Sorting SQL table using PHP help!

Hello All! I’m stuck trying to figure out how to be able to use one link and sort my sql query either ASC or DESC based upon what is sorted currently. (e.g. clicking the link sorts the opposite of the current sorted column) I am extremly new to this and below is the closest i’ve came… It doesn’t work the way i was hoping… I just want to use column headings as links to and once click they sort by default asc then desc if clicked again.

here’s how i am first reading the $direction variable and see if its set
$direction = $_GET[‘direction’];

if (!isset($direction))
{$direction = ‘DESC’;}
else if ($direction = ‘DESC’)
{$direction = ‘ASC’;}

Then i have my link for the column like below… the theory here is it would pass the current direction (default is desc) and then switch it to asc (eventually vica versa too)…


Any ideas or easier way to do this?

Well your code should be formatted differently.

[php]$direction = $_GET[‘direction’];[/php]

This would return an undefined index notice if ‘direction’ is not set.

$direction = ‘DESC’; // first set default value

// then look for modified value
if (isset($_GET[‘direction’])) {
// by not assigning the actual value of $_GET[‘direction’] we can require a value of ‘DESC’ or ‘ASC’
$direction = ($_GET[‘direction’] == ‘DESC’ ? ‘DESC’ : ‘ASC’);

// right now the value of $direction would be used for your query

// now alternate the value of $direction only when building your link
echo ‘ArtifactID’;

Thanks Matt! i was getting the undefined notice but i killed that by using

[php]error_reporting(E_ALL ^ E_NOTICE);[/php]

obviously not the proper way, but thanks for helping me fix my sorting issue. Makes sense now that i take a look at it… Very much appreciated.

Sponsor our Newsletter | Privacy Policy | Terms of Service