2017-11-25 334 views
-2

任何人都可以看到這個腳本有什麼問題嗎?我已經驗證數據是在$ _POST數組中,並且查詢字符串也是正確地形成的,但是由於某種原因,當它被執行時,要更新的列在數據庫中被清空。PDO UPDATE查詢刪除值而不是更新

/* Get the ID for the house to be modified by using a hidden-field 'hiddenDescription' */ 
$stmt = $db->prepare('SELECT id FROM talot WHERE kuvaus = :description'); 
$stmt->bindParam(':description', $_POST['hiddenDescription'], PDO::PARAM_STR); 
$stmt->execute(); 
if($row = $stmt->fetch(PDO::FETCH_ASSOC)){ 
    // The column names in the database 
    $col_names = array("kaupunki", "osoite", "pintaAla", "koko", "vuosi", "hinta", "otsikko", "kuvaus", "valittaja"); 
    $comma = ","; 
    $i = 0; 
    $unprepared = 'UPDATE talot SET '; 
    /* Go through the POST -array and add the column name and :$key (for binding) into the query string. Also add comma */ 
    foreach($_POST as $key => $value){ 
     if(!empty($_POST[$key])){ 
      // Skip hiddenDescription 
      if($key != 'hiddenDescription'){ 
       $unprepared .= "$col_names[$i] = :$key".$comma; 
      } 
      // If $key was hiddenDescription decrement $i; 
      else{ 
       $i--; 
      } 
     } 
     $i++; 
    } 
    // chop the last comma. 
    $prepared = chop($unprepared, ','); 
    $prepared .= ' WHERE id = :id'; 
    $stmt = $db->prepare($prepared); 
    $i = 0; 
    /* Go through the POST -array and bind values that are not empty. Again skip hiddenDescription. */ 
    foreach($_POST as $key => $value){ 
     if(!empty($value)){ 
      if($key != 'hiddenDescription'){ 
       $stmt->bindParam(":$key", $value, PDO::PARAM_STR); 
      } 
      else{ 
       $i--; 
      } 
     } 
     $i++; 
    } 
    // Bind the ID received in the first database query. 
    $id = (int)$row['id']; 
    $stmt->bindParam(":id", $id, PDO::PARAM_INT); 
    $result = $stmt->execute(); 
    if($result){ 
     echo 1; 
    } 

謝謝!

+0

呼應的SQL語句,並顯示它的返回 – Akintunde007

+0

對象(PDOStatement)#3(1){「0」 ryString「] => string(49)」UPDATE talot SET osoite =:address WHERE id =:id「 } }更新talot SET osoite =:地址WHERE id =:id –

+0

在PHP中:echo var_dump($ stmt) 。 「:」。 $準備; –

回答

0

好吧..解決了這個呵呵。

此:

foreach($_POST as $key => $value){ 
    if(!empty($value)){ 
     if($key != 'hiddenDescription'){ 
      $stmt->bindParam(":$key", $value, PDO::PARAM_STR); 
     } 
     else{ 
      $i--; 
     } 
    } 
    $i++; 
} 

更改爲此:

foreach($_POST as $key => &$value){ 
if(!empty($value)){ 
    if($key != 'hiddenDescription'){ 
     $stmt->bindParam(":$key", $value, PDO::PARAM_STR); 
    } 
    else{ 
     $i--; 
    } 
} 
$i++; 

}

(bindParam需要& $變量):