in reply to SQL LIKE and Binding Variables
First (for mysql, at least) the way to include a literal "%" or literal "_" as part of the search condition in the "LIKE" value is to put a backslash in front of that character -- e.g. % 1\_000\% % will match any string field value that contains a literal " 1_000% ", with anything (or nothing) before and after.
As a more general method for conjoining different "like" conditions (updated as per "###" comments):
(I like putting parens around a set of related "OR" conditions -- it's a handy safeguard in case I need to include some other condition using "AND".)my @sources = ( 'artist 1', 'artist 2', 'whatever' ); ### we make an +array first... my @values = map { s/([_%])/\\$1/g; "%$_%" } @sources; ### ...to avoi +d an error here my $like_clause = join( " or ", map { "Songs.Artist LIKE ?" } @values; my $sth = $dbh->prepare( "SELECT * FROM Songs where ($like_clause)" ); $sth->execute( @values );
UPDATE: Sorry about having posted unusable code earlier -- I should have tested my initial version, to see that it produced the error mentioned in Mad_Mac's reply below. My code has been fixed now, as indicated in the comments above.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: SQL LIKE and Binding Variables
by Mad_Mac (Beadle) on Nov 03, 2009 at 22:23 UTC | |
by Anonymous Monk on Nov 03, 2009 at 23:07 UTC |