Home >Database >Mysql Tutorial >Why Doesn\'t My Custom Error Message Show When mysqli_connect Fails in PHP?

Why Doesn\'t My Custom Error Message Show When mysqli_connect Fails in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 17:35:14512browse

Why Doesn't My Custom Error Message Show When mysqli_connect Fails in PHP?

Why does PHP not show a custom error message when mysqli_connect fails?

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.

How to Handle Connection Errors

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
}

How to Hide Error Messages from Users

To hide error messages from users, set display_errors to 0 in php.ini or using ini_set():

ini_set('display_errors', 0);

How to Display User-Friendly Error Pages

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.";
    }
});

How to Test Connection Credentials

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
}

How to Hide Connection Credentials

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn