2013-06-24 51 views
15

我得到这个令人讨厌的错误,虽然我有一个为什么我得到它的想法,我不能为我的生活找到一个解决方案。PDO错误:SQLSTATE [HY000]:一般错误:2031

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); 

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

我没有得到无效的参数数量的错误,所以所有的占位符已被正确绑定(我假设)。

查询:

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 

所有占位符值驻留在$标准,除了最后两所限,我手动bindValue()绑定。

+1

尝试在谷歌搜索“PDO结合极限参数” –

+0

1)它会一直不错,包括人类可读的错误信息,而不是仅仅的神秘代码,2)显示您的实际查询,以便我们可以看到错误源于哪里。 – deceze

+0

@deceze如果在那里有任何人类可读的消息,我会:a)现在可能已经解决了它,b)如果没有,然后将它包括在这里。这是完整的错误信息,相信我。 – silkfire

回答

17

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

3

the manual

public bool PDOStatement::execute ([ array $input_parameters ])

Execute the prepared statement. If the prepared statement included parameter markers, you must either:

  • call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers

  • or pass an array of input-only parameter values

你需要选择的方法。你不能混用两者。

+0

我不能使用'bindParam' /'bindValue'作为其他值...叹。 – silkfire

+0

@silkfire请参阅http://stackoverflow.com/questions/10014147/limit-keyword-on-mysql-with-prepared-statement-maybe-still-a-bug/10014200#10014200了解其他想法。 –

+0

'PDO :: ATTR_EMULATE_PREPARES,true)' - 不应该**启用**模拟准备?我认为这是相反的方式,非常具有误导性。 – silkfire

13

此相同的错误2031时能发出一个绑定两个值具有相同参数的名称,如在:

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

..所以,要小心了。

+0

这个答案拯救了我的一天! – JWizard

2

如果您尝试运行带有占位符的查询,而不是准备statment如

$stmt = $db->query('SELECT * FROM tbl WHERE ID > ?'); 

,而不是

$stmt = $db->prepare('SELECT * FROM tbl WHERE ID > ?'); 
-1

异常也发生(至少在MySQL这个例外情况也出现/ PDO)当您尝试更新AUTO_INCREMENT字段时。

2

这不完全是一个答案,但这个错误也发生,如果你试图用一个字连字符作为占位符,例如:

$sth->bindValue(':page-1', $page1);

所以最好使用

$sth->bindValue(':page_1', $page1);

0

如果您有不匹配的参数,则会发生这种情况。例如:

$q = $db->prepare("select :a, :b"); 
$q->execute([":a"=>"a"]); 
相关问题