Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Binding a Wildcard [duplicate]

Hope Somebody will help me about how I bind a parameter in mysqli when a multiple character wildcard needs to be next to the variable value. I found that it worked for me when creating a SQL statement, like this:

$sql = "SELECT item_title FROM item WHERE item_title LIKE '%$title%'";

However, I tried to bind the variable following the same pattern, and found that it failed. They used this code:

$sql = "SELECT item_title FROM item WHERE item_title LIKE '%?%'";

It raised this error:

Warning: mysqli_stmt_bind_param() [function.mysqli-stmt-bind-param]: Number of variables doesn't match number of parameters in prepared statement in program_name on line......

Can anybody tell me how fix this problem? Thank you.

like image 904
TNK Avatar asked Nov 01 '25 06:11

TNK


2 Answers

You can bind only data literals not arbitrary query parts.
So, prepare your literal first

$var = "%$var%";
$sql = "SELECT item_title FROM item WHERE item_title LIKE ?";
like image 198
Your Common Sense Avatar answered Nov 03 '25 21:11

Your Common Sense


You can do like this way:

$sql = "SELECT item_title FROM item WHERE item_title LIKE ? ";

and then

$title_new =  '%'.$title.'%';
mysqli_stmt_bind_param($stmt, 's', $title_new);    

Updated based on user's comment

To implement below SQL

 s2.subject_name LIKE '%$keyword%' OR c.city_name LIKE '%$keyword%' 

Use below MySqli statement s2.subject_name LIKE ? OR c.city_name LIKE ?

 $keyword = '%'.$keyword.'%';
 mysqli_stmt_bind_param($stmt, 'ss', $keyword, $keyword);
like image 28
Minesh Avatar answered Nov 03 '25 21:11

Minesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!