PDO更新不替换预准备语句中的占位符

时间:2012-07-04 16:54:14

标签: php mysql pdo

我尝试使用以下代码更新表格。如果我将WHERE temp_booking_id = ':temp_booking_id'");更改为使用实际的当前会话temp_id,则查询将会运行,但会将占位符添加到表中(例如:签出)作为值。

$data保留正确的值,但不替换占位符。

一直盯着这几个小时,我不能解决问题所在,并环顾四周,但没有找到解决办法。

PDOStatement:errorInfo()正在返回

  

PDOStatement :: errorInfo():Array([0] => 00000)

如果我删除占位符周围的引号,则返回

  

PDOStatement :: errorInfo():Array([0] => HY093)

有什么想法吗?

try {
  $data = array(
    'temp_booking_id' => $_SESSION['temp_id'],
    'check_in' => $in,
    'check_out' => $out, 
    'adults' => $a,
    'children1' => $c1,
    'children2' => $c2,
    'infants' => $i,
    'cots' => $c,
    'promo_code' => $pc
 );

 $STH = $DBH->prepare("UPDATE b_temp_booking 
   SET check_in = ':check_in',
   check_out = ':check_out',
   adults = ':adults',
   children1 = ':children1',
   children2 = ':children2',
   infants = ':infants',
   cots = ':cots',
   promo_code = ':promo_code' 
   WHERE temp_booking_id = ':temp_booking_id'");

 $STH->execute($data);

 echo "\nPDOStatement::errorInfo():\n";
 $arr = $STH->errorInfo();
 print_r($arr);

} catch(PDOException $e) {
  echo 'ERROR: ' . $e->getMessage();
}

1 个答案:

答案 0 :(得分:5)

嗯,似乎你的SQL语句不需要单引号。例如,您可以尝试运行此块:

   $STH = $DBH->prepare("UPDATE b_temp_booking 
   SET check_in = :check_in,
   check_out = :check_out,
   adults = :adults,
   children1 = :children1,
   children2 = :children2,
   infants = :infants,
   cots = :cots,
   promo_code = :promo_code 
   WHERE temp_booking_id = :temp_booking_id");

查看有关PDO准备语句的PHP手册:http://www.php.net/manual/en/pdo.prepared-statements.php 在这里看来,在命名占位符周围不需要引号。

另外,请尝试按照他们使用bindParam()方法的示例:

$STH->bindParam(':temp_booking_id', $temp_booking_id);

$temp_booking_id = $_SESSION['temp_id']; // Not sure how binding the environment variable will work, so decoupling it.

$STH->bindParam(':check_in', $in);
$STH->bindParam(':check_out', $out); 
$STH->bindParam(':adults', $a);
$STH->bindParam(':children1', $c1);
$STH->bindParam(':children2', $c2);
$STH->bindParam(':infants', $i);
$STH->bindParam(':cots', $c);
$STH->bindParam(':promo_code', $pc);

准备好执行时,可以运行以下行:

$STH->execute();

检查一下,看看参数的绑定是否是您正在寻找的。