php mysqli bind_params无效

时间:2015-10-08 12:09:54

标签: php mysqli parameters bind params

我尝试使用以下代码获取参数化查询:

 $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();

然而,在执行查询后,我已经检查了我的mysql数据库中的general_log表,并且查询没有改变:

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 '%?%'

编辑:

最后让它使用以下代码:

 $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();

感谢大家的帮助!

2 个答案:

答案 0 :(得分:2)

由于您将占位符包装为',因此它已被威胁为常规字符串而不是占位符。

正确的方法是将您绑定的变量包装为%%

$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();

类似问题:

答案 1 :(得分:-1)

更改打击代码。

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

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);