0

Suppose i want to run query like this:

$q = "SELECT * FROM items WHERE name LIKE $1";
$r = pg_query_params($dbconn, $q, array("%" .  $ss . "%"));

The problem may arise if user has supplied string with % or _ for $ss. How can i tell engine to not consider % and _ in $ss as special symbols?


For now my approach is

$q = "SELECT * FROM items WHERE name LIKE $1 ESCAPE '\'";
$r = pg_query_params($dbconn, 
         $q, 
         array("%" . str_replace("%", "\%", str_replace("_", "\_", $ss)) . "%"));

But what if escape character (\) is the last one in the string, then appended % will be escaped as well.

1 Answer 1

3

The first suggestion is to eschew LIKE. Just do:

SELECT * FROM items WHERE position($1 in name) > 0;

Then you don't have to worry about special characters.

You can use ESCAPE . . . but you need something that is not in the string, say ~.

SELECT * FROM items WHERE name LIKE $1 ESCAPE '~'

Then when you bind the parameter:

$r = pg_query_params($dbconn, $q,
                     array("%" . str_replace(str_replace($ss, "_", "~_"), "%", "~%") . "%"));

You can escape the escape character by doubling it. That is just another str_replace():

$r = pg_query_params($dbconn, $q,
                     array("%" . str_replace(str_replace(str_replace($ss, "~", "~~"), "_", "~_"), "%", "~%") . "%"));

Alternatively, make the use of LIKE a feature, and let the users put in wildcards, because they then have more powerful search capabilities.

Sign up to request clarification or add additional context in comments.

3 Comments

Any character could be in the string and in any position, that is one of my concerns
@Yola . . . I modified the answer. But on second thought, see the first solution. LIKE is not the right operator for what you want to do.
Great! Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.