开发者

adding mysql_real_escape_string automatically with regexp

开发者 https://www.devze.com 2023-03-03 04:32 出处:网络
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:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号