如何在准备好的SQL语句中绑定参数?

时间:2012-05-06 14:44:23

标签: php sql prepared-statement

我想使用预处理语句查询我的MySQL数据库。查询应如下所示:

SELECT name, idname FROM names WHERE origin='english' AND name like('%a%')"

这个很棒:

$origin = "english";
$stmt = $mysqli->prepare("SELECT name, idname FROM names WHERE origin=? AND name like('%a%')"))
$stmt->bind_param("s", $origin);

但这根本不起作用(即使没有错误):

$origin = "english";
$letter = "a";
$stmt = $mysqli->prepare("SELECT name, idname FROM names WHERE origin=? AND name like(%?%)")) 
$stmt->bind_param("ss", $origin, $letter);

请注意上一学期like。我不知道如何绑定第二个参数letter

1 个答案:

答案 0 :(得分:1)

使用LIKE语句将值传递给CONCAT谓词。

更正版本:

$origin = "english";
$letter = "a";
$stmt = $mysqli->prepare("SELECT name, idname FROM names WHERE origin=? 
AND name LIKE CONCAT('%',?,'%')")) 
$stmt->bind_param("ss", $origin, $letter);