Justus Bosschieter
Justus Bosschieter

Reputation: 83

php mysqli bind_params not working

I'm trying to get a parameterized query working with the following code:

 $stmt = $mysqli->prepare("SELECT formattributes.id as attr_id, forms.title as form_title, formattributes.label as attr_label, formattributes.description as attr_description FROM formattributes
INNER JOIN forms ON forms.id = formattributes.form_id WHERE forms.title  LIKE '%?%'");

$stmt->bind_param('s', $search);
$search = $_GET['search'];

$stmt->execute();
$result = $stmt->get_result();

However after executing the query I've checked my general_log table in my mysql database and the query just didn't change:

SELECT formattributes.id as attr_id, forms.title as form_title, formattributes.label as attr_label, formattributes.description as attr_description FROM formattributes
INNER JOIN forms ON forms.id = formattributes.form_id WHERE forms.title  LIKE '%?%'

EDIT:

Finally got it working with the following code:

 $param = "%{$_POST['search']}%";
$stmt = $mysqli->prepare("SELECT formattributes.id as attr_id, forms.title as form_title, formattributes.label as attr_label, formattributes.description as attr_description FROM formattributes
INNER JOIN forms ON forms.id = formattributes.form_id WHERE forms.title  LIKE ?");
$stmt->bind_param('s', $param);
$stmt->execute();
$result = $stmt->get_result();

Thanks everyone for the help!

Upvotes: 0

Views: 113

Answers (2)

Ofir Baruch
Ofir Baruch

Reputation: 10346

Since you put the placeholder wrapped with ', it's been threaten as a regular string and not as a placeholder.

The right way would be to wrap the variable you're binding with %%:

$stmt = $mysqli->prepare("SELECT formattributes.id as attr_id, forms.title as form_title, formattributes.label as attr_label, formattributes.description as attr_description FROM formattributes
INNER JOIN forms ON forms.id = formattributes.form_id WHERE forms.title  LIKE ?");

$stmt->bind_param('s', $search);
$search = '%'.$_GET['search'].'%';

$stmt->execute();
$result = $stmt->get_result();

Similar questions:

Upvotes: 2

Patel Kishan
Patel Kishan

Reputation: 65

change blow code.

 $stmt->bind_param(':s', $search);

OR

SELECT formattributes.id as attr_id, forms.title as form_title, formattributes.label as attr_label, formattributes.description as attr_description FROM formattributes
INNER JOIN forms ON forms.id = formattributes.form_id WHERE forms.title  LIKE '%:s%'

 $stmt->bind_param(':s', $search);

Upvotes: -1

Related Questions