更新时间:2021-10-17 22:45:03
您当前的代码有一些缺陷。让我给你一些指导。
Your current code has some flaws. Let me give you few pointers.
您不需要创建的函数,至少不需要当前形式的函数。每次调用此函数时,它都会创建一个新的PDO对象,这可能会影响脚本的性能。理想情况下,整个脚本的执行过程中只需要一个连接。
You do not need the function you have created, at least not in the current form. Every time you call this function it creates a new PDO object, which can hinder your script's performance. Ideally you would want to have only one connection throughout the execution of your whole script.
在创建新的PDO连接时,您需要记住3件事:设置正确的连接字符集,启用错误报告以及禁用模拟准备。
When creating new PDO connection you need to remember 3 things: to set proper connection charset, enable error reporting, and disable emulated prepares.
utf8mb4
。完整代码应如下所示:
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new \PDO('mysql:host=localhost;dbname=dbname;charset=utf8mb4', 'user', 'pw', $options);
不要捕获异常,除非您知道该如何处理并且肯定您需要这样做。***是例外。让PHP与其他异常/错误/警告一起处理它们。毕竟为什么只为PHP异常创建一个异常?所有PHP错误都应以相同方式处理。无论您什么都不打印(包括 die
, exit
, echo
) >, var_dump
)在屏幕上手动显示错误消息。如果此类代码曾经投入生产,那么这将是一个巨大的安全问题。
Don't catch the exceptions unless you know what to do with them and are positively sure you need to do so. Exceptions are best left be; let PHP handle them together with the other exceptions/errors/warnings. After all why make an exception just for PHP exceptions? All PHP errors should be handled the same. Whatever you do never print (including die
, exit
, echo
, var_dump
) the error message manually on the screen. This is a huge security issue if such code ever makes its way into production.
如果将PDO连接设置为对错误抛出异常,则无需使用 if
语句来检查 prepare()
或 execute()
的返回码。
If your PDO connection is set to throw exceptions on errors, you never need to use if
statements to check return code of prepare()
or execute()
.