douxunchen3498 2014-02-15 08:05
浏览 103
已采纳

为什么“$ this - > _ query-> execute()”总是评估为false?

I have, in a db.php file, the following code:

    public function query($sql, $params = array()){
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)){
        $x = 1;
        if(count($params)){
            foreach($params AS $pa){
                $this->_query->bindValue($x, $pa);
                $x++;
            }
        }
        #MASSIVE ERROR
        #correctthis
        if($this->_query->execute()){
            echo 'success';
            $this->_result = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_query = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }

    return $this;
}

public function error(){
    return $this->_error;
}

My problem is that $this->_query->execute() always is false, which means $_error is always being set to true. I can't get it to work, even though there doesn't seem to be anything wrong with it.

The script enters the prepare (I tested by echoing), which means it prepared successfully. It also enters the foreach loop so the values must be getting bound. But it just can't seem to execute. Why?

Edit:

I use DB::getInstance()->query("SELECT email FROM user_credentials WHERE user_id = ?", array(1)) to call the query, and this is what getInstance looks like:

    public static function getInstance(){
    if(!isset(self::$_instance)){
        self::$_instance = new DB();
    }
    return self::$_instance;
}
  • 写回答

3条回答 默认 最新

  • dongmei425373 2014-02-15 08:11
    关注

    Make your function this way

    public function queryAll($sql, $params = array(), $method = PDO::FETCH_OBJ)
    {
        $stmt = $this->_pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll($method);
    }
    

    or, if you prefer method chaining, then this way

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

    Then set PDO in exception mode, and you will be always informed of any error occurred. To so so add this code in constructor

    $this->_pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    

    The rest of your code is useless, inflexible, error-prone and sometimes plainly wrong.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿