PDOStatement :: execute():SQLSTATE [HY093]:参数号无效:绑定变量数与令牌数不匹配

时间:2014-10-01 14:55:50

标签: php mysql pdo

我收到错误消息:

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /var/www/calendar/insert.php on line 17

但我不明白我做错了什么。

我有一个使用6个绑定的INSERT声明,我绑定了6,那么不匹配的地方在哪里?

代码

插入

$stmt = $dbh->prepare("INSERT INTO bookings (forename, surname, badge, department, start, end) VALUES (:forename, :surname, :badge, :department, STR_TO_DATE(:dp1,'%Y-%m-%d'), STR_TO_DATE(:dp2,'%Y-%m-%d'))");

绑定

foreach ($_POST as $key => $value) {
  $stmt->bindParam('$key', $value);
  echo "Binding $key as $value <br>";
}

输出:

Binding forename as John
Binding surname as Doe
Binding badge as 1 
Binding department as Days 
Binding dp1 as 2014-10-06 
Binding dp2 as 2014-10-10 

2 个答案:

答案 0 :(得分:2)

由于您使用的是单引号,因此不会插入变量,您需要将它们更改为双引号:

foreach ($_POST as $key => $value) {
  $stmt->bindParam(":$key", $_POST[$key]); // assuming $key matches those named placeholders

}

编辑:对于评论的良好见解,如同雄辩地说明@marc,您只需使用$value即可获得最后一个值。

答案 1 :(得分:0)

  • 无需单引号'
  • 无需冒号:
  • 使用bindValue代替

foreach ($_POST as $key => $value) {
    $stmt->bindValue($key, $value);
}