Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do fuzzy searches using bound parameters in PDO?

Tags:

sql

php

pdo

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?

like image 434
Polsonby Avatar asked Sep 13 '08 19:09

Polsonby


1 Answers

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();
like image 197
Polsonby Avatar answered Oct 11 '22 15:10

Polsonby