首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BindParam()不能正常工作

BindParam()不能正常工作
EN

Stack Overflow用户
提问于 2016-08-29 10:41:39
回答 2查看 490关注 0票数 1

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

代码语言:javascript
复制
    // 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;

    }

我就是这样调用这个方法的

代码语言:javascript
复制
$db->query("SELECT * FROM users WHERE username = :username AND id = :id ", array(':username' => 'sayantan94', ':id' => 1));

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

代码语言:javascript
复制
$db->query("SELECT * FROM users WHERE username = :username", array(':username' => 'sayantan94'));

或者这个

代码语言:javascript
复制
$db->query("SELECT * FROM users WHERE id = :id ", array(':id' => 1));

我正在得到正确的结果。我的密码怎么了??

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-29 11:04:30

除了在另一个答案中所说的,你的大部分代码要么是无用的,要么是有害的。事实上,你只需要这几行

代码语言:javascript
复制
public function query($sql, $params = array())
{
    $query = $this->_pdo->prepare($sql);
    $query->execute($params);
    return $query; 
}

它将完成您的函数所做的一切,但是没有那么多代码,也没有不良的副作用。假设您将在一个循环中运行一个嵌套查询。在第二次查询执行之后,$this->_results变量是什么?在这样的函数中,不应该存在与特定查询相关的类变量.

另外,

  • 不需要手动检查准备结果- PDO本身将引发异常
  • 不需要_error变量,因为它是非常无用的,而PDO本身的异常则更有用和更丰富
  • 不需要在循环中绑定- execute()可以同时绑定所有参数。
  • 不需要测试$params数组- execute()也会接受空数组。
  • 不需要返回fetchAll() restult -您可以在以后再这样做,方法是将它像下面这样的$data = $db->query($sql, $params)->fetchAll();链接起来
  • 不需要rowCount() -您可以一直只计算从fetchAll()返回的数组
票数 2
EN

Stack Overflow用户

发布于 2016-08-29 10:58:41

您的预测是false,$value按值计算,因为bindParam需要&$变量,所以进行引用,尝试如下:

代码语言:javascript
复制
if(count($params)) {
   foreach($params as $param => &$value) {
       $this->_query->bindParam($param, $value);
   }
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39204270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档