PHP中的bindParam覆盖错误
时间:2020-03-06 14:51:15 来源:igfitidea点击:
这有点奇怪,我很可能会编写完全错误的代码,因此,为什么我在两天内在脚本的完全不同的部分中两次遇到相同的错误。我正在使用的代码如下:
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'
如果我使用此数组,则从第一个执行的SQL
var_dump( )
是
SELECT * FROM {table} WHERE active = :active AND name = 'James'
完全符合我的期望。绑定参数将完全按预期方式打印"将活动绑定到1"和"将名称绑定到James"。这些行存在于数据库中,但第二行
var_dump()
调用$ results不会输出任何内容,即不返回任何行。
如果我传递单个约束的数组,例如
array( 'active' => 1 )
,效果很好。似乎是在通过多个约束时,它才停止工作。
解决方案
这是因为bindParam
通过绑定到变量来工作,并且我们正在将变量($ value
)重用于多个值。尝试使用bindValue
。
甚至更好;将值作为数组传递给" execute"。这使该语句变为无状态,这在编程中通常是一件好事。