tags:

views:

365

answers:

1

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?

+2  A: 

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();
Flubba
Glad you found it. I just found it the other day, too, looking for the same thing. Too bad you can't accept your own answer!
Brian Warshaw
Aha - they fixed it - you can now accept your own answer. Good for using StackOverflow as a library
Flubba