所以我正在尝试进行条件更新,但我似乎在将数据与语句绑定(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/