Callum Whyte
Callum Whyte

Reputation: 2429

Ordering results in PHP search suggestions

I have a PHP search suggestion script which gets results from a MySQL database and then pushes them to the page with jQuery. In my database I have a field for the rank of each result but I want to make this work in my PHP code. I want the results with the highest number in their rank field to be displayed higher.

My PHP code is:

<p id="searchresults"><?php

$db=new mysqli('localhost','username','password','database');

if(isset($_POST['queryString'])){
$queryString=$db->real_escape_string($_POST['queryString']);
            if(strlen($queryString)>0){
                $query = $db->query("SELECT * FROM search WHERE name LIKE '%" . $queryString . "%' LIMIT 10");
                if($query){
                    while ($result = $query ->fetch_object()){
                        echo '<a href="/search/'.$result->name.'/1/">';                     
                        $name=$result->name;            
                        echo ''.$name.'';
                    }
                }
            }
        }
?></p>

I hope you can understand what I am trying to describe.

Thanks in advance, Callum

Upvotes: 0

Views: 256

Answers (1)

Beno&#238;t
Beno&#238;t

Reputation: 7427

You can just added 'ORDER BY rank DESC' in you sql query

$query = $db->query("SELECT * FROM search WHERE name LIKE '%" . $queryString . "%' ORDER BY rank DESC LIMIT 10");

You can go on mysql help for SELECT

Upvotes: 5

Related Questions