我正在尝试使用 mysqli 在 SQL 中的 LIKE 语句中绑定参数,如下所示:
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
$q = 'SELECT * from `books`';
if (!isblank($title) || !isblank($author) || !isblank($isbn)) {
$q .= ' WHERE 1 = 1';
}
if (!isblank($title)) {
$q .= ' AND `title` LIKE "%?%"';
}
if (!isblank($author)) {
$q .= ' AND `author` LIKE "%?%"';
}
if (!isblank($isbn)) {
$q .= ' AND `isbn` = ?';
}
echo $q;
if ($statement = $db->prepare($q)) {
if (!isblank($title) && !isblank($author) && !isblank($isbn)) {
$statement->bind_param('sss', $title, $author, $isbn);
} else if (!isblank($title) && !isblank($author)) {
$statement->bind_param('ss', $title, $author);
} else if (!isblank($title) && !isblank($isbn)) {
$statement->bind_param('ss', $title, $isbn);
} else if (!isblank($author) && !isblank($isbn)) {
$statement->bind_param('ss', $author, $isbn);
} else if (!isblank($title)) {
$statement->bind_param('s', $title);
} else if (!isblank($author)) {
$statement->bind_param('s', $author);
} else {
$statement->bind_param('s', $isbn);
}
if ($statement->execute()) {
$statement->bind_result($returned_book); // hello carlo how are you today
while ($statement->fetch()) {
echo var_dump($returned_book);
}
}
}
问题是 mysqli 会声明没有足够的参数可以绑定,因为?
在字符串中。如果我去掉引号($q .= ' AND
标题LIKE %?%';
),参数绑定正确,但SQL语法无效。如何绑定到此 LIKE 查询?
绑定
不像复制和粘贴替换那样起作用。您需要将?
放在值的位置。然后,要绑定的值必须包含以下%
:
$q = '... LIKE ?';
...
$theValue = "%$theValue%";
$statement->bind_param('s', $theValue);
若要将字符串括在 SQL 中,请使用撇号而不是引号。不支持引号。在 php 中,将字符串包装成引号:
$q .= " AND `title` LIKE CONCAT('%', ?, '%')";