搜索只读取一个关键字:SQLSTATE [HY093]:参数号无效

时间:2015-10-23 02:52:37

标签: php mysql pdo

我的网站搜索功能存在问题。它不会处理包含多个单词的搜索字词。在http://mobile.mixtapemonkey.com/

尝试搜索栏问题的实例

搜索“这样更好” 一旦你输入B我就会收到错误。除了它的工作原理,你认为这个问题是什么?

    if (empty($errors)) {
  $name_explode = explode(' ', $name); // explode keywords to get each individual keyword, and put into array
  $name_count = count($name_explode); // count keywords from array
  foreach($name_explode as $name_single) {
    $x++; // increment x each loop

    $keyword = "%".$name_single."%";

    $where .= '`keywords` LIKE :keyword'; // append to where clause
    if ($name_count!=$x) {
      $where .= ' AND '; // as long as keyword isn't the last, append AND.
    }
  } 

  $sql = "SELECT `name`, `thumb`, `id`, `title` FROM `mixtapes` WHERE ".$where." ORDER BY `id` DESC LIMIT 40";

  $search = $db->prepare($sql); // perform query

  $search->bindParam(':keyword', $keyword, PDO::PARAM_STR);

  $search->execute();

  $search_num_rows = $search->rowCount(); // get number of rows (results) returned

1 个答案:

答案 0 :(得分:1)

请检查我添加的代码。您收到错误的原因是由于您的foreach循环。在该循环中,您每次都会添加:keyword。但该计数与bindParam值计数不匹配。所以我改变了你的代码并发布在

下面
if (empty($errors)) {
$name_explode = explode(' ', $name); // explode keywords to get each individual keyword, and put into array
$name_count = count($name_explode); // count keywords from array
$x = 0;
foreach($name_explode as $name_single) {
$x++; // increment x each loop

$keyword[':keyword'.$x] = "%".$name_single."%";

$where .= '`keywords` LIKE :keyword'.$x; // append to where clause
if ($name_count!=$x) {
  $where .= ' OR '; // as long as keyword isn't the last, append AND.
}
} 

$sql = "SELECT `name`, `thumb`, `id`, `title` FROM `mixtapes` WHERE ".$where." ORDER BY `id` DESC LIMIT 40";

$search = $db->prepare($sql); // perform query


$search->execute($keyword);

$search_num_rows = $search->rowCount(); //