0

I'm going to write a simple search on products table, and when user is searching for something I use product_name LIKE %search_term% to search the product table. But I need to sort them by relevance.

I'm using ZEND freamwork and my database is MySQL

Mohammad Kermani
  • 5,188
  • 7
  • 37
  • 61

1 Answers1

0

Here someone asked about how to ORDER BY relevance in MySQL and someone suggested a good query for that, what you need to do is:

 SELECT  product_name
  FROM products
 WHERE product_name like '%search_term%'
 GROUP BY name
 ORDER BY CASE WHEN product_name like 'search_term %' THEN 0
               WHEN product_name like 'search_term%' THEN 1
               WHEN product_name like '% search_term%' THEN 2
               ELSE 3
          END, product_name

You will get the search_term from user, and have to check it by mysql_real_escape_string for security reasons, but we can't use mysql_real_escape_string in ZEND. Then we have to check it by ZEND, we use quote() instead of mysql_real_escape_string.

//get the search_term what user is looking for:
 $search_term=$this->parameters['search_term'];

//mysql_real_escape_string:
$search_term= $this->db->quote($search_term);
$search_term = substr($search_term, 1, strlen($search_term)-2); //Remove quotation from it.

$query = $this->db->select();
$query->from('products', ['product_id', 'product_name', 'product_sub_name']);
$query->where('product_name LIKE ?', '%'.$search_term.'%');
$query->group('product_name');
$query.="
   ORDER BY CASE WHEN product_name like '$search_term %' THEN 0
        WHEN product_name like '$search_term%' THEN 1
        WHEN product_name like '% $search_term%' THEN 2
        ELSE 3
        END, product_name";

return $this->db->fetchAll($query);

This will return what you need, and sort by relevant according to the above SQL query that I found here

If you are going to limit your search, you can easily add it to the $query variable. Then you will have (For example limit it to 10 results):

$query.="
   ORDER BY CASE WHEN product_name like '$search_term %' THEN 0
      WHEN product_name like '$search_term%' THEN 1
      WHEN product_name like '% $search_term%' THEN 2
      ELSE 3
      END, product_name
      LIMIT 0 , 10";
Community
  • 1
  • 1
Mohammad Kermani
  • 5,188
  • 7
  • 37
  • 61
  • `mysql_real_escape_string()` was removed in PHP7. The ZF way of quoting strings is the correct one. – Tim Fountain Feb 24 '16 at 10:46
  • @TimFountain Yes you are right, but I just wanted to give an example, and people know mysql_real_escape_string(), I think this is better to make the answer more clear for them – Mohammad Kermani Feb 24 '16 at 10:52