There may not be a fully portable answer to this. My best guess for a concise answer would be: "... LIKE '%" . quotemeta($str) . "%' ..." but I fear that some database won't handle all of the potential backslashes. So a more conservative approach might be called for:
but then some databases might support things other than %, _, and [chars] in their LIKE constructs so the first answer might be better.my $pattern= $string_from_user; $pattern =~ s#(['%_\[\]])#\\$1#g; "... LIKE '%$pattern%' ..."
Do all databases even support \ for escaping LIKE "wildcards"? What about for escaping single quotes (apostrophes)? I believe that using two consecutive apostrophes to represent a single apostrophe when inside of an apostrophe-delimited string is part of the SQL standard. So 'don''t' = "don't" in SQL. I've long been curious what the standard says about LIKE strings but have always ended up looking up what my current database supports instead (which has always been the use of \ to escape things).
In dealing with MySQL for PerlMonks, I found what I consider to be a quirk. If I want to find all strings containing a backslash followed by a percent sign (\%), I have to tell MySQL LIKE '%\\\\\%%' (which means I'd have to tell Perl "... LIKE '%\\\\\\\\\\%%' ...") because, when I use what I would have expected to work (LIKE '%\\\%%'), it appears that some backslahses are consumed when MySQL parses the single-quoted string and the LIKE operation ends up seeing %\\%%, which finds strings that contain just a backslash.
So you might have to resort to:
So I fear you'll have to test and use what works for your current database. This should probably be abstracted by DBI but I don't believe that it currently is. - tye# Escape "wildcard" characters in user input: my $pattern= quotemeta($string_from_user); # Escape things processed by 'single quote' parsing: $pattern =~ s#([\\'])#\\$1#g; "... LIKE '%$pattern%' ..."
In reply to Re: DBI, quoting, and LIKE searches (no good answer)
by tye
in thread DBI, quoting, and LIKE searches
by Mr_Person
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |