Reputation: 140
I'm about to create the search engine for my website. It's actually the first time I try to do such a thing, so I took a look around the internet and also here on StackOverflow, but I still have some questions, so I hope you can give me some advice.
Now, considering this simplified version of the table in which I should search:
+----+--------+------------+
|ID | Title | Description|
+----+--------+------------+
|1 | Title1 | Lorem ipsum|
+----+--------+------------+
|2 | Title2 | Dolor sit |
+----+--------+------------+
and this string, written by the user in the search bar:
Lorem ipsum dolor sit amet.
I thought something like:
$string = mysqli_real_escape_string($_GET['string']);
$words = explode(' ', $string);
$count_words = count($words);
Then I have two options.
Select every row from the table and then check if the elements of the array $words are part of a field:
$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
}
}
Or maybe, is better something like:
for($i = 0; $i < $count_words, $i++) {
$search_query = "SELECT * FROM 'table' WHERE 'title' = '". $words[$i] . "'";
}
Which is: Is it better to select everything first, and then check the data, or select only the rows which fit the string? Or, maybe, is there something like a standard way to write this script?
Thanks in advance.
Upvotes: 0
Views: 133
Reputation: 333
Try with something like this instead:
$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;
You can try this at here
Upvotes: 1
Reputation: 375
You could use:
$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);
I hope that this is useful for You.
Upvotes: 1