0

我有一个用户查询要在 mysql 数据库中搜索

<input type="text" name="query_textbox"><input type="submit" name="search_button">
<?php 
   if (isset($_GET['search_button'])) 
   {
    $query = $_GET['query_textbox'];
    $command = "SELECT * FROM `table` WHERE `ProteinName` LIKE '%$query%';";
    $result = mysql_query($command);
    echo $result;
   }
?>

当我在文本框中输入“人类”时,它就可以工作了。但是当我搜索“人类蛋白质”时,它显示 0 个结果。现在的问题是“如果我搜索包含诸如‘人类蛋白质’之类的空格的查询,它应该向我显示‘人类蛋白质’以及‘人类’和‘蛋白质’的结果。怎么做?

4

2 回答 2

2

你可以这样做:

$query = $_GET['query_textbox'];

// explode the query by space (ie "human protein" => "human" + "protein")
$keywords = preg_split("#\s+#", $query, -1, PREG_SPLIT_NO_EMPTY);

// combine the keywords into a string (ie "human" + "protein" => "'%human%' OR '%protein%'")
$condition = "'%" . implode("%' OR '%", $keywords) . "%'";

$command = "SELECT * FROM `table` WHERE `ProteinName` LIKE $condition;";
于 2013-02-06T06:22:38.460 回答
-1
$query = $_GET['query_textbox'];

// explode the query by space (ie "human protein" => "human" + "protein")
$keywords = explode(" ", $query);

foreach($keywords as $key => $value){
    $condition[] = `ProteinName` LIKE "'%".$value."%'"
}

$cond_str = implode(' OR ', $condition);
$command = "SELECT * FROM `table` WHERE $cond_str;";
于 2013-02-06T06:37:58.043 回答