当我的查询有错误时无法捕获PDOException,为什么?
我使用的是CodeIgniter,我有以下代码从数据库中获取所有记录:
try {
$sth = $this->db->conn_id->prepare($query);
$sth->bindParam(':something', $something, PDO::PARAM_INT);
$sth->execute();
//...
}
catch (PDOException $e) {
//error goes here
}
我在$ ORDER BY之前放置了LIMIT的$查询时犯了一个错误。 即:
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()之前。 为什么?
链接地址: http://www.djcxy.com/p/69569.html