【问题标题】:PDO prepared query error: number of bound variables does not match number of tokensPDO 准备查询错误:绑定变量的数量与标记的数量不匹配
【发布时间】:2015-03-04 08:36:22
【问题描述】:

我正在将其他人编写的一些未准备好的 PDO 查询转换为已准备好的 PDO 查询。所有未定义的变量和已发布的变量实际上都在此例程中执行;为了简洁起见,我省略了他们的定义。证据在布丁中,对于此处提供的现有的、未准备好的查询,有效:

$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

我做错了什么?在我看来,好像每个参数都被考虑在内;是什么导致解释器声称存在令牌计数不匹配?

【问题讨论】:

  • 准备好的语句上的占位符不需要引号,并删除多余的addlashes

标签: php mysql pdo


【解决方案1】:

去掉占位符中的双引号

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

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

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

【讨论】:

  • 为了完整起见,可能值得添加的是,带有引号的命令尝试插入文字字符串 ":title" 等(或者,如果启用了 ANSI_QUOTES SQL 模式,由这些名称标识的模式对象的值(几乎可以肯定不存在)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-10
相关资源
最近更新 更多