PDO准备了查询错误:绑定变量的数量与令牌数量不匹配

时间:2015-03-04 08:36:23

标签: php mysql pdo

我正在将其他人写的一些毫无准备的PDO查询转换为准备PDO查询。事实上,所有未定义的变量和POSTed变量都在此例程中执行;为了简洁起见,我省略了他们的定义。证据在布丁中,因为这里提供的现有的,未准备好的查询有效:

$query = sprintf('INSERT INTO galleries (title, description, meta_description, published) VALUES ("%s", "%s", "%s", %d)', addslashes($_POST['gallery_name']), addslashes($_POST['gallery_description']), addslashes($_POST['gallery_meta_description']), intval($published));
$connection->query($query);

但是,我将此代码转换为完全准备好的查询,此处不会:

$query = 'INSERT INTO galleries (title, description, meta_description, published) VALUES (":title", ":description", ":meta_description", :published)';

$PdoStatementObject = $connection->prepare($query);

$title = addslashes($_POST['gallery_name']);
$description = addslashes($_POST['gallery_description']);
$meta_description = addslashes($_POST['gallery_meta_description']);
$published_int = intval($published);

$PdoStatementObject->bindValue(":title", $title, PDO::PARAM_STR);
$PdoStatementObject->bindValue(":description", $description, PDO::PARAM_STR);
$PdoStatementObject->bindValue(":meta_description", $meta_description, PDO::PARAM_STR);
$PdoStatementObject->bindValue(":published", $published_int, PDO::PARAM_INT);

$PdoStatementObject->execute();

生成的错误消息是:

PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

我做错了什么?它看起来好像每个参数都被考虑在内;是什么导致口译员声称令牌计数不匹配?

1 个答案:

答案 0 :(得分:1)

摆脱占位符中的双引号

(":title", ":description", ":meta_description", :published)

(:title, :description, :meta_description, :published)

检查文档http://php.net/manual/en/pdo.prepared-statements.php