我们应该始终在MySQL和php中使用准备好的语句还是何时使用这些语句? [英] Should we always use prepared statements in MySQL and php or when to use these?

查看:45
本文介绍了我们应该始终在MySQL和php中使用准备好的语句还是何时使用这些语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了很多文章,说使用准备好的语句非常安全并且可以防止SQL注入.我没有使用准备好的语句就建立了一些网站.但是在阅读了所有这些文章之后,我正在考虑使用准备好的语句来更改整个代码.

I read so many articles saying that using prepared statements is very secure and good to prevent SQL injections. I built a few websites without using prepared statements. But after read all those articles, I am thinking to change whole codes using prepared statements.

我的问题

是否总是需要使用准备好的语句?还是存在正常的陈述比准备的陈述就足够的情况?

Is it necessary to use prepared statements always? or is there any scenario whereby normal statement will be sufficient over prepared statements?

推荐答案

如果您具有完全硬编码的SQL查询并且在SQL中不需要PHP变量,则无需准备就可以了.

Non-prepared statements are sufficient if you have an SQL query that is entirely hard-coded, and needs no PHP variables in the SQL.

这是一个例子:

$result = $mysqli->query("SELECT * FROM mytable WHERE updated_at > NOW() - INTERVAL 7 DAY");

查询是独立的.它只是一个固定的字符串,完全在您的应用程序的控制之下.任何不受信任的内容都不会影响查询.

The query is self-contained. It's just a fixed string, entirely under control of your application. There's no way any untrusted content can affect the query.

如果您的查询需要一些可变部分,请使用查询参数,如下所示:

If your query needs some variable part, then use query parameters, like this:

$stmt = $mysqli->prepare("SELECT * FROM mytable WHERE updated_at > NOW() - INTERVAL ? DAY");
$stmt->bind_param("i", $number_of_days);
$stmt->execute();

查询参数的重点是从SQL解析步骤中分离出可能不受信任的内容.通过使用参数,直到解析完SQL之后,绑定变量的值才与查询结合.因此,绑定参数不可能影响查询的逻辑-该参数将被限制为在查询中充当单个标量值.

The point of query parameters is to separate potentially untrusted content from the SQL parsing step. By using parameters, the value of the bound variable is not combined with the query until after the SQL has been parsed. Therefore there is no way the bound parameter can affect the logic of the query — the parameter will be limited to act as a single scalar value in the query.

这篇关于我们应该始终在MySQL和php中使用准备好的语句还是何时使用这些语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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