How to prevent/catch connection error with MySQLi

◇◆丶佛笑我妖孽 提交于 2019-12-23 11:55:00

问题


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?


回答1:


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

@$mysql = new mysqli('localhost', 'user', 'pass', 'wrongdatabase');
if($mysql->connect_errno) trigger_error($mysql->connect_error,E_USER_ERROR);

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



来源:https://stackoverflow.com/questions/14047204/how-to-prevent-catch-connection-error-with-mysqli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!