如何在字符串mysqli PHP中绑定参数

时间:2016-02-02 14:33:08

标签: php mysql mysqli

我正在尝试使用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 title LIKE %?%';),则参数会正确绑定,但SQL语法无效。如何绑定此LIKE查询?

2 个答案:

答案 0 :(得分:3)

绑定不像复制和粘贴替换那样工作。您需要将?代替 。然后,您绑定的值必须包含%

$q = '... LIKE ?';

...

$theValue = "%$theValue%";
$statement->bind_param('s', $theValue);

答案 1 :(得分:0)

要在SQL中包含字符串,请使用撇号而不是引号。不支持报价。在PHP中将字符串包装成引号:

$q .= " AND `title` LIKE CONCAT('%', ?, '%')";