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

时间:2014-02-15 08:05:57

标签: php mysql object pdo

我在db.php文件中有以下代码:

    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;
}

我的问题是$this->_query->execute()总是为假,这意味着$ _error总是设置为true。我无法让它发挥作用,即使它似乎没有任何问题。

脚本进入准备(我通过echo测试),这意味着它已成功准备。它也会进入foreach循环,因此必须绑定值。但它似乎无法执行。为什么呢?

编辑:

我使用DB::getInstance()->query("SELECT email FROM user_credentials WHERE user_id = ?", array(1))来调用查询,这就是getInstance的样子:

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

3 个答案:

答案 0 :(得分:0)

我认为您与数据库没有正确连接。查看连接功能是否正常工作。如果你从在线教程中尝试这个,那就像下面的代码:

$this->_pdo = new PDO('mysql:host=' . Config::get 
('mysql/host') . ';dbname=' . Config::get('mysql/db'), 
Config::get('mysql/username'), Config::get('mysql/password')); 

答案 1 :(得分:-1)

尝试此操作以了解查询返回的特定错误。我只修改了 else 块。

    #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;
        echo $this->_query->errorInfo()[2];
    }

答案 2 :(得分:-1)

以这种方式使你的功能

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

或者,如果您更喜欢方法链接,那么就这样

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

然后在异常模式下设置PDO,并始终通知您发生的任何错误。为此,请在构造函数

中添加此代码
$this->_pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

你的其余代码是无用的,不灵活的,容易出错的,有时甚至是明显的错误。

相关问题