如何自动转义PHP SQL查询中的字符串? [英] How to automatically escape strings in a PHP SQL query?
问题描述
以下是我目前的方法:
$db->query(sprintf('INSERT INTO pages (title, content) VALUES ("%s", "%s")',
$db->esc($title),
$db->esc($content)));
正如你所看到的,我通过将每个字符串传递到我的$ db-> esc()方法来手动转义上述查询中的每个字符串。
As you can see I'm manually escaping each string in the above query by passing each string to my $db->esc() method.
首先让我指出我不想使用准备好的语句。
First let me indicate that I don't want to use prepared statements.
我可以想出的最好的想法是让我的$ db->查询( )方法wrap sprintf()并自动调用$ db-> esc()对每个字符串转换规范 - 像这样:
The best idea I can come up with is to have my $db->query() method wrap sprintf() and automatically call $db->esc() on each string conversion specification - like this:
$db->query('INSERT INTO pages (title, content) VALUES ("%s", "%s")',
$title,
$content);
对我来说看起来不错,但现在我的问题是如何从格式化字符串中正确解析出所有的字符串转换规范,并在每个相应的参数上调用$ db-> esc() sprintf())?
That looks great to me, but now my question becomes how do I correctly parse out all the string conversion specifications from the format string and call $db->esc() on each respective argument(before passing that all to sprintf())?
你会用不同的方法吗?
推荐答案
你应该阅读关于准备声明。
准备:语句模板由应用程序创建并发送到数据库管理系统(DBMS)。某些值未指定,称为参数,占位符或绑定变量(标记为?):
Prepare: The statement template is created by the application and sent to the database management system (DBMS). Certain values are left unspecified, called parameters, placeholders or bind variables (labelled "?" below):
`INSERT INTO PRODUCT (name, price) VALUES (?, ?)`
DBMS对语句模板进行解析,编译和执行查询优化,并在不执行的情况下存储结果。
执行:稍后,应用程序为参数提供(或绑定)值,DBMS执行语句(可能返回结果)。
The DBMS parses, compiles, and performs query optimization on the statement template, and stores the result without executing it. Execute: At a later time, the application supplies (or binds) values for the parameters, and the DBMS executes the statement (possibly returning a result).
它是PHP中的补充: PDO , MySQLi , PostgreSQL 等。所以,没有理由自己实现。只需使用它。
And it's implimentation in PHP: PDO, MySQLi, PostgreSQL and other. So, there is no reason to implement it by yourself. Just use it.
这篇关于如何自动转义PHP SQL查询中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!