PHP中的bindParam覆盖错误 [英] Error with bindParam overwriting in PHP
问题描述
这有点奇怪,我很可能会编写完全错误的代码-因此,为什么我在两天内在脚本的完全不同的部分中两次遇到相同的错误.我正在使用的代码如下:
This is a bit of a weird one, and I could well be coding this completely wrong - hence why I've hit the same error twice in two days, in completely different parts of a script. The code I'm using is below:
public function findAll( $constraints = array() ) {
// Select all records
$SQL = 'SELECT * FROM ' . $this->tableName;
// See if there's any constraints
if( count( $constraints ) > 0 ) {
$SQL .= ' WHERE ';
foreach( $constraints as $field => $value ) {
$SQL .= $field . ' = :' . $field . ' AND ';
}
}
// Remove the final AND and prepare the statement
$SQL = substr( $SQL, 0, -5 );
$PDOStatement = $this->PDO->prepare( $SQL );
// Loop through constraints and bind parameters
foreach( $constraints as $field => $value ) {
print 'Binding ' . $field . ' to ' . $value . '
';
$PDOStatement->bindParam( $field, $value );
}
$PDOStatement->execute();
var_dump($PDOStatement);
while ( $results = $PDOStatement->fetch( PDO::FETCH_ASSOC ) ) {
var_dump($results);
}
}
我对使用PDO很陌生,但基本上我正尝试传递一系列约束,例如
I'm pretty new to using PDO, but basically I'm attempting to pass an array of constraints e.g.
array( 'active' => 1, 'name' => 'James' )
并返回表
WHERE active = 1 AND name = 'James'
如果我使用此数组,则从第一个
If I use this array, the SQL executed from the first
var_dump( )
执行的SQL是
SELECT * FROM {table} WHERE active = :active AND name = 'James'
-完全符合我的期望.绑定参数将完全按预期打印活动绑定到1"和将名称绑定到James".这些行存在于数据库中,但是对$ results的第二个
- exactly as I expect. The bound parameters prints 'Binding active to 1' and 'Binding name to James' - exactly as expected. The rows exist in the database, and yet the second
var_dump()
调用什么也不输出-即,没有返回行.
call for $results outputs nothing - i.e. no rows are returned.
如果我传递一个单一约束的数组,例如
If I pass an array of a single constraint, e.g.
array( 'active' => 1 )
,这很好用.似乎是在多个约束都通过的情况下,它才停止工作.
, this works perfectly fine. It appears to be whenever multiple constraints are passed that it stops working.
推荐答案
这是因为 bindParam
通过绑定到变量来工作,并且您正在将变量($value
)重用于多个值.尝试使用 bindValue
.
That's because bindParam
works by binding to a variable, and you are re-using the variable ($value
) for multiple values. Try with bindValue
instead.
甚至更好;而是将值作为数组传递给 execute
.这使该语句变为无状态,这在编程中通常是一件好事.
Or even better yet; Pass the values as an array to execute
instead. This makes the statement stateless, which is generally a good thing in programming.
这篇关于PHP中的bindParam覆盖错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!