Set PDO to throw exceptions by default [duplicate]

假装没事ソ 提交于 2019-11-26 06:46:44

问题


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

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

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


回答1:


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

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




回答2:


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

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


来源:https://stackoverflow.com/questions/8992795/set-pdo-to-throw-exceptions-by-default

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!