设置 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=someDatabase', '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屋!