2016-03-14 42 views
0

所以我試圖做一個有條件的更新,但我似乎有問題與聲明綁定數據。有條件的PDO bindParam更新

功能:

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]:無效的參數編號:綁定變量的數量不匹配的令牌數量

+0

對不起,這是測試。錯誤來自第二個'try'語句 – smurfAccount

+0

您正在設置if和else語句中的參數。但是在查詢中,只有在非空的情況下才包含參數。 –

回答

3

這裏:

$stmt .= "UPDATE MEMBER SET "; 

你追加更新到以前的$stmt字符串。您將以:

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

在一個標識符更多(:idUPDATE)。

刪除.以在此字符串中開始新查詢。

$stmt = "UPDATE MEMBER SET "; 

注:
你正在這樣太複雜了。跳過對空值的檢查,只是在更新數據集時更新所有列,通過檢查哪些內容已更改以及哪些內容尚未優先獲得任何內容。

+0

我把它放在沒有'.'同樣的錯誤。我改變了第一個'stmt'的名字,並且仍然會出現相同的錯誤 – smurfAccount

+0

呃,在你準備好之前echo'$ stmt',並將它與你的綁定進行比較。 –

0

除了@Gerald施耐德回答,您設置帕拉姆在兩種情況下(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"; 
} 

所定義的參數有沒有別的條件