使用正则表达式自动添加 mysql_real_escape_string
我有一个 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'
orselect 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 PDO: http://php.net/manual/en/book.pdo.php< /a>
Use PDO: http://php.net/manual/en/book.pdo.php
这是一个坏主意,因为如果您要使用 }} 那么现在您必须转义结尾的 }}。您基本上是在发明一种新的语法来完成完全相同的事情。
请改用准备好的语句。
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.