0

The below loops through a table in my MySql database and shows all the car records in a table cell that match. I know i can use the ORDER BY command in the MySql query to order by a particular column but how can i place a particular record on top and then list all the remaining matches?

For example i have a simple form before this where the user selects their favourite car ($_POST['user_car']) and the required spec ($_POST['user_spec']) with the $_POST method. So my query shows all records that match the spec selected, but i want the selected car to be at the very top of the list with the remaining to follow.

        $query_params = array( 
            ':spec' => $_POST['user_spec']
        );

        $query = " 
            SELECT 
                *
            FROM 
                table
            WHERE
                spec=:spec
        "; 

        try { 
            $stmt = DB::get()->prepare($query); 
            $stmt->execute($query_params); 
            $rows = $stmt->fetchAll(); 
        }  
        catch(PDOException $ex) {}

        foreach($rows as $row):

            $cell .= '<td>
                          <input type="checkbox" '.$check.' name="spec[]" value="'.$row['id'].'"/><span> '.$row['spec'].'
                      </td>';
        endforeach;
1
  • 1
    Add the selected value to the ORDER BY, ie SELECT.. ORDER BY car='ford' DESC, car_name. This test will produce 1 for the match and 0 for no-match
    – Waygood
    Mar 18, 2013 at 14:20

1 Answer 1

4

The ORDER BY does not limit you to just column(S) you can put evaluated statements in there too.

        SELECT 
            *
        FROM 
            table
        WHERE
            spec=:spec
        ORDER BY car_name=:user_car DESC, car_name ASC

if users favourite car is 'mini', then the record with car_name of 'mini' will evaluate to 1, and the rest to 0, so it will appear first. The rest of the cars will then be ordered by their name.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.