mysqli 要么死,难道就得死吗? [英] mysqli or die, does it have to die?

查看:22
本文介绍了mysqli 要么死,难道就得死吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用一些这样的代码:

If I use a bit of code like this:

$update_result = mysqli_query( $link , $sql_update_login ) or die ('Unable to execute query. '. mysqli_error($link));

它必须死吗,或者你可以在之后提出不同的查询吗?就像将错误日志写入另一个表的预定函数一样?如:

Does it have to die or can you put a different query afterwards? Like a predetermined function that writes a log of the error to another table? Such as:

$update_result = mysqli_query( $link , $sql_update_login ) or function('$query, $error);

'or' 后面的其他选项是什么?我没有在文档中找到它,任何线索表示赞赏.

What are the other options after 'or'? I haven't found it in the documentation, any clues are appreciated.

推荐答案

一定要死吗

恰恰相反,它不应该or die().
PHP 是一种遗传不良的语言.非常不好的遗传.并且 or die() 错误消息是最糟糕的基础之一:

Quite contrary, it shouldn't or die() ever.
PHP is a language of bad heredity. Very bad heredity. And or die() with an error message being one of the worst rudiments:

  • die 会抛出一条错误消息,向潜在的攻击者透露一些系统内部信息
  • 奇怪的消息让无辜的用户感到困惑,让他们没有界面可以工作,所以他们很可能会退出.
  • 它会在中间杀死脚本,因此可能会导致显示的设计撕裂(或根本没有设计)(即用户请求的页面呈现不完整)
  • 无法恢复地终止脚本.虽然抛出的异常可以被捕获并优雅地处理
  • die() 不会提示您错误发生的位置.而在一个相对较大的应用程序中,它会很难找到.
  • die throws an error message out, revealing some system internals to a potential attacker
  • it is confusing innocent users with strange messages and leaving them no interface to work with, so they'd likely just drop out.
  • it kills the script in the middle, so it may cause torn design (or no design at all) shown (i.e. an incomplete render of the page the user requested)
  • killing the script irrecoverably. While thrown exception can be caught and gracefully handled
  • die() gives you no hint of the place where the error occurred. And in a relatively big application it will be quite a pain to find.

所以,千万不要将 die() 用于 MySQL 错误,即使是临时调试:还有更好的方法.

So, never use die() with MySQL errors, even for the temporary debugging: there are better ways.

无需手动检查错误,只需在连接代码中添加以下行,将 mysqli 配置为在出错时抛出异常

Instead of manually checking for the error, just configure mysqli to throw exceptions on error, by adding the following line to your connection code

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

然后按原样编写每个 mysqli 命令,没有任何 or die 或其他任何东西:

and after that just write every mysqli command as is, without any or die or anything else:

$result = mysqli_query($link, $sql);

此代码会在出现错误时抛出异常,因此您将始终了解每个问题,而无需一行额外代码.

This code will throw an exception in case of error and thus you will always be informed of every problem without a single line of extra code.

有关如何使您的错误报告生产就绪、统一和整体合理,同时使您的代码更清晰的更详细说明,您可以在我关于 PHP 错误报告.

A more detailed explanation on how to make your error reporting production ready, uniform and overall sensible while making your code much cleaner, you can find in my article on PHP error reporting.

这篇关于mysqli 要么死,难道就得死吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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