tags:

views:

26

answers:

2

I was just kindly helped to get the rows in a table to display using ORDER BY. Then I realized I also want to click the same link to decrement if desired. I tried to set up a conditional, but it's not working as I expected:

<?php
$orderBy = array('type', 'description', 'recorded_date', 'added_date');

$order = 'type';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
    $order = $_GET['orderBy'];
}


$sql="SELECT * FROM $tbl_name ORDER BY " .$order;

?>
<table>
    <tr>
        <th>
        <?php 
            if($order == 'type'){ 
        ?>
                <a href="?orderBy=type_dec">Type:</a>
        <?php 
            } else{
        ?>
                <a href="?orderBy=type">Type:</a>
        <?php 
            }
        ?>
            <a href="?orderBy=type">Type:</a>
        </th>
        <th>
            Description:
        </th>
        <th>
            <a href="?orderBy=recorded_date">Recorded Date:</a>
        </th>
        <th>
            <a href="?orderBy=added_date">Added Date:</a>
        </th>
    </tr>

I know I don't have the full code, but I was surprised to see that even as it is, the "type" link is showing up twice in the above example. I thought one or the other would show up depending on the value of $order.

Also, i have a feeling that the way I'm trying to achieve this with the decrementing could be done in a much better way. Please feel free to share that way!

+1  A: 

The easiest way to handle this is using sessions:

$orderBy = $_SESSION['orderBy'];
$orderBy = (isset($_GET['orderBy'])) ? $_GET['orderBy'] : $orderBy;

$order = $_SESSION['order'];
$order = (isset($_GET['order'])) ? $_GET['order'] : $order;

// construct the query as follows:
// make sure $orderBy and $order are valid 
$sql = "SELECT fields FROM table ORDER BY {$orderBy} {$order}";

// the code to display could look something like this:
$displayOrder = ($order == 'ASC') ? 'DESC' : 'ASC';

echo '<a href="?orderBy=type&order=' . $displayOrder;

Be careful when doing pagination though, it is trickier than it seems.

NullUserException
I haven't tried the session yet, but I did try this, an I'm curious why it doesn't work:$sql="SELECT * FROM $tbl_name ORDER BY " .$order;echo "<a href='?orderBy=type DESC'>Type:</a>"; Can i not just append DESC like that to run the SQL?
Joel
edit: I added those to the array, and it worked great.
Joel
@Joel you sure can, but it also makes it harder for you to extract the parameter later. BTW if you are going to use sessions, remember to put [`session_start()`](http://php.net/manual/en/function.session-start.php) on every script that uses sessions.
NullUserException
+2  A: 
Scott
This approach works but becomes harder to manage once you start using pagination.
NullUserException