Combine PHP prepared statments with LIKE

Solution 1:

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.'%'));

For mysqli user the following.

$test_string = '%' . $test_string . '%';
$st->bind_param('s', $test_string);
$st->execute();

Solution 2:

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.

Solution 3:

You could try something like this:

"SELECT * FROM table WHERE name LIKE CONCAT(CONCAT('%',?),'%')"

Solution 4:

in PHP using MYSQLI you need to define a new parameter which will be declared as:

$stmt = mysqli_prepare($con,"SELECT * FROM table WHERE name LIKE ?");
$newParameter='%'.$query.'%';
mysqli_stmt_bind_param($stmt, "s", $newParameter);
mysqli_stmt_execute($stmt);

this works for me..