How do you prevent a connection error if, for example, the database name is invalid, for the given code below?
$mysql = new mysqli('localhost', 'user', 'pass', 'wrongdatabase');
if($mysql->connect_errno)
die($mysql->connect_error);
The if statement will output the right error message, but there will still be a warning sent from the first line, which says
Warning: mysqli::mysqli() [<a href='mysqli.mysqli'>mysqli.mysqli</a>]: (42000/1049): Unknown database 'wrongdatabase' in C:\wamp\www\example.php on line 14
I know with PDO you would simply wrap it in a try/catch block, but how to do it with MySQLi?
Definition and Usage The connect_error / mysqli_connect_error() function returns the error description from the last connection error, if any.
Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.
To get the error message we have to use another function mysqli_error() to print the error message returned by MySQL database after executing the query. Here it is how to print the error message. echo mysqli_error(); The above line will print the error returned by mysql database if the query fails to execute.
The answer here was incorrect and outdated. A more recent answer to this question can be found here
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