Default PDO Error Mode in PHP 8.0

Default PDO Error Mode in PHP 8.0

PDO is a PHP extension that provides a 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 an 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:

<?php

$pdo = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'root', 'passwd123');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$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:

<?php

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

Leave a Comment

Cancel reply

Your email address will not be published.