Default MySQLi Error Mode in PHP 8.1

Default MySQLi Error Mode in PHP 8.1

MySQLi is a PHP extension that allows to use the functionality provided by MySQL database. MySQLi supports five different error modes, which defines how MySQLi should behave when an error occurs.

No.Error modeDescription
1.MYSQLI_REPORT_OFFIf SQL error occurs then MySQLi will not emit a warning or throw an exception. Error can be manually retrieved by using mysqli_error function.
2.MYSQLI_REPORT_ERRORIf SQL error occurs then MySQLi will report a warning (E_WARNING).
3.MYSQLI_REPORT_STRICTIf SQL error occurs then MySQLi will throw mysqli_sql_exception instead of warning. Used as MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT.
4.MYSQLI_REPORT_INDEXIf no index or bad index was used in a query then MySQLi reports about it. Used as MYSQLI_REPORT_ERROR | MYSQLI_REPORT_INDEX. MYSQLI_REPORT_STRICT can be added as well.
5.MYSQLI_REPORT_ALLReport everything by applying all options.

Default error mode can be changed with mysqli_report function.

In versions prior to PHP 8.1, the default error mode was MYSQLI_REPORT_OFF. In this mode, MySQLi is silent. So no warning is emitted, and no exception is thrown when an SQL error occurs. The mysqli_error function can be used to get error manually:

<?php

$conn = mysqli_connect('127.0.0.1', 'root', 'passwd123', 'testdb');

$result = mysqli_query($conn, 'INSERT INTO non_existent_table (data) VALUES (5)');
echo $result ? 'Ok' : 'Error: '.mysqli_error($conn);

mysqli_close($conn);
Error: Table 'testdb.non_existent_table' doesn't exist

Since PHP 8.1, the default error mode is MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT. MySQLi will throw an exception if an SQL error occurs.

<?php

$conn = mysqli_connect('127.0.0.1', 'root', 'passwd123', 'testdb');
mysqli_query($conn, 'INSERT INTO non_existent_table (data) VALUES (5)');
mysqli_close($conn);
Fatal error: Uncaught mysqli_sql_exception: Table 'testdb.non_existent_table' doesn't exist in ...

Similar changes were made for default PDO error mode in PHP 8.0.

Leave a Comment

Cancel reply

Your email address will not be published.