PDO - 搜索是整体查询术语而不是单独查询每个术语

时间:2012-09-16 21:59:29

标签: php mysql search pdo prepared-statement

我目前有一个简单的搜索引擎,它根据用户的输入搜索数据库中的列:

$search = $_GET['search'];
$terms = explode(" ", $search);

        $sql = "SELECT * FROM people WHERE lname LIKE :search";
    $q   = $conn->prepare($sql) or die("failed!");
    $q->bindValue(':search',"%".$search."%",PDO::PARAM_STR);
    $q->execute();

 if ($q){

 //
 do something

 }

目前它正在搜索整个术语,例如“红色桌面”返回结果但“桌面红色”不返回任何内容

有什么想法吗?任何帮助非常感谢!

编辑:

我已将其改为此...

   $search = $_GET['search'];
   $terms = explode(" ", $search);

        $sql = "SELECT * FROM people WHERE MATCH (lname,fname) AGAINST  (:search IN BOOLEAN MODE)";
    $q   = $conn->prepare($sql) or die("failed!");
    $q->bindValue(':search',"%".$search."%",PDO::PARAM_STR);
    $q->execute(); 

现在似乎工作正常,如果有人能提出更好的解决方案,我会非常感激!

1 个答案:

答案 0 :(得分:1)

这可能不是最好的方法,但我认为这样的事情可能会起作用。我本想知道是否有更聪明的方法来做到这一点!

$search = $_GET['search'];
$terms = explode(" ", $search);

$sql = "SELECT * FROM people"
if(count($terms) > 0) {
  $sql .= " WHERE (lname LIKE '%:term_0%' OR fname LIKE '%:term_0%')";
  for($i = 1; $i < count($terms); $i++)
    $sql .= " AND (lname LIKE '%:term_" . $i . "%' OR fname LIKE '%:term_" . $i . "%')";
}

$q = $conn->prepare($sql) or die("failed!");

for($i = 0; $i < count($terms); $i++)
  $q->bindValue(':term_' . $i, $terms[$i]);
$q->execute();