如何使用MySQLi防止/捕获连接错误 [英] How to prevent/catch connection error with MySQLi

查看:97
本文介绍了如何使用MySQLi防止/捕获连接错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,对于下面的给定代码,如果数据库名称无效,如何防止连接错误?

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);

if语句将输出正确的错误消息,但第一行仍会发出警告,提示

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

我知道使用PDO,您只需将其包装在try/catch块中,但是如何使用MySQLi?

I know with PDO you would simply wrap it in a try/catch block, but how to do it with MySQLi?

推荐答案

我只是@ing.
这是手动错误抑制并非绝对有害的少数情况之一.

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);

这至少是必须执行的错误控制.
在具有合理设置的实时服务器上,它将记录错误,而不是直接向用户吐痰并发送适当的HTTP标头.尽管最好使用自定义错误处理程序以更灵活的方式处理此类错误

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

这篇关于如何使用MySQLi防止/捕获连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆