php - 搜索只读到一个关键字 : SQLSTATE[HY093]: Invalid parameter number

标签 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

最佳答案

请检查我添加的代码。出现该错误的原因是您的 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(); //

关于php - 搜索只读到一个关键字 : SQLSTATE[HY093]: Invalid parameter number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33294116/

相关文章:

java - 在 JPA 中获取单列值

php - PDO 类的通用插入方法

php - 在php中打开javascript函数

mysql - 如何通过排除特定日期来获取过去的第七个日期

php - PDO exec 不工作,数据库仍然是空的

php - $_SESSION ['uiD' ] 注册后无法重定向到主页,uiD 未设置

php - mysql 左连接和返回已连接和未连接

php - 在php中计算地球上两个坐标之间的行驶距离

php - Joomla 插件 : "Another plugin is already using the named folder"

PHP/MySQL : How to return info if record already exists (without update)