1

Using the code below, i am able to return all products that match the search word. However they order in a way that a product with a name different from the search phrase appears first and one with a matching name later because the description had a match.

How can i sort and return the products whose name matches the search phrase first?

    $sqli = "
SELECT * 
  FROM product 
 WHERE";

Foreach($strarray as $key=>$value){
If($key > 0){
$sqli = $sqli . "OR";
}
$sqli = $sqli . " (Name LIKE '%" . $value . "%' or Description LIKE '%" . $value . "%')";
}
Strawberry
  • 33,750
  • 13
  • 40
  • 57

1 Answers1

2

Add an ORDER BY clause:

$ssql .= " ORDER BY Name LIKE '%" . $value . "%' DESC"

A boolean expression is 1 for TRUE and 0 for FALSE, so sorting by a condition orders by whether the row matches the condition.

BTW, you should learn to use prepared statements to prevent SQL injection. See How can I prevent SQL injection in PHP?

Barmar
  • 741,623
  • 53
  • 500
  • 612