2017-11-25 259 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需要& $变量):