简体   繁体   中英

mysql like query, how can you sort targeting two columns in a table but sorting by the results matched by one column

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 . "%')";
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM