Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent/catch connection error with MySQLi [duplicate]

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?

like image 512
reformed Avatar asked Dec 26 '12 22:12

reformed


People also ask

What is the use of mysqli_ connect_ error()?

Definition and Usage The connect_error / mysqli_connect_error() function returns the error description from the last connection error, if any.

Do I need to close Mysqli connection?

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.

How to check error in query in php?

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.


1 Answers

The answer here was incorrect and outdated. A more recent answer to this question can be found here

like image 155
3 revs Avatar answered Sep 23 '22 18:09

3 revs