条件PDO bindParam更新

时间:2016-03-14 18:52:30

标签: php mysql pdo

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

功能:

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]:参数号无效:绑定变量数与令牌数不匹配

2 个答案:

答案 0 :(得分:3)

下面:

$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 ";

注意:
你这样做太复杂了。跳过检查空值,只需在更新数据集时更新所有列,通过检查已更改的内容和未更改的内容,您无法获得任何内容。

答案 1 :(得分:0)

除了@Gerald Schneider的回答,你在这两种情况下都设置了参数(if / else)

if(!empty($upemail)){$STH->bindParam(':memEmail', $upemail);}else{$STH->bindParam(':memEmail', $row['memEmail']);}

但是只在一种情况下定义参数

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";
}

没有其他条件

相关问题