更新时间:2023-12-05 11:19:10
你应该积极地不习惯抑制错误。错误是有原因的。相反,在您的代码中正确和防御地处理它们,并继续改进代码,直到错误消失。
您应该执行以下操作:
$ conn = mysql_connect($ host,$ user,$ pass);
//总是测试看你的动作/连接/任何成功的
如果(!$ conn){
//发生错误。处理错误
//显示用户的消息,向`error_log()'写一条消息,任何适当的
}
else mysql_select_db($ dbname);
在生产系统上,您不应显示错误,因为它可能会放弃您的代码的详细信息,数据库。相反,请在php.ini或运行时关闭 display_errors
:
//在开发和生产中,确保报告所有错误
error_reporting(E_ALL& E_STRICT);
//在开发中显示屏幕上的所有错误,以便处理它们,因为它们发生
ini_set('display_errors',1);
//在生产中将它们关闭
ini_set('display_errors',0);
事实上,使用 @
在这个经典问题中,第二次被投票支持PHP的不良做法
Hey guys I was wondering why you would "suppress" a php error? I obviously see the difference in the extra line that spits out from the error... but is it good to suppress it?
Access denied for user 'user'@'localhost' (using password: YES)
Vs
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in (deleted) on line 8
Access denied for user 'user'@'localhost' (using password: YES)
If so, should I get into the habit of typing @ at the start of my mysql queries in my php ?
Thanks!
You should positively NOT get into the habit of suppressing errors. The errors are there for a reason. Instead, handle them properly and defensively in your code, and keep refining your code until the errors are gone.
You should do things like:
$conn = mysql_connect($host, $user, $pass);
// Always test to see if your action/connection/whatever was successful
if (!$conn) {
// something went wrong. handle the error
// Display a message for the user, write a message to `error_log()`, whatever's appropriate
}
else mysql_select_db($dbname);
On a production system, you should never display errors, since it risks giving up details of your code and database. Instead, turn display_errors
off in php.ini, or at runtime:
// In development and production, make sure all errors are reported
error_reporting(E_ALL & E_STRICT);
// In development show all errors on screen so you handle them as they occur
ini_set('display_errors', 1);
// In production turn them off
ini_set('display_errors', 0);
In fact, error suppression with @
is the second most voted for PHP bad practice in this classic question.