如何使用SQL搜索来搜索多个关键字

时间:2019-11-05 08:32:42

标签: php sql

我有一个当前的SQL搜索查询,该查询允许用户输入关键字来搜索我的SQL数据库。目前,搜索将使用多个单词,但将显示任一关键字的所有结果。如果您输入“ Ford Mustang”,它将显示所有具有“ Ford”或“ Mustang”的结果,但是我需要它仅显示同时显示“ Ford”和“ Mustang”的结果。

我尝试过的是下面的

public function getProductByName($name){
    $stmt = $this->pdo->prepare('SELECT * FROM tbl_products WHERE name REGEXP :names');
    $names = "[[:<:]](" . str_replace(" ", "|", $name) . ")[[:>:]]";
    $stmt->execute(array('names' => $names));
    return $stmt;
}

2 个答案:

答案 0 :(得分:1)

也许这就是您要寻找的

  

从示例中选择*,例如“%mustang%ford%”

答案 1 :(得分:0)

您可以编写查询

select * from tbl_products where name like "%Mustang%" and name like "%ford%";

PHP代码

//you may split search string like
$searchArray = explode(' ', $name);

//for loop for preparing the query
$query = 'SELECT * FROM tbl_products WHERE ';
$searchParams = array();
$conditions = [];
for($searchArray as $searchStr){
    $conditions[] = 'name like ?';
    $searchParams[] = "%$searchStr%";
}

//attach the conditions
$query .= implode(" and ", $conditions);

//execute the query 
$stmt = $this->pdo->prepare($query);

$stmt->execute($searchParams);