PDO错误:“参数号无效:参数未定义”

时间:2012-06-15 10:27:06

标签: php mysql pdo prepared-statement parameterized-query

我正在尝试使用带有数组形式参数的简单MySQL插入查询。它一直告诉我参数的数量是错误的。我尝试了以下内容,都产生了同样的错误:

$stmt3 = $link->prepare('INSERT INTO messages VALUES(null, :room, :name, :message, :time, :color)');
$stmt3->execute(array(':room' => $Clean['room'],':name' => $Clean['name'],':message' => $Clean['message'],':time' => $time,':color:' => $Clean['color']));

$stmt3 = $link->prepare('INSERT INTO messages VALUES(:null, :room, :name, :message, :time, :color)');
$stmt3->execute(array(':null' => null, ':room' => $Clean['room'],':name' => $Clean['name'],':message' => $Clean['message'],':time' => $time,':color:' => $Clean['color']));

以及专门声明列以避免空插入:

$stmt3 = $link->prepare('INSERT INTO messages (room, name, message, time, color) VALUES(:room, :name, :message, :time, :color)');
$stmt3->execute(array(':room' => $Clean['room'],':name' => $Clean['name'],':message' => $Clean['message'],':time' => $time,':color:' => $Clean['color']));

这是我第一次使用PDO(我通常使用mysqli,但我当前的共享主机没有mysqlnd插件,阻止我使用prepare(),所以从这个角度来看任何见解都是值得赞赏的。

2 个答案:

答案 0 :(得分:19)

问题 - 你会踢自己 - 是:color

调用execute()时为该标记传递的值的数组键名为:color:。删除尾随:(我猜这只是一个错字)。

$stmt3->execute(array(
    ':room' => $Clean['room'],
    ':name' => $Clean['name'],
    ':message' => $Clean['message'],
    ':time' => $time,
    ':color' => $Clean['color'],
    ));

答案 1 :(得分:-2)

我可能在这里错了,但据我所知你需要这样做:

$stmt3->bindParam(':room', $Clean['room']);
$stmt3->bindParam(':name', $Clean['name']);
//and so on

但作为个人偏好,我总是这样做

$stmt3 = $link->prepare('INSERT INTO messages VALUES(null, ?, ?, ?, ?, ?)');
$stmt3->execute(array($Clean['room'], $Clean['name'], $Clean['message'], $time, $Clean['color']))