Jump to content

Search MySql


eugene2009

Recommended Posts

So im building a search form.. everything is up and running.. and it works perfectly. i just have one quick question. in my mysql database, i have a photo named bmw... and the description for it is "this is a black bmw 325i" for example.. when i search "black bmw" or "bmw 325i" the results show.. but what if i wanted to search "black 325i"? how would i be able to do that? heres me code

 

if (isset($_GET['search'])) {
   $searchTerms = trim($_GET['search']);
   $searchTerms = strip_tags($searchTerms); // remove any html/javascript.
   
   if (strlen($searchTerms) < 3) {
      $error[] = "Search terms must be longer than 3 characters.";
   }else {
      $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.
   }
   
   // If there are no errors, lets get the search going.
   if (count($error) < 1) {
      $searchSQL = "SELECT id, name, description, category FROM cars WHERE ";
      
      // grab the search types.
      $types = array();
      $types[] = isset($_GET['name'])?"`name` LIKE '%{$searchTermDB}%'":'';
      $types[] = isset($_GET['description'])?"`description` LIKE '%{$searchTermDB}%'":'';
      $types[] = isset($_GET['category'])?"`category` LIKE '%{$searchTermDB}%'":'';
      
      $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked)
      
      if (count($types) < 1)
         $types[] = "`name` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked
      
          $andOr = isset($_GET['matchall'])?'AND':'OR';
      $searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `name`"; // order by title.

      $searchResult = mysql_query($searchSQL) or die("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}");
      
      if (mysql_num_rows($searchResult) < 1) {
         $error[] = "The search term provided {$searchTerms} yielded no results.";
      }else {
         $results = array(); // the result array
         $i = 1;
         while ($row = mysql_fetch_assoc($searchResult)) {
            $results[] = "{$i}: {$row['name']}<br />{$row['description']}<br />{$row['category']}<br /><br />";
            $i++;
         }
      }
   }
}

function removeEmpty($var) {
   return (!empty($var)); 
}

Link to comment
https://forums.phpfreaks.com/topic/183139-search-mysql/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.