PHP 8.1 : MySQLi default error mode switched to strict
23, April 2022

Legacy PHP apps are way too scared of errors. They suppress them, silent them, hide them under the carpet. Most of the time they forget about them. PHP developers are like some character in psychological horror movie who doesn't want to remember what he did last night (spoiler: he killed someone).

As a result, error_reporting is set to off, @ is used before most of the brat functions. I have even seen people to wrap a giant try-catch block around their whole code, off course the catch block was empty. What do you mean logging the errors? Why would we do that when we don't have any errors? Here, look at our error log file, see? No errors. Argh.....


MySQLi default error mode is one of such issue. It is set MYSQLI_REPORT_OFF by default. As a result, developers were never notified of their errors in query. PHP just silently ignores them and continues the code execution flow. One justification for this behavior was to hide sensitive info of the query from website visitors. But that's totally off the point, Users shouldn't see the internal errors of a website but the developer/sysadmin should know them all. Most of the security exploits take advantage of buggy behavior. Silencing them makes them harder to detect and fix.

And how do we justify all those mysql_query() or die($mysqli->error) code snippet on stackoverflow?


PHP 8.1 comes with a sensible default:

On 8.1, mysqli default error mode is set to same as:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);


MYSQLI_REPORT_ERROR: Throws warning message whenever there is an error. PHP does not stop code execution, just emits the message.

MYSQLI_REPORT_STRICT: Converts those warning message to mysqli_sql_exception . PHP fully stops code execution. This way we now have an exception that we can control (via catch) when error happens.

Combining both of them means PHP will now trigger exception for all mysqli errors.


Now we can implement a proper exception handling logic so website visitor get a nice looking page when DB error happens and developer can have every information in hand to fix those errors.


But, I like being psychopath

Here you go. Use this line to go back to dark era and please don't tell anyone that you got it from me.

mysqli_report(MYSQLI_REPORT_OFF);


RFC: https://wiki.php.net/rfc/mysqli_default_errmode


Write comment about this article: