有谁能看到这个脚本有什么问题?我已经验证数据是在$ _POST数组中,并且查询字符串也是正确形成的,但由于某种原因,当执行此操作时,要更新的列将在数据库中清空。
/* 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 :(得分: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需要& $ variable):