Search code examples
phpmysqli

PHP returns fatal error instead of error number when connecting to MySQL


My current computer has XAMPP installed and I have used it successfully to test PHP programs for some years. I recently bought a new computer and have installed the latest version of XAMPP on it, as well as transferring a number of PHP application programs to it. When trying to connect to a database, I use the following logic:

<?php
function dbConnect() {`
@ $db = new mysqli('localhost', 'live_username', 'live_PW', 'live_db_name' );
$test = mysqli_connect_errno();
  if (mysqli_connect_errno()) {
    @ $db = new mysqli('localhost', 'test_username', 'test_PW', 'test_db_name' );
    if (mysqli_connect_errno()) {
      $test = mysqli_connect_errno();
      echo "Error # ".$test."<br/>";
      echo 'Error: Could not connect to database. Please try again later.';
      exit;
    }
  }
return $db;
}
?>

This logic is used by all my applications on a number of different host servers to connect to a database, and it always works fine. First, a connection to the client's live database is attempted. If this fails because that database is not available or some other error occurs, then an attempt to connect to the test database is made.

On the new computer, on executing the first connection attempt, I get the message:

Fatal error: Uncaught mysqli_sql_exception: Access denied for user 'centr120_genuser'@'localhost' (using password: YES) in C:\xampp\htdocs\cmp\connectdb.php:3 Stack trace: #0 C:\xampp\htdocs\cmp\connectdb.php(3): mysqli->__construct('localhost', 'live_use...', Object(SensitiveParameterValue), 'live_db_name') #1 C:\xampp\htdocs\cmp\index.php(17): dbConnect() #2 {main} thrown in C:\xampp\htdocs\cmp\connectdb.php on line 3

For some reason, a fatal error occurs on the first connection attempt, which means that the test for the error number ( mysqli_connect_errno() ) never gets executed.

Does anyone know why this happens?


Solution

  • It must be because you installed PHP >= 8.1

    mysqli_report: As of PHP 8.1.0, the default setting is MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT. Previously, it was MYSQLI_REPORT_OFF.

    I suggest you rewrite your code with try-catch statements:

    function dbConnect() {
        try {
            return new mysqli('localhost', 'centr120_genuser', 'Baroque73!', 'centr120_cmp');
        } catch (mysqli_sql_exception) {}
    
        return new mysqli('localhost', 'pract458_genuser', 'Gunjur64!', 'pract458_cmp' );
    }
    

    This way, PHP will return the first connection if it works, and otherwise will try to create the second one.

    Note that printing something like "Error: Could not connect to database. Please try again later." is a bad practice. Your code should be able to handle any fatal error, not only the database connection. And the error message must be generic, without any particular details.