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条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了