设置PDO默认情况下引发异常 [英] Set PDO to throw exceptions by default
问题描述
我总是希望PDO在发生错误时引发异常,因为我总是这样使用PDO:
I always want PDO to throw exceptions if an error occurs, as I always use PDO like so:
try {
$dbh = new PDO("mysql:host=$kdbhost;dbname=$kdbname",$kdbuser,$kdbpw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// some queries
}
catch (PDOException $e) {
error_log('PDO Exception: '.$e->getMessage());
die('PDO says no.');
}
如果有一个我可以编辑的配置文件会很不错,那么PDO默认会抛出异常-这可能吗?
It would be nice if there was a config file I could edit to make it so PDO throws exceptions by default - is this possible?
我想要这样做的原因是这样,我不必每次都写此行:
The reason I want this is so I don't have to write this line every time:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
更新-此后,我创建了一个库来为我处理数据库访问(包括将PDO设置为引发异常).
Update - I have since created a library which handles database access for me (including setting PDO to throw exceptions).
推荐答案
您可以将setAttribute函数添加到构造函数中:
You can add the setAttribute function to the constructor:
$pdo = new PDO('mysql:host=localhost;dbname=someTable', 'username', 'password', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
但是我找不到将其添加到php.ini文件或其他配置文件中的方法.
But I cannot find a method to add it to the php.ini file or some other config file.
这篇关于设置PDO默认情况下引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!