Should we ever check for mysqli_connect() errors manually?
Never display connection errors manually!
MySQLi will generate a warning if it is unable to open the connection to MySQL. This warning tells you all you need to know including the error code, error message, and the place in the code where it happened. Checking for the error manually will not give you any more information.
If you can't see the warning and your connection cannot be created, it might mean that your PHP is not configured to show them. In that case, you must check the error log file on your server. If you do not know where that is, use phpinfo()
to get that information and search for error_log
. It will tell you where the error log file is located.
If there is no warning in the error logs, it could mean that your PHP has error reporting silenced (either completely or just warnings). Check your PHP configuration.
In the production environment these settings should be maintained:
-
error_reporting
must beE_ALL
-
log_errors
must beOn
-
display_errors
must beOff
In the development environment these settings should be maintained:
-
error_reporting
must beE_ALL
-
log_errors
must beOn
-
display_errors
must beOn
As you can see in the error message your database username and password has been revealed to the end-user. These are sensitive information which you do not want to show anyone. In fact, a normal user would not understand this cryptic message. This is why display_errors
must always be switched off in the production environment. Logging the errors on the server is safe.
Warnings vs. Exceptions
Warnings do not stop the script. If a warning is emitted the script will keep on executing until it encounters a fatal error. In most cases, you would want to throw an exception to stop the script. Do not use die/exit
! If mysqli connection cannot be made, an exception should be thrown and if it is unhandled it will bubble up and stop the script with a fatal error. You can configure mysqli to throw exceptions automatically. This is invaluable because all mysqli functions can fail for many reasons and they will not inform you about any problems unless you check for errors manually every single one of them. Use the following line before opening connection:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
Do not catch the exceptions unless you really know what to do with them! One possible use case is described in How to connect properly using mysqli
Can mysqli_error()
show any connection-related problems?
No. mysqli_error($conn)
expects that the mysqli connection was successful. $conn
must be a valid mysqli connection otherwise you would get this error message:
Warning: mysqli_error(): Couldn't fetch mysqli in C:\...
Neither $conn->error
nor mysqli_error($conn)
can display any connection related errors!
Related: Should I manually check for errors when calling “mysqli_stmt_prepare”?