php sprintf + sql like

Sometimes I do my best programming when I’m tired. Don’t ask me why, I just do. It’s a skill I picked up in college.

Being tired and producing good code wasn’t the case last night. I was trying to use the sprintf PHP function with a SQL “Like” statement. I made some dumb mistakes that tripped me up for a while. Hopefully someone out there will find this post and help them not make the problems I made, sleepy or not!

Normally the LIKE is used in mysql like this:
SELECT name FROM users WHERE name LIKE 'J%';

That would get all names including: Josh, Jason, Jimi, etc.
In a SQL Like statement the % is a wild card, so the command is to match everything starting with “J”

Now when you use the sprintf() function it looks kind like this:
$query = sprintf("SELECT name FROM users WHERE name='%s'", $searchString);
The %s will be replaced with the value of $searchString

Trying to combined them is where I had some problems….

At first I tried to do something like this:
$query = sprintf("SELECT name FROM users WHERE name LIKE'%s'", $searchString);
didnt return what I was looking for at all, it had no wild cards in it!

Then I tried this:
$query = sprintf("SELECT name FROM users WHERE name LIKE'%s%'", $searchString);
didnt work either, this time it threw errors

But this worked great
$query =
sprintf("SELECT name FROM users WHERE name LIKE '%s'", $searchString . "%");

So the moral of the story is, if you want to use a SQL Like statement, appent the wildcard for the Like statement to the string to be inserted by the sprintf funtion.