PDO 错误: SQLSTATE[HY000]: 常规错误: 2031

2022-08-30 18:00:35

我得到了这个烦人的错误,虽然我知道我为什么会得到它,但我不能为我的生活找到解决方案。

if ($limit) {
   $sth->bindValue(':page', $page - 1, PDO::PARAM_INT);
   $sth->bindValue(':entries_per_page', $page * $entries_per_page, PDO::PARAM_INT);
}

$sth->execute($criteria);

查询包含占位符 ()。但是要添加这些 LIMIT 占位符,我需要使用手动方法 (),否则引擎会将它们转换为字符串。:placeholderbindValue

我没有收到参数数量无效错误,因此所有占位符都已正确绑定(我假设)。

查询:

SELECT `articles`.*, `regional_municipalities`.`name` AS `regional_municipality_name`, 
       `_atc_codes`.`code` AS `atc_code`, `_atc_codes`.`name` AS `substance`
FROM `articles`
LEFT JOIN `_atc_codes`
ON (`_atc_codes`.`id` = `articles`.`atc_code`)
JOIN `regional_municipalities`
ON (`regional_municipalities`.`id` = `articles`.`regional_municipality`)
WHERE TRUE AND `articles`.`strength` = :strength
GROUP BY `articles`.`id`
ORDER BY `articles`.`id`
LIMIT :page, :entries_per_page

所有占位符值都驻留在$criteria中,除了最后两个 LIMIT,我手动将其绑定。bindValue()


答案 1

当一个人绑定两个具有相同参数名称的值时,可能会发出相同的错误 2031,例如:

  • $sth->bindValue(':colour', 'blue');
  • $sth->bindValue(':colour', 'red');

..所以,要小心。


答案 2

不能使用 。使用任一或;如果将参数传递给 ,这些参数将使 PDO 忘记已通过 绑定的参数。->bind*->execute($params)execute()->bind*


推荐