使用正则表达式自动添加 mysql_real_escape_string

发布于 2024-11-04 21:28:48 字数 1045 浏览 1 评论 0原文

我有一个 mysql 类,它有一个名为 query() 的方法,它基本上是 mysql_query()。此方法接收查询作为参数,如下所示:

insert into table set field1 = 'value 1', field2 = 'value 2' 或者 select id from table where field1 = 'value 1', field2 like '%value 2%'

当然,这不是一个很好的做法,因为所有值都应该首先通过 传递mysql_real_escape_string()。

我想使用正则表达式来捕获将某些信息传递给方法的所有模式,例如粗体部分:

insert into table set field1 = '**value 1**', field2 = '**value 2**'

问题是,如果我让 preg_replace 贪婪,它最终会捕获:

insert into table set field1 = '**value 1', field2 = 'value 2**'

如果它不贪婪,它会catch:

insert into table set field1 = '**value **' 1', field2 = 'value 2' (其中 returned1 实际上 = "value '1"。

一个选项是将分隔符之间的值,如下例所示,但这对我来说似乎不是最好的方法:

insert into table set field1 = {{value 1}}, field2 = {{value 2}} 然后捕获“{{”和“}}”之间的所有文本并将其替换为其 mysql_real_escape_string()'ed 值。

有没有办法以更专业的方式做到这一点?

ps:抱歉代码中有**,我不知道如何在刻度线内加粗

I have a mysql class which has a method called query() which is basically mysql_query(). This method receives the query as the parameter like this:

insert into table set field1 = 'value 1', field2 = 'value 2'
or
select id from table where field1 = 'value 1', field2 like '%value 2%'

This is not a very good practice, of course, because all the values should be first passed through mysql_real_escape_string().

I want to use a regular expression to catch all the patterns where some information is passed to the method, like the bolded sections:

insert into table set field1 = '**value 1**', field2 = '**value 2**'.

The problem is that if I let preg_replace be greedy it would eventually catch:

insert into table set field1 = '**value 1', field2 = 'value 2**'

and if it's not greedy it would catch:

insert into table set field1 = '**value **' 1', field2 = 'value 2' (where filed1 is actually = "value '1".

An option would be to put the values between a delimiter like in the following example, but this does not seem the best method to me:

insert into table set field1 = {{value 1}}, field2 = {{value 2}}
and then just catch all text between "{{" and "}}" and replace it with its mysql_real_escape_string()'ed value.

Is there a way to do this in a more professional way?

ps: sorry for having ** inside the code, I don't know how to bold inside the ticks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

囚我心虐我身 2024-11-11 21:28:48

这是一个坏主意,因为如果您要使用 }} 那么现在您必须转义结尾的 }}。您基本上是在发明一种新的语法来完成完全相同的事情。

请改用准备好的语句。

This is a bad idea, because if you were to use }} then now you'll have to escape for the closing }}. You're basically inventing a new syntax to do the exact same thing.

use prepared statements instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文