Thursday, 29 October 2020

Should we ever check for mysqli_connect() errors manually?

The PHP manual for mysqli_connect() suggests checking for the return value and displaying the error messages on the screen.

$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

Similarly for OOP-style constructor this is suggested:

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

Some users on Stack Overflow even used code with mysqli_error($conn) such as this:

$conn = mysqli_connect('localhost', 'a', 'a');
if (!$con) {
    die('Could not connect: ' . mysqli_error($conn));
}

However, in the past few weeks I have been asking myself a question, why would I need to do that? The output of the first example is:

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'my_user'@'localhost' (using password: YES) in C:\xampp\...\mysqli.php on line 4

Error: Unable to connect to MySQL. Debugging errno: 1045 Debugging error: Access denied for user 'my_user'@'localhost' (using password: YES)

As you can see the error message is displayed twice! The manual "debugging" actually provides less information.

Should we ever manually check for connection errors? Would we ever get more information this way than from the automatic warning? Is this the recommended practice?



from Should we ever check for mysqli_connect() errors manually?

No comments:

Post a Comment