How do you do fuzzy searches using bound parameters in PDO?
Question
Trying to do this sort of thing...
WHERE username LIKE '%$str%'
...but using bound parameters to prepared statements in PDO. e.g.:
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
I've tried numerous permutations of single quotes and % signs and it's just getting cross with me.
I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters?
Solution
Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine:
$str = "%$str%";
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
OTHER TIPS
5 years later, in case anyone else stumbles upon this, there is an alternative method I've discovered. The accepted solution wasn't really feasible for my situation, but this method seems to get the job done as well:
$query = $db->prepare("select * FROM table WHERE field LIKE CONCAT('%',:search,'%')");
$query->bindParam(':search', $str);
$query->execute();
I'm not sure if there will be a performance hit due to the overhead of calling the CONCAT
function, but I wanted to pass this along as an option. Hopefully it will help someone.