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?
I am just @-ing it.
That's one of the few cases where manual error suppression is not absolute evil.
Note that you're confusing exceptions with errors. Though you can catch it too, if you make simple custom error handler which will throw an exception out of any error.
Though I have a feeling that you're taking exceptions wrong way, as a sort of error suppression feature. Anyway, you should never die on error. At least make it
This is very least error control one have to do.
On a live server with sane settings it will log error instead of spitting it right to the user and send appropriate HTTP header. though it will be better to have a custom error handler to handle such errors more flexible way