我这样做(是的,我用错了连接数据,这是强制连接错误)
26 try {
27 $connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
28 } catch (Exception $e ) {
29 echo "Service unavailable";
30 exit (3);
31 }
但是PHP是这样做php_warning:
mysqli的:: mysqli的():(一千○四十五分之二万八):拒绝访问用户my_user'@ 'localhost' 的(使用密码:YES)
在这个例子中我使用的是错误的连接数据强制连接错误,但在现实世界中的数据库能够降下来,或者网络可能会下降......等等。
问:有没有一种方法, 不抑制警告,拦截与数据库的连接有问题?
你需要告诉mysqli的抛出异常:
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
} catch (Exception $e ) {
echo "Service unavailable";
echo "message: " . $e->message; // not in live code obviously...
exit;
}
现在,你将捕获异常,你可以把它从那里。
对于PHP 5.2.9+
if ($mysqli->connect_error) {
die('Connect Error, '. $mysqli->connect_errno . ': ' . $mysqli->connect_error);
}
你会希望将报告模式设定了严格的级别为好,就像吉荣建议,但上面的代码仍然是有用的特异性检测连接错误。 这两种方法的结合是在推荐的PHP手册 。
检查$connection->connect_error
值。
在这里看到的例子: http://www.php.net/manual/en/mysqli.construct.php
是什么,如果我们只是做如果单纯的区别? 为什么我会不屑于与尝试,赶上如果简单,如果做的一切?
if ($mysqli->connect_errno) { echo "connection error, exiting..."; exit; } // everything was fine... echo "hello, connection was established!"
mysqli_report(MYSQLI_REPORT_STRICT);,如别处所描述的,给我一个错误并立即停止脚本。 但低于这个似乎为我提供所需的输出...
error_reporting(E_ERROR);
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
error_reporting(E_ERROR | E_WARNING | E_PARSE);
if($connection->connect_errno)
{
// Database does not exist, you lack permissions, or some other possible error.
if(preg_match($connection->connect_error, "Access denied for user"))
{
print("Access denied, or database does not exist.");
}
else
{
print("Error: " . $connection->connect_error);
}
}
试图抓住这个误差在try..catch()会失败。