有没有办法在PHP中捕获MySQL和数据库错误? [英] Is there any way to catch MySQL and database errors in PHP?

查看:687
本文介绍了有没有办法在PHP中捕获MySQL和数据库错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候我收到一个数据库错误,如

Sometimes I am getting a database error like


警告:mysql_connect()[function.mysql-connect]:拒绝用户访问'test'@'101.190.193.83'(使用密码:YES)

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'test'@'101.190.193.83' (using password: YES)

无法连接:访问被拒绝为用户'test'@'101.190.193.83'(使用密码:YES)

Could not connect: Access denied for user 'test'@'101.190.193.83' (using password: YES)"

但真正没有密码更改。

有没有办法在日志文件中捕获此错误,并在屏幕上显示一些不错的消息,如服务器错误。请稍候再试一次。

Is there any way to capture this error in a log file and show some nice message on the screen, like "Server error. Please try again some time."

推荐答案

如果您不希望PHP显示警告,使用@运算符

If you don't want PHP to show the warning, you have to use the "@" operator

$connect = @mysql_connect(HOST, USER, PASS);//won't display the warning if any.
if (!$connect) { echo 'Server error. Please try again sometime. CON'; }

您还可以考虑设置 display_errors 到您的 php.ini 文件在生产

You may also consider setting display_errors to 0 in your php.ini file in production

您也可以考虑 PDO 连接到MySQL,它使用异常作为默认报告错误,

You may also consider PDO for connecting to MySQL, it's using exceptions as a default to report errors,

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Could not connect : ' . $e->getMessage();
}

这篇关于有没有办法在PHP中捕获MySQL和数据库错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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