How do I catch warnings for mysqli_connect()
Example
if (!$connection2 = mysqli_connect($host, $username, $password, $name)){
die('MySQL ERROR: ' . mysql_error());
}
OR
$connection2 = mysqli_connect($host, $username, $password, $name);
if (!$connection2){
die('MySQL ERROR: ' . mysql_error());
}
So, I am trying to test mysqli_connect()
method by putting wrong host, username etc. in it. But when I put the wrong variables in it such as I put hostlocal
instead of localhost
. It gives me this error
Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo failed:
No such host is known.
I know I am putting the wrong host in it but I want to catch the errors in an appropriate way. A decent message would be perfect just like:
Unfortunately, the details you entered for connection are incorrect!
How do I get this message instead of the warning?
For one, mysql_error()
won't give you anything. It's a part of another library, mysql_
, which doesn't interchange with the new and improved mysqli_
. That being said, you can set MySQLi to throw exceptions, which you then can catch.
The warnings would still be logged, if error-logging is enabled (as it should!). But you can catch the error and display something more user-friendly to the page if the connection fails. You should never display actual error messages to a live project - in development its fine, but never on any live environment.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Set MySQLi to throw exceptions
try {
$connection2 = mysqli_connect($host, $username, $password, $name);
} catch (mysqli_sql_exception $e) {
// $e is the exception, you can use it as you wish
die("Unfortunately, the details you entered for connection are incorrect!");
}
This would however log the same warning as what you're getting to the log,
php_network_getaddresses: getaddrinfo failed: Name or service not known
although it won't be displayed to the page.
You can suppress the warning (so it won't be logged) by adding @
, but I don't recommend it unless you explicitly implement your own error-handling/reporting. Errors should be logged.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Set MySQLi to throw exceptions
try {
$connection2 = @mysqli_connect($host, $username, $password, $name);
} catch (mysqli_sql_exception $e) {
error_log($e->getMessage()); // Log the error manually
die("Unfortunately, the details you entered for connection are incorrect!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With