0

Cant seem to figure out whats wrong, the query should be correct, and it works in phpMyAdmin but when I introduce a wildcard into the php string "%", every query fails.

This works:

$query = sprintf("SELECT `id`FROM `table`WHERE `name` LIKE '".$resources[1]."'", 
                                                                   mysql_real_escape_string($resources[1]));

This does not:

$query = sprintf("SELECT `id`FROM `table`WHERE `name` LIKE '%".$resources[1]."%'", 
                                                                   mysql_real_escape_string($resources[1]));

The query Im obviously trying to generate is

SELECT `id` FROM `table`WHERE `name` LIKE '%someName%'
4
  • What does echo $query; tell you? Can you make an example of that kind of value you are searching? Don't forget that a leading % requires that there be something in front of the value, so searching for %Michael% will not give you MichaelTaylor Commented Feb 14, 2013 at 18:36
  • it doesnt generate at all when I introduce the wildcard, without the wildcard it generates as it should Commented Feb 14, 2013 at 18:36
  • You mean $query is empty in the second example? That seems unlikely. Commented Feb 14, 2013 at 18:37
  • I agree with you but that is what is happening, and the only difference is when I introduce the wildcard, when the wildcard is absent, echo $query comes out as it should Commented Feb 14, 2013 at 18:39

1 Answer 1

2

Read the sprintf man page: http://php.net/sprintf

$sql = sprintf('..... '%%%s%%', $var);
                       ^^--- turns into %
                         ^--  %s -> $var
                           ^^-- turns into %

Your code, as written, does NOTHING to prevent sql injection, since you're not using sprintf() properly.

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

2 Comments

SQL injection is already protected against elsewhere in the code, that isnt what I was asking about.
However you are correct that I wasnt using sprintf properly and that was what was causing the problem

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.