PDO Errors and Error Handling for PHP

  • 2021-11-13 06:55:55
  • OfStack

PHP PDO Errors and Error Handling


This is the default mode. PDO will simply set the error code and can use the PDO::errorCode() And PDO::errorInfo() Method to examine statements and database objects. If the error is caused by a call to a statement object, you can call the PDOStatement::errorCode() Or PDOStatement::errorInfo() Method. If the error is caused by calling the database object, you can call the above two methods on the database object.


In addition to setting the error code, PDO emits a traditional E_WARNING message. This setting is useful during debugging/testing if you just want to see what's wrong without interrupting the flow of your application.


In addition to setting the error code, PDO throws an PDOException exception class and sets its properties to reflect the error code and error message. This setting is also useful during debugging, because it effectively magnifies the point in the script where the error occurred, so that potential areas of the code that are problematic can be pointed out very quickly (remember: if an exception causes the script to terminate, the transaction is automatically rolled back).

Another useful aspect of exception mode is that it builds its own error handling more clearly than traditional PHP-style warnings, and requires less code/nesting than silent mode and explicitly checking the return value of each database call.

Create an PDO instance and set the error mode

$dsn = 'mysql:dbname=testdb;host=';
$user = 'dbuser';
$password = 'dbpass';
try {
  $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
  echo 'Connection failed: ' . $e->getMessage();

Note: Regardless of whether you currently set PDO::ATTR_ERRMODE If the connection fails, PDO::__construct() One PDOException exception will always be thrown. Uncaught exceptions are fatal.

Create an PDO instance and set the error mode in the constructor

$dsn = 'mysql:dbname=test;host=';
$user = 'googleguy';
$password = 'googleguy';
   Use  try/catch  The surrounding constructor is still valid, even if the  ERRMODE  For  WARNING , 
   Because if the connection fails, PDO::__construct  Will always throw 1 A  PDOException  Abnormal. 
try {
  $dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
  echo 'Connection failed: ' . $e->getMessage();
//  This will result in  PDO  Throw 1 A  E_WARNING  Level error, not the  1 Anomalies   (When the data table does not exist) 
$dbh->query("SELECT wrongcolumn FROM wrongtable");

The above routine outputs:

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


Related articles: