4

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

$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

 }

目前它正在整体搜索术语,例如“red desk”返回结果但“desk red”不返回任何内容

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

编辑:

从那以后我把它改成了这个......

   $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(); 

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

4

1 回答 1

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(); 
于 2012-09-17T04:07:50.870 回答