PHP PDO Errors and Error Handling
- ** PDO::ERRMODE_SILENT **
This is the default mode. PDO will simply set the error code, which can be checked using the PDO::errorCode() and PDO::errorInfo() methods on the statement and database objects. If the error was caused by a call on the statement object, you can call that object's PDOStatement::errorCode() or PDOStatement::errorInfo() method. If the error was caused by a call on the database object, you can call the above two methods on the database object.
- ** PDO::ERRMODE_WARNING **
In addition to setting the error code, PDO will also issue a traditional E_WARNING message. If you just want to see what went wrong without interrupting the application flow, this setting is very useful during debugging/testing.
- ** PDO::ERRMODE_EXCEPTION **
In addition to setting the error code, PDO will also throw a PDOException class and set its properties to reflect the error code and error message. This setting is also very useful during debugging because it effectively magnifies the point in the script where the error occurred, allowing you to quickly pinpoint the problematic area of code (remember: if an exception terminates the script, the transaction is automatically rolled back).
Another very useful aspect of exception mode is that, compared to traditional PHP-style warnings, you can build your own error handling more clearly, and it requires less code/nesting than silent mode and explicitly checking the return value of each database call.
Creating a PDO Instance and Setting the Error Mode
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Note: Regardless of whether PDO::ATTR_ERRMODE is currently set, if the connection fails, PDO::__construct() will always throw a PDOException. An uncaught exception is fatal.
Creating a PDO Instance and Setting the Error Mode in the Constructor
PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
// This will cause PDO to throw an E_WARNING level error, not an exception (when the data table does not 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
add a note add a note
PHP PDO Reference Manual