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";