tags:

views:

157

answers:

3

Anyone know how to combine PHP prepared statements with LIKE? i.e.

"SELECT * FROM table WHERE name LIKE %?%";

+9  A: 

The % signs need to go in the variable that you assign to the parameter, instead of in the query.

I don't know if you're using mysqli or PDO, but with PDO it would be something like:

$st = $db->prepare("SELECT * FROM table WHERE name LIKE ?");
$st->execute(array('%'.$test_string.'%'));
Chad Birch
+2  A: 

You can use the concatenation operator of your respective sql database:

# oracle
SELECT * FROM table WHERE name LIKE '%' || :param || '%'
# mysql
SELECT * from table WHERE name LIKE CONCAT('%', :param, '%')

I'm not familar with other databases, but they probably have an equivalent function/operator.

Richard Levasseur
That won't work with strings. It will throw warnings about non-integers.
St. John Johnson
He's probably coming from an Oracle background, that's the Oracle concatenation operator, but in MySQL it's the OR operator. In MySQL you'd have to do CONCAT('%', ?, '%')
Chad Birch
ah, noted! I haven't used mysql in years.
Richard Levasseur
A: 

You could try something like this:

"SELECT * FROM table WHERE name LIKE CONCAT(CONCAT('%',?),'%')"
St. John Johnson