簡體   English   中英

PHP網站搜索引擎

[英]Search engine for a website in PHP

我將為我的網站創建搜索引擎。 這實際上是我第一次嘗試這樣做,所以我在Internet上以及StackOverflow上進行了瀏覽,但是我仍然有一些疑問,所以希望您能給我一些建議。

現在,考慮應該在其中搜索的表格的簡化版本:

+----+--------+------------+
|ID  | Title  | Description|
+----+--------+------------+
|1   | Title1 | Lorem ipsum|
+----+--------+------------+
|2   | Title2 | Dolor sit  |
+----+--------+------------+

以及用戶在搜索欄中輸入的以下字符串:

Lorem ipsum dolor sit amet.

我想到的是:

$string = mysqli_real_escape_string($_GET['string']);
$words = explode(' ', $string);
$count_words = count($words);

然后我有兩個選擇。

從表中選擇每一行,然后檢查$ words數組的元素是否屬於字段:

$description_array = explode(' ', $description); // I get this var from the query
for($i = 0; $i < $count_words; $i++) {

 if(in_array($words[$i]), $description_array) {
   // Something here
  }

}

或者,也許是更好的東西,例如:

for($i = 0; $i < $count_words, $i++) {
 $search_query = "SELECT * FROM 'table' WHERE 'title' = '". $words[$i] . "'";
}

這是:首先選擇所有內容, 然后檢查數據,還是僅選擇適合字符串的行更好嗎? 或者,也許有類似標准的方式編寫此腳本嗎?

提前致謝。

您可以使用:

$wordsToSearch = array();

$string = mysqli_real_escape_string($_GET['string']);
$words = explode(' ', $string);

foreach($word as $val){
  $w = "`title` LIKE '%".$val."%' OR `description` LIKE '%".$val."%'";
  $wordsToSearch[] = $w;
}

$search_query = "SELECT * FROM 'table' WHERE ".implode("OR",$wordsToSearch);

我希望這對您有用。

嘗試使用類似這樣的方法:

$string = mysqli_real_escape_string(trim($_GET['string']));
$words = explode(' ', $string);

//Check if the user wrote more than a single word
if (count($words)>1) {
    //Then you can create only one query and then you can fetch the result of that
    //Implode the words
    $search_query = "SELECT * FROM table WHERE title='".implode("' OR title='", $words)."'";
}
else { //If the user wrote only one word
    $search_query = "SELECT * FROM table WHERE title='".$string."'";
}
echo $search_query;

你可以在這里試試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM