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 Responses to "sprintf and mySQL's "LIKE""

Comments are closed.

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements