Search code examples
phpmysqlsearch-engine

How to make exact keyword search appear first?


I made a mysql/php search engine in which I added google url with keywords google search engine and another yahoo url with keywords yahoo search engine. If I type google search engine on the search box how do I make google url appear first?

This is the code:

//connect to database
  mysql_connect("","","");
  mysql_select_db("");

   //explode out search term
   $search_exploded = explode(" ",$search);

   foreach($search_exploded as $search_each)
   {

        //construct query
    $x++;
    if ($x==1)
     $construct .= "Keywords LIKE '%$search_each%'";
    else
     $construct .= " OR Keywords LIKE '%$search_each%'";

   }

  //echo outconstruct
  $constructx = "SELECT * FROM searchengine WHERE $construct";

  $construct = "SELECT * FROM searchengine WHERE $construct LIMIT $s,$e";
  $run = mysql_query($constructx);

  $foundnum = mysql_num_rows($run);


  $run_two = mysql_query("$construct");

  if ($foundnum==0)
   echo "No results found for <b>$search</b>";
  else

Solution

    1. To find count of entries, you can use SELECT count(*) instead of mysql_num_rows with full query.
    2. To sort results, you need to use "ORDER BY" in query, and some field, which will be criteria of ordering. In your case you can write
      $construct = "SELECT * FROM searchengine WHERE $construct ORDER BY Keywords LIMIT $s,$e ";

    And don't forget to sanitize your $search.
    $search = mysql_real_escape_string($search);