[英]How to search mysql from php
我有一個來自用戶的查詢要在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條結果。 現在的問題是“如果我搜索包含“人蛋白質”等空格的查詢,它應該向我顯示“人蛋白質”,“人”和“蛋白質”的結果。該怎么做?
您可以執行以下操作:
$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;";
$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;";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.