这有些奇怪,我完全可以将它编码为完全错误的 - 因此,为什么我在两天内在脚本的完全不同部分碰到了相同的错误两次。我使用的代码如下:在PHP中bindParam覆盖错误
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的内容不会输出 - 即不返回任何行。
如果我传递一个单个约束的数组,例如
array('active' => 1)
,这工作非常好。似乎只要通过多个约束就会停止工作。