Default PDO Error Mode in PHP 8.0

PDO is a PHP extension that provides uniform way to access various databases (MySQL, PostgreSQL, etc.). PDO supports three different error modes. Error mode defines how PDO should behave on errors.

No.Error modeDescription
1.PDO::ERRMODE_SILENTIf SQL error occurs then PDO will not emit a warning or throw an exception. Error can be manually inspected by using the PDO::errorCode and PDO::errorInfo methods.
2.PDO::ERRMODE_WARNINGIf SQL error occurs then PDO will emit a warning (E_WARNING).
3.PDO::ERRMODE_EXCEPTIONIf SQL error occurs then PDO will throw a PDOException.

In versions prior to PHP 8.0, the default error mode was PDO::ERRMODE_SILENT. In this mode PDO is silent. So no warning is emitted and no exception is thrown when SQL error occurs. In order to minimize the probability of overlooking SQL errors, often the error mode is set to PDO::ERRMODE_EXCEPTION. PDO::ATTR_ERRMODE attribute is used to control the error mode and it can be set with PDO::setAttribute method.

In the following code we tried to insert a record in a table that does not exist:


$pdo = new PDO('mysql:dbname=testdb;host=', 'root', 'passwd123');
$pdo->exec('INSERT INTO non_existent_table (data) VALUES (5)');

We explicitly set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION and an exception is thrown:

Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'testdb.non_existent_table' doesn't exist ...

Since PHP 8.0, the default error mode is PDO::ERRMODE_EXCEPTION. So we don’t need to explicitly set the attribute to PDO::ERRMODE_EXCEPTION:


$pdo = new PDO('mysql:dbname=testdb;host=', 'root', 'passwd123');
$pdo->exec('INSERT INTO non_existent_table (data) VALUES (5)');

Leave a Comment

Your email address will not be published. Required fields are marked *