In the past, PHP's mysql extension required manual error handling. However, the mysqli extension introduced in PHP 8.1 now automatically triggers exceptions upon encountering errors, eliminating the need for manual error detection.
Your code includes an if (!$conn) block that attempts to output a custom error message. This approach is outdated. mysqli inherently throws errors, which should be handled automatically.
To hide error messages from site visitors, you should use the display_errors configuration option. Setting it to 0 will prevent PHP from displaying any errors. You can set this option in php.ini or in PHP code using ini_set('display_errors', 0).
While it's essential to hide system errors from users, you may want to display a user-friendly error page. This can be achieved using an error handler like:
<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> An internal server error has occurred.<br> Please try again later."; } });</code>
This handler logs the error, sets an HTTP 500 status code, and displays a generic error message if display_errors is set to 0.
In certain scenarios, you may need to explicitly handle connection errors. This can be done using a try-catch block. However, such handling should be limited to cases where specific error scenarios require alternative actions.
If you're concerned about sensitive information appearing in the stack trace, consider upgrading to PHP 8.2 or later, which hides database passwords from the stack trace.
The above is the detailed content of Why Doesn\'t My Custom PHP Error Message Appear When mysqli_connect Fails?. For more information, please follow other related articles on the PHP Chinese website!