Search engine results, like ordering as "best" match/results

Viewed 23

What is the best way to order my results by those that match best, currently it seems they are in alphabetical order. See Illustration. I want it so that when you search google that the results with title google are first.

I'm trying to develop a mini search engine.

<style>
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
</style>

<form action="" method="GET">
  <label for="search">Query:</label>
  <input type="search" id="search" name="s" value="<?php echo $_GET['s']; ?>"><br>
  <input type="submit" value="Submit">
</form> 
<?php
include 'includes/config.php';

if(!empty($_GET))
{

    $search_string = $_GET['s'];
    $searchTerms = explode(' ', $search_string);
    $searchTermBits = array();
    foreach ($searchTerms as $term) {
        $term = trim($term);
        if (!empty($term)) {
            $searchTermBits[] = "keywords.word LIKE '%$term%'";
        }
    }

   print_r($searchTermBits);
   echo "<hr>";
   echo implode(' AND ', $searchTermBits);


    $query = $_GET['s'];

    $stmt = $pdo->prepare(
                "SELECT links.title, links.URL, count(*) 
                FROM links, link_word, keywords 
                WHERE links.link_id = link_word.link_id 
                AND link_word.key_id = keywords.key_id 
                AND ".implode(' OR ', $searchTermBits)." 
                OR links.title LIKE ? GROUP BY URL");

    $stmt->execute(['%'.$query.'%']); 
    
    echo "<ul>";
    while ($row = $stmt->fetch()) {
        echo "<li><a href='".$row['URL']."'>".$row['title']."</a><li><small style='color: grey;'>".$row['URL']."</small>";
    }
    echo "</ul>";
}
?>
1 Answers

something like that?

SELECT links.title, links.URL, count(*) 
FROM links, link_word, keywords 
WHERE links.link_id = link_word.link_id 
AND link_word.key_id = keywords.key_id 
AND ".implode(' OR ', $searchTermBits)." 
OR links.title LIKE ? GROUP BY URL
order by (case when links.title like '%google%' then 1 else 0 end) desc, name
Related