php - 条件 PDO bindParam 更新

标签 php mysql pdo

所以我正在尝试进行条件更新,但我似乎在将数据与语句绑定(bind)时遇到了问题。

功能:

function updateEditor($email, $first, $last, $id){
global $DBH;
$response = false;
$upemail = "";
$upfirst = "";
$uplast = "";

$stmt = "SELECT memEmail, memFirst, memLast FROM MEMBER WHERE memID = :id";
try{
    $STH = $DBH->prepare($stmt);
    $STH->bindParam(':id', $id);
    $STH->execute();

    $STH->setFetchMode(PDO::FETCH_ASSOC);
    $row = $STH->fetch();
    if($row['memEmail'] != $email){ $upemail = $email;}
    if($row['memFirst'] != $first){ $upfirst = $first;}
    if($row['memLast'] != $last){ $uplast = $last;}

}catch(PDOException $e) {
    echo $e->getMessage() . "first";

}
$stmt .= "UPDATE MEMBER SET ";
if(!empty($upemail)){
    $stmt .= "memEmail = :memEmail";
    if(!empty($upfirst) || !empty($uplast)){
        $stmt .= ", ";
    }
}
if(!empty($upfirst)){
    $stmt .= "memFirst = :memFirst";
    if(!empty($uplast)){
        $stmt .= ", ";
    }
}
if(!empty($uplast)){
    $stmt .= "memLast = :memLast";
}
if(empty($upemail) && empty($upfirst) && empty($uplast)){
    return false;
}else{
    $stmt .= " WHERE memID = :id";
}

try{
    $STH = $DBH->prepare($stmt);
    if(!empty($upemail)){$STH->bindParam(':memEmail', $upemail);}else{$STH->bindParam(':memEmail', $row['memEmail']);}
    if(!empty($upfirst)){$STH->bindParam(':memFirst', $upfirst);}else{$STH->bindParam(':memFirst', $row['memFirst']);}
    if(!empty($uplast)){$STH->bindParam(':memLast', $uplast);}else{$STH->bindParam(':memLast', $row['memLast']);}
    $STH->bindParam(':id', $id);
    $STH->execute();

    $STH->setFetchMode(PDO::FETCH_ASSOC);

    $response = true;
}catch(PDOException $e) {
    echo $e->getMessage() . "second";
    $response = $e->getMessage() . "second";

}
return $response;
}

到目前为止,我已经尝试使用 ? 和上面的代码将变量放入语句中。我不断收到的错误是:

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

最佳答案

这里:

$stmt .= "UPDATE MEMBER SET ";

您将 UPDATE 附加到先前的 $stmt 字符串。你最终会得到:

$stmt = "SELECT memEmail, memFirst, memLast FROM MEMBER WHERE memID = :idUPDATE MEMBER SET "; // and the rest

导致多一个标识符 (:idUPDATE)。

删除 . 以在此字符串中开始新查询。

$stmt = "UPDATE MEMBER SET ";

注意:
你让这种方式太复杂了。跳过对空值的检查,仅在更新数据集时更新所有列,通过检查已更改的内容和未更改的内容不会获得任何 yield 。

关于php - 条件 PDO bindParam 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35995727/

相关文章:

php - PDO lastInsertID() 由于在一次调用中运行多个查询而失败

PHP - 使用 PDO 将字符串数组绑定(bind)到 IN() 子句

php - 使用 PHP 正则表达式获取特定的 "<elm>..</elm>"?

PHP 如何读取特定的单词和行然后添加到 MySQL 数据库

sql - 计划的数据库设计

PHP:是否可以将数据库层实现为单例?代码里面

mysql - 使用 PDO 和 LIKE 不起作用,为什么?

php - 表达式引擎和 CSS

php - Symfony2 无法连接到 '192.168.1.50' (113) 上的 MySQL 服务器

php - 如何使用laravel和mysql查看基于日期范围的数据