PHP 8.1: MySQLi: Default error mode set to exceptions
In PHP 8.1, the default error handling behavior of the MySQLi extension has changed from silencing errors to throw an Exception on errors.
Prior to PHP 8.1, the default error reporting mode in MySQLi was to silent the errors, and often lead to code that did not follow proper Exception/Error handling. From PHP 8.1 and later, the default error reporting mode is to throw an Exception on errors.
MySQLi's default error mode is changed from
MYSQLI_REPORT_OFF
toMYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT
- MYSQLI_REPORT_OFF
+ MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT
This change is similar to PDO extension changing its error reporting mode to Exceptions in PHP 8.0.
Prior to PHP 8.1, an error in the extension, database, query, or the database connection returned false
and emitted a PHP warning.
$mysqli = new mysqli("localhost", "non-existing-user", "", "");
Warning: mysqli::__construct(): (HY000/2002): No connection could be made because the target machine actively
refused it in ... on line ...
From PHP 8.1 and later, the default error mode is set to MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT
.
$mysqli = new mysqli("localhost", "non-existing-user", "", "");
Fatal error: Uncaught mysqli_sql_exception: Connection refused in ...:...
Backwards Compatibility Impact
This is a breaking change because the default value is different in PHP 8.1.
For compatibility across PHP versions prior to PHP 8.1, it is possible to explicitly set the error handling mode using mysqli_report
function before the first MySQLi connection is made. It is also possible to instantiate a mysqli_driver
instance, and set the error reporting value.
Note that
mysqli_driver
class has a mono-state pattern, which means once the error reporting value is set, it affects all MySQLi connections throughout the request unless the value is later overwritten in another call. The same applies for themysqli_report
function as well.
Configure PHP 8.1 behavior in all PHP versions:
mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
or
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT;
Configure PHP < 8.1 behavior in all PHP versions:
mysqli_report(MYSQLI_REPORT_OFF);
or
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_OFF;
Using Exceptions (default behavior in PHP 8.1) is recommended, because it brings errors that could have gone unnoticed. To prevent sensitive data leakage, configure the display_errors
INI value to off
. With MYSQLI_REPORT_OFF
, the caller must handle the errors by checking the return value of mysqli_*
function calls, or by checking the $mysqli->error
property.
Related Changes
- PHP 8.0: PDO: Default error mode set to exceptions
- PHP 8.3: SQLite3: New
\SQLite3Exception
, deprecations, and changes