🎓 A1Learner
🔍
0 of 38 lessons completed

PDO Errors

A PDO error is a failure that PDO reports when a database job cannot be done. PDO reports the failure by throwing a PDOException, a kind of exception that a catch block can handle.

An uncaught failure stops the program

This program asks a memory database for a table that was never created. No catch block handles the thrown exception, so the fatal error line prints and the program stops.

<?php
$db = new PDO("sqlite::memory:");
$db->query("SELECT * FROM missing");

A catch block prints the failure

The setAttribute line pins the throwing error mode first. The same query sits in a try block, and the catch block prints the class name and the message of the exception.

<?php
$db = new PDO("sqlite::memory:");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
  $db->query("SELECT * FROM missing");
} catch (PDOException $e) {
  echo get_class($e) . "\n";
  echo $e->getMessage() . "\n";
}

A failure at connect time

This DSN names a folder that does not exist on the machine. The new PDO line fails at once, and the catch block prints the message.

<?php
try {
  $db = new PDO("sqlite:/no/such/dir/x.db");
} catch (PDOException $e) {
  echo $e->getMessage() . "\n";
}

Example

<?php
$db = new PDO("sqlite::memory:");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
  $db->query("SELECT * FROM catalogue");
} catch (PDOException $e) {
  echo $e->getMessage() . "\n";
}
try {
  $other = new PDO("sqlite:/no/such/dir/x.db");
} catch (PDOException $e) {
  echo $e->getMessage() . "\n";
}

Key points

  • Since PHP 8, PDO throws a PDOException by default when a database job fails.
  • An uncaught exception stops the program and prints a fatal error line.
  • The getMessage method gives the failure message of an exception as text.
  • The get_class function gives the class name of an object as text.
  • The setAttribute method with PDO::ATTR_ERRMODE and PDO::ERRMODE_EXCEPTION pins the throwing behaviour.
  • A connect failure happens at the new PDO line, before any query runs.

In this example, the first try block queries a table named catalogue that was never created. Its catch block prints the missing table message. The second try block tries to open a database in a missing folder, and its catch block prints the connect message.

Note

Since PHP 8 the throwing behaviour is the default, so failures no longer stay silent.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Since PHP 8, what does PDO do by default when a query fails?