36

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

Alex Coplan
  • 13,211
  • 19
  • 77
  • 138
  • 4
    I don't think what you suggest is possible. So umm, if it's something you do often, why not create an object around the functionality or at least separate the functionality into a procedurally included file? –  Jan 24 '12 at 19:30
  • Actually, if you just need to catch PDO exceptions when the connection is established, you don't need to set the ATTR_ERRMODE attribute. PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set – rodrunner Jan 12 '17 at 16:28
  • It's not necessary to set PDO, in order to get the error information (if exists) and avoid escape sequences or SQL Injection is adviced to use Prepared Statements, PDOStatement::errorInfo return the information you are looking for regardless ATT_ERRMODE. –  Nov 11 '17 at 18:32

2 Answers2

55

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

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

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
Wouter J
  • 41,455
  • 15
  • 107
  • 112
27

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);
Dan Soap
  • 10,114
  • 1
  • 40
  • 49