我的查询有错误时无法捕获PDOException,为什么?

时间:2014-03-04 21:24:11

标签: php mysql codeigniter exception pdo

我正在使用CodeIgniter,我有以下代码从数据库中获取所有记录:

try {
     $sth = $this->db->conn_id->prepare($query);  
     $sth->bindParam(':something', $something, PDO::PARAM_INT);
     $sth->execute();  
     //...
    }
     catch (PDOException $e) {
            //error goes here
    } 

我在$ query上犯了一个错误,我把LIMIT放在ORDER BY之前。即:

SELECT `something` from some_table LIMIT 0, 10 ORDER BY some_other_field DESC (bad)

而不是

SELECT `something` from some_table ORDER BY some_other_field DESC LIMIT 0, 10 (correct)

但是当我运行我的代码时,我没有抓到任何PDOException(只返回没有结果),即使我设置PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION

那为什么呢?那么如何捕获查询错误?

更新1 :在CodeIgniter pdo_driver.php文件中,我已经更改了db_connect()和db_pconnect():

function db_connect()
    {
        $this->options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
        $this->options['PDO::ATTR_EMULATE_PREPARES'] = FALSE;

        return new PDO($this->hostname, $this->username, $this->password, $this->options);
    }

    // --------------------------------------------------------------------

    /**
     * Persistent database connection
     *
     * @access  private called by the base class
     * @return  resource
     */
    function db_pconnect()
    {
        $this->options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
        $this->options['PDO::ATTR_PERSISTENT'] = TRUE;

        return new PDO($this->hostname, $this->username, $this->password, $this->options);
    }

但是我不会捕获任何PDOException,除非我添加: $ this-> db-> conn_id-> setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION); 在我运行execute()之前。为什么呢?

0 个答案:

没有答案