php 设置 PDO 默认抛出异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8992795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:57:04  来源:igfitidea点击:

Set PDO to throw exceptions by default

phpmysqlpdophp-ini

提问by Alex Coplan

I always want PDO to throw exceptions if an error occurs, as I always use PDO like so:

如果发生错误,我总是希望 PDO 抛出异常,因为我总是像这样使用 PDO:

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.');
}

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?

如果有一个我可以编辑的配置文件以使其默认情况下 PDO 抛出异常,那就太好了 - 这可能吗?

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


Update- I have since created a library which handles database access for me (including setting PDO to throw exceptions).

更新- 我已经创建了一个库来为我处理数据库访问(包括设置 PDO 以抛出异常)。

回答by Wouter J

You can add the setAttribute function to the constructor:

您可以将 setAttribute 函数添加到构造函数中:

$pdo = new PDO('mysql:host=localhost;dbname=someTable', 'username', 'password', array(
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));

But I cannot find a method to add it to the php.ini file or some other config file.

但是我找不到将它添加到 php.ini 文件或其他配置文件的方法。

回答by Dan Soap

In extension to rdlowrey's comment, the easiest way would be:

作为 rdlowrey 评论的扩展,最简单的方法是:

class MyPDO extends PDO {

    public function __construct($dsn, $username = null, $password = null, array $driver_options = null) {
         parent :: __construct($dsn, $username, $password, $driver_options);
         $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

}

invocation then simply is a matter of

调用然后只是一个问题

$dbh = new MyPDO("mysql:host=$kdbhost;dbname=$kdbname",$kdbuser,$kdbpw);