scriptygoddess

12 Feb, 2003

sprintf and mySQL's "LIKE"

Posted by: Jennifer In: Lessons learned

Chalk this up to "not one of my finer (smarter) moments". This is so silly, I probably shouldn't even admit to not realizing this – but I'm putting it here so I never forget it again.

I had wanted to run a SELECT query where the conditional would be set with the "LIKE" – but I needed to construct the query using the sprintf() function.

Normally the LIKE is used in mysql like this:

SELECT firstname, lastname FROM users WHERE lastname LIKE '%son';

That would get all lastnames including: Johnson, Jameson, etc. etc. Now when you use the sprintf() function it looks kind like this:

$query = sprintf("SELECT firstname, lastname FROM users WHERE lastname='%s';", $_REQUEST['Jameson']);

The brain-fart I had was with the wildcard "%" and the "%s". Doing this gave me errors.

$query = sprintf("SELECT firstname, lastname FROM users WHERE lastname LIKE '%%s';", $_REQUEST['son']);

Don't ask me why it took me as long as it did to realize this is what you had to do:

$query = sprintf("SELECT firstname, lastname FROM users WHERE lastname LIKE '%s';", "%".$_REQUEST['son']);

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

No Responses to "sprintf and mySQL's "LIKE""

Comments are closed.

Featured Sponsors


  • Curt: If anyone comes across this with similar issues I was able to sort out the pagination issues painlessly with easyCommentsPaginate from http://www.mush
  • Christopher: Yeah, it is indeed hard to do. And something remains elusive about why the pagination never worked. I tried everything I could find. Regardless, I
  • Jennifer: Hi Christopher, always hard to bug test stuff like that remotely. Sorry those didn't help. Glad you found a solution though :)

About


Advertisements