BindParam() 无法正常工作

BindParam() not working properly

在我的数据库 class 中,我有一个方法 query(),它将 SQL 语句和参数作为参数并在数据库中运行它们。

    // the parameters are the sql statement and the values, returns the the current object
    // the result set object can be accessed by using the results() method

    public function query($sql, $params = array()) {

        $this->_error = false;  // initially the error is set to false

        if($this->_query = $this->_pdo->prepare($sql)) {

            // if the parameters are set, bind it with the statement
            if(count($params)) {
                foreach($params as $param => $value) {
                    $this->_query->bindParam($param, $value);
                }
            }

            // if the query is successfully executed save the resultset object to the $_results property
            // and store the total row count in $_count
            if($this->_query->execute()) {
                $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
                $this->_count = $this->_query->rowCount();
            } else {
                $this->_error = true;
            }
        }

        return $this;

    }

这就是我调用方法的方式

$db->query("SELECT * FROM users WHERE username = :username AND id = :id ", array(':username' => 'sayantan94', ':id' => 1));

但是当我 print_r() 结果集时,我得到一个空数组。但是如果我这样做

$db->query("SELECT * FROM users WHERE username = :username", array(':username' => 'sayantan94'));

或这个

$db->query("SELECT * FROM users WHERE id = :id ", array(':id' => 1));

我得到了正确的结果。我的代码有什么问题??

你foreach为false,$value by value,因为bindParam需要&$variable,做个参考,试试这个:

if(count($params)) {
   foreach($params as $param => &$value) {
       $this->_query->bindParam($param, $value);
   }
}

http://php.net/manual/en/pdostatement.bindparam.php

除了其他答案中所说的,您的大部分代码不是无用就是有害。其实你只需要这几行

public function query($sql, $params = array())
{
    $query = $this->_pdo->prepare($sql);
    $query->execute($params);
    return $query; 
}

它会做你的函数做的所有事情,但没有那么多代码,也没有讨厌的副作用。想象一下,您将 运行 循环中的嵌套查询。在第二次查询执行后,你的 $this->_results 变量变成了什么?在这样的函数中 不应有与特定查询相关的 class 变量。

此外,

  • 无需手动检查准备结果 - PDO 将自行抛出 异常
  • 不需要 _error 变量,因为它没什么用,而 PDO 自己的异常更有用且信息量更大
  • 无需循环绑定 - execute() 可以一次绑定所有参数
  • 无需测试 $params 数组 - execute() 也将接受空数组。
  • 不需要 return fetchAll() 结果 - 您以后可以随时这样做,就像这样链接它 $data = $db->query($sql, $params)->fetchAll();
  • 不需要 rowCount() - 您总是可以只计算从 fetchAll()
  • 编辑的数组 return