PDO
PHP Manual

Errors and error handling

PDO offers you a choice of 3 different error handling strategies, to fit your style of application development.

PDO standardizes on using SQL-92 SQLSTATE error code strings; individual PDO drivers are responsible for mapping their native codes to the appropriate SQLSTATE codes. The PDO::errorCode() method returns a single SQLSTATE code. If you need more specific information about an error, PDO also offers an PDO::errorInfo() method which returns an array containing the SQLSTATE code, the driver specific error code and driver specific error string.

Example #1 Create a PDO instance and set the error mode

<?php
$dsn 
'mysql:dbname=testdb;host=127.0.0.1';
$user 'dbuser';
$password 'dbpass';

try {
    
$dbh = new PDO($dsn$user$password);
    
$dbh->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
} catch (
PDOException $e) {
    echo 
'Connection failed: ' $e->getMessage();
}

?>

Note:

PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set. Uncaught Exceptions are fatal.

Example #2 Create a PDO instance and set the error mode from the constructor

<?php
$dsn 
'mysql:dbname=test;host=127.0.0.1';
$user 'googleguy';
$password 'googleguy';

/*
    Using try/catch around the constructor is still valid even though we set the ERRMODE to WARNING since
    PDO::__construct will always throw a PDOException if the connection fails.
*/
try {
    
$dbh = new PDO($dsn$user$password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (
PDOException $e) {
    echo 
'Connection failed: ' $e->getMessage();
    exit;
}

// This will cause PDO to throw an error of level E_WARNING instead of an exception (when the table doesn't exist)
$dbh->query("SELECT wrongcolumn FROM wrongtable");
?>

The above example will output:

Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.wrongtable' doesn't exist in
/tmp/pdo_test.php on line 18


PDO
PHP Manual