【问题标题】:multiple LIKE does not work in PDO (PHP)多个 LIKE 在 PDO (PHP) 中不起作用
【发布时间】:2015-04-24 16:39:14
【问题描述】:

嘿,我在我的 PDO 函数中有这个,我想用相同的输入($string)检查我的数据库的 2 列。这来自我的 HTML 搜索框。我想要一个数组中的结果。但是,使用此代码,它只检查 genre 列而不是 name 列。但它应该检查两列。有什么帮助吗?谢谢。

public function search($string){
    $question = '%' . $string . '%';
    $sql = "SELECT * FROM `products` WHERE `name` OR `genre` LIKE :q";
    $stmt = $this->pdo->prepare($sql);
    $stmt->bindValue(':q', $question);
    $stmt->execute();
    $data = '%$data%';
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

使用此查询时出现此错误:

$sql = "SELECT * FROM `products` WHERE `name` like :q OR `genre` LIKE :q";

致命错误:带有消息的未捕获异常“PDOException” 'SQLSTATE[HY093]: 参数号无效' in /Applications/MAMP/htdocs/bad/bad/dao/ProductsDAO.php:32 堆栈跟踪: #0 /Applications/MAMP/htdocs/bad/bad/dao/ProductsDAO.php(32): PDOStatement->execute() #1 /Applications/MAMP/htdocs/bad/bad/controller/ProductsController.php(24): ProductsDAO->search('pokemon') #2【内部函数】: ProductsController->index() #3 /Applications/MAMP/htdocs/bad/bad/controller/Controller.php(9): call_user_func(Array) #4 /Applications/MAMP/htdocs/bad/bad/index.php(50): 控制器->filter() #5 {main} 在第 32 行的 /Applications/MAMP/htdocs/bad/bad/dao/ProductsDAO.php 中抛出

【问题讨论】:

  • 答案已编辑,请检查更改。如果您有任何疑问或错误,请告诉我。

标签: php pdo sql-like


【解决方案1】:

您的查询没有将值传递给 Where 子句,而只是传递了列名。 我还编辑了您将参数传递给执行的方式。

您遇到的错误是由于(文档摘录):

当您调用 PDOStatement::execute() 时,您必须为希望传递给语句的每个值包含一个唯一的参数标记。您不能在准备好的语句中两次使用同名的命名参数标记。您不能将多个值绑定到单个命名参数,例如 SQL 语句的 IN() 子句。

所以我已经编辑了答案。

试试这个:

修改这行:

$sql = "SELECT * FROM `products` WHERE `name` OR `genre` LIKE :q";
$stmt->bindValue(':q', $question);
$stmt->execute();

对于这个:

$sql = "SELECT * FROM `products` WHERE `name` LIKE :name OR `genre` LIKE :genre";
$params = array('name' => $question, 'genre' => $question); //or :name and :genre
$stmt->execute($params);

如果您仍然遇到错误,请查看文档,其中包含一些示例。 PHP PDOStatement::execute Documentation

【讨论】:

  • 它仍然无法正常工作,我仍然遇到同样的错误。
  • 还是不做:(
【解决方案2】:

试试这个:

public function search($string){
    $question = "%".$string."%";
    $sql = "SELECT * FROM `products` WHERE `name` LIKE :n OR `genre` LIKE :q";
    $stmt = $this->pdo->prepare($sql);
    $stmt->bindValue(':q', $question);
    $stmt->bindValue(':n', $question);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

【讨论】:

  • 感谢您的成功。你刚刚保存了我的学校项目
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 2013-01-03
  • 2011-02-11
  • 2017-08-13
相关资源
最近更新 更多