Home >Database >Mysql Tutorial >Why Doesn\'t My Custom Error Message Show When mysqli_connect Fails in PHP?
In the past, PHP used the MySQL extension to connect to databases, which required manual error handling. However, with the introduction of mysqli, errors are automatically thrown, eliminating the need for manual checks like if (!$conn).
In PHP 8.1 and later, mysqli throws exceptions for errors. Therefore, the custom error message in your code is not displayed.
The recommended approach is to use a try-catch block to handle database connection errors rather than relying on manual checks:
try { $conn = mysqli_connect($dbServerName, $dbUsername, $dbPassword, $dbName); } catch (Exception $e) { // Handle the error here }
To hide error messages from users, set display_errors to 0 in php.ini or using ini_set():
ini_set('display_errors', 0);
Use an error handler to display a generic error page instead of the specific error message:
set_exception_handler(function ($e) { // Log the error error_log($e); // Set HTTP status code to 500 http_response_code(500); // Check display_errors setting if (ini_get('display_errors')) { echo $e; } else { echo "<h1>500 Internal Server Error</h1>An internal server error has occurred. Please try again later."; } });
Use a separate connection test with try-catch to test credentials for installation scripts or backup scenarios:
try { $conn = mysqli_connect($dbServerName, $dbUsername, $dbPassword, $dbName); } catch (Exception $e) { // Handle the error }
In PHP 8.2 and later, the database password is hidden from the stack trace.
The above is the detailed content of Why Doesn\'t My Custom Error Message Show When mysqli_connect Fails in PHP?. For more information, please follow other related articles on the PHP Chinese website!