In an attempt to establish a database connection, you encountered an issue where the custom error message you defined was not being displayed when the connection failed. You are also seeking a method to suppress error messages from the user's view.
Starting with PHP 8.1, the mysqli extension now automatically throws exceptions in the event of an error, eliminating the need for manual error handling as was done in earlier versions of PHP.
Custom error messages, like the one you defined, are no longer recommended for error handling. Both PDO and mysqli have the ability to raise errors automatically, just like any other PHP command. Therefore, manually checking for errors, as you attempted to do with the if (!$conn) segment, is obsolete.
To prevent error messages from reaching the user, you should utilize the display_errors configuration option, which can be set to 0 to suppress all error output. This can be configured in the php.ini file or directly in your PHP code:
<code class="php">ini_set('display_errors', 0);</code>
Instead of displaying cryptic error messages, it is advisable to present a user-friendly error page to site visitors. This can be achieved by setting up an error handler, such as the one below, which will catch all irrecoverable errors:
<code class="php">set_exception_handler(function ($e) { error_log($e); http_response_code(500); if (ini_get('display_errors')) { echo $e; } else { echo "<h1>500 Internal Server Error</h1>\nAn internal server error has been occurred.<br>\nPlease try again later."; } });</code>
If you need to specifically handle database connection errors, you can use a separate connection test script wrapped in a try-catch block, separate from your regular connection code.
For enhanced security, update your PHP version to 8.2 or later, which obscures database passwords from appearing in the stack trace.
The above is the detailed content of Why Are My Custom Error Messages Not Displaying in mysqli_connect Failures After Upgrading to PHP 8.1?. For more information, please follow other related articles on the PHP Chinese website!