这有点奇怪,我很可能完全错误地编码 - 因此为什么我在两天内两次完全相同的错误,在一个完全不同的脚本部分。我正在使用的代码如下:
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的新手,但基本上我试图传递一系列约束,例如
array( 'active' => 1, 'name' => 'James' )
并返回表WHERE active = 1 AND name = 'James'
中的所有行
如果我使用这个数组,那么从第一个
var_dump( )
执行的SQL是SELECT * FROM {table} WHERE active = :active AND name = 'James'
- 完全符合我的预期。绑定参数打印'Binding active to 1'和'Binding name to James' - 完全符合预期。这些行存在于数据库中,但是对$ results的第二次var_dump()
调用没有输出任何内容 - 即没有返回任何行。
如果我传递一个单一约束的数组,例如
array( 'active' => 1 )
,这很好用。似乎每当传递多个约束时它就会停止工作。
答案 0 :(得分:10)
这是因为bindParam
通过绑定到变量来工作,并且您正在为多个值重用变量($value
)。请尝试使用bindValue
。
甚至更好;将值作为数组传递给execute
。这使得语句无状态,这在编程中通常是一件好事。
答案 1 :(得分:0)
如上所述,使用bindValue
代替bindParam
肯定会实现这一目标。但是,在最近花了相当多的时间来解决这个问题后,我发现了另一种解决方案。以下是如何使用bindParam在foreach循环中完成PDO变量绑定:
从原始帖子中替换以下行:
$PDOStatement->bindParam( $field, $value );
......用这个:
$PDOStatement->bindParam( $field, $constraints[$field] );
使用$value
而不是绑定$array_name[$array_key]
。这样做是因为你现在绑定到一个唯一的变量而不是在循环的每次传递中重用的变量。
然而,用作占位符的变量$field
显然不需要是唯一变量。我还没有彻底研究过这个问题,但是即使使用了bindParam,用作占位符的变量也会立即被解析(而不是被指定为变量引用)。
此外,由于您不再需要直接访问$value
,您也可以将其替换为:
foreach( $constraints as $field => $value ) {
......用这个:
foreach (array_keys($constraints) as $field) {
这是可选的,因为没有这个改变它将正常工作。在我看来,它看起来更干净,因为后来为什么$value
被分配但从未使用过,可能会让人感到困惑。