Question

I have a PHP script that outputs a list of reviews in a table and orders them by the date they were submitted - (similar to have Trip Advisor ratings work).

Below I have included how the table heading are set out:

NAME || DATE || REVIEW || RATING

Below I have listed the code:

//run a query to find all the fields in the review table that belong to the specific hall, using the id in the url ($current_id)
if ($r = $db->prepare("SELECT * FROM reviews WHERE hall_id = :current_id ORDER BY overall DESC")) {
    //bind the parameters used in the above query using the 'current_id' variable
    $r->bindParam(':current_id', $current_id);
    //Execute the prepared query
    $r->execute(); 

        //search review table for all fields and save them in $review
        $reviewtemp = $r->fetchAll();
       foreach( $reviewtemp as $review) { ...

ORDER BY date DESC orders the reviews by the date. However, when the user clicks on the 'RATING' header in the table, I need the reviews to be ordered by the highest rating (which is a number). So ORDER BY date DESC would change into ORDER BY rating DESC.

I'm unsure whether I have to create an entire new page (and simply change 1 word of my php script) to do this, or if there is a more simple and efficient method?

Was it helpful?

Solution

I wouldn't make whole new page, I would say have a variable that you can change that you would use in the order by in your query.

$orderby = 'rating';

And then your query would have "ORDER BY $orderby DESC"

EDIT

If you make the date header a link to "yourscript.php?orderby=date", you could have something like this on "yourscript.php"

switch($_GET['orderby']){
    case 'date':
        $orderby = 'date';
        break;
    default :
        $orderby = 'rating';
        break;
}

OTHER TIPS

Up to you, but when I do this I use tablesorter. Take a look, it lets you display the results and clicking on the headers reorders on the fly, no new queries. It also lets you sort by more than one column by holding shift.

I whipped up a fiddle for you to check out.

http://tablesorter.com
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top