简单的问题(我希望).
目前我正在使用以下代码:
mysql_query($sql) or header("Location: /error");
为了防止脚本的其余部分运行,我需要添加exit;或die().有没有办法使用上面的内联方法,或我需要使用:
$result = mysql_query($sql);
if (!result) {
header("Location: /error");
exit();
}
Run Code Online (Sandbox Code Playgroud)
谢谢
Fos*_*sco 11
怎么样:
function customDie($location) {
header('Location: ' . $location);
exit();
}
mysql_query($sql) or customDie("/error");
Run Code Online (Sandbox Code Playgroud)
如果你坚持以这种方式做事,最好制作一个处理所有这些的自定义查询方法.就像是
function custom_mysql_query($query) {
$doDebug=true; // Set to true when developing and false when you are deploying for real.
$result=mysql_query($query);
if(!$result) {
if($doDebug) {
// We are debugging so show some nice error output
echo "Query failed\n<br><b>$query</b>\n";
echo mysql_error(); // (Is that not the name)
}
else {
// Might want an error message to the user here.
}
exit();
}
}
Run Code Online (Sandbox Code Playgroud)
然后只调用custom_mysql_query而不是mysql_query,如果查询失败,你将永远死掉,如果$debug是,你也会得到失败的查询和数据库错误.
但实际上:你永远不应该使用mysql_query或调用它的函数(比如我刚写的那个).使用起来太不安全了.(很难避免sql注入)
使用pdo类而不是mysql_方法(谷歌它,在线有很多教程和解释).