为什么 MySQLi 准备了语句?
在 MySQLi 中使用准备好的语句有哪些优点?
如果唯一的目的是保护查询,那么使用 mysqli_real_escape_string 之类的东西清理查询不是更好,而不是为每个查询编写这么多行代码(例如准备、bind_param、执行、关闭, ETC。)?
What are the advantages of using prepared statements with MySQLi?
If the only purpose is to secure the query, isn't it better to clean the query using something like mysqli_real_escape_string
instead of writing so many lines of code for each query (like prepare, bind_param, execute, close, etc.)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
准备语句不仅仅是为了代码安全。它帮助 SQL Server 解析您的语句并为您的查询生成执行计划。
如果您运行 SELECT 1000 次,那么 SQL Server 将必须解析、准备并生成如何获取数据 1000 次的计划。
如果您准备一条语句,然后每次使用不同的绑定值运行准备好的语句 1,000 次,则该语句仅解析一次,并且每次都使用相同的查询计划。
这不仅在您在脚本内运行 1,000 个查询时有帮助,而且在您只有 1 个语句并运行脚本 1,000 次时也有帮助。服务器可以记住服务器端的计划。下次运行脚本时,它将再次使用相同的计划。
当然,对于一两个查询来说,这似乎微不足道,但是当您开始执行大量查询或重复执行同一查询时,您将节省大量处理时间。
Preparing statements is not just for code security. It helps the SQL server parse your statement and generate an execution plan for your query.
If you run a SELECT 1000 times then the SQL server will have to parse, prepare, and generate a plan on how to get your data 1000 times.
If you prepare a statement then run the prepared statement 1,000 times each with different bound values then the statement is parsed only once and the same query plan is used each time.
This helps not only when you run 1,000 queries inside the script but also if you only have 1 statement and run the script 1,000 times. The server can remember the plan server side. The next time your script runs it will use the same plan again.
Sure it may seem trivial for one or two queries but when you start executing large numbers of queries or the same query repeatedly you will save a lot of processing time.
有几个优点:
WHERE $x = 4
如果$x
为 null,则会出现语法错误,但WHERE ? = 4
就可以了。There are several advantages:
WHERE $x = 4
you will get a syntax error if$x
is null, butWHERE ? = 4
will work.