[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1087
  • Last Modified:

PHP Sort Order ASC and DESC

I have the following code:
$sort = (isset($_GET['sort'])) ? $_GET['sort'] : 'cn';

// Determine the sorting order:
switch ($sort) {
	case 'cn':
		$order_by = 'card_number ASC';

Open in new window

When implemented it works fine.  However, how do I add to that DESC? So, If I click on the link it orders everything in an ASC manner and when I click on it again it sorts in a DESC manner?
0
rgranlund
Asked:
rgranlund
  • 7
  • 3
  • 3
  • +3
1 Solution
 
GaryCommented:
Why not just the following and place directly into the query, defaulting to ASC, assuming when you click the link it is either sending DESC or nothing.  You need logic on the page to say whether the sort link has a sort variable added - i.e. only when the sort is ASC

$sort=isset($_GET['sort'])?$_GET['sort']:"ASC";

$sql = ".... card_number $sort";
0
 
Julian HansenCommented:
You need to keep a direction value either embedded in the link or as a session variable
$dir = empty($_GET['dir'])?'ASC':(($dir=='ASC')?'DESC':'');
Then in your link in your <th> or wherever
<a href="page.php?sort=cn&dir=<?php echo $dir;?>">CN</a>

Open in new window

A variation on the above is to concat the field and the direction together like so
<a href="page.php?sort=cn:asc">CN</a>
And then split them on the server side
list($field, $dir) = explode(':', $_GET['sort']);

Open in new window

or using session
$dir = empty($_SESSION['sortdir'])?'':$_SESSION['sortdir'];
$dir = ($dir == '')?'ASC':(($dir=='ASC')?'DESC':'');
$_SESSION['sortdir'] = $dir;

Open in new window

The above translates to blank dir => database order
ASC and DESC as implied
0
 
Dave BaldwinFixer of ProblemsCommented:
I believe he has left out a lot of code.  'cn' appears to be the default for 'ASC'.  Something else, probably thru AJAX, must be changing the sort order.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Julian HansenCommented:
As I read it cn is an aliase for the fieldname he wants to sort on hence the switch statement that creates the order by.
0
 
Dave BaldwinFixer of ProblemsCommented:
I agree but he says it switches between 'ASC' and 'DESC' when he clicks on the link.  That code isn't being shown.
0
 
Julian HansenCommented:
I understood him to mean he was asking how to change his code to be able to switch between the two - that is what my post is based on.

currently the code (I assume in response to a column click in a table) sorts the data by that column but it is in ASC order - as per the existing code.

I think the request is how to extend that to make it alternate between ASC and DESC
0
 
rgranlundAuthor Commented:
@julianH  That is exactly what I am trying todo.  Back and forth.  Fist click, orders ASC, second click orders DESC and so on.
0
 
Julian HansenCommented:
Ok, then try the suggestions I posted earlier - I use those all the time in my code - works well.

Personally I prefer the SESSION approach - I maintain state of what the interface is doing there rather than having to modify complicated URL's
0
 
GaryCommented:
Why use sessions for something that is only needed on one page and can be achieved with a tiny bit of code.?
The link is built initially as ASC with no sort order in the link, click the link and on the processing page you add in the link for sort by asc
First check on page if sort is set for the query, and just add $sort to it.

$sort=isset($_GET['sort'])?$_GET['sort']:"ASC";

In the link all you need is

if(isset($_GET['sort']){echo "&sort=asc";}
0
 
lwadwellCommented:
Having a look at this and stepping back ... I have to ask what is being sorted on the page? ... is it a table, a list or what?  I also have to ask ... why go the back end server and run some PHP to extract the data again with a different 'order by'?
This sounds like the sorting should be done client side with JavaScript/jQuery etc. without the need to use server side scripting at all - the PHP should just present the page with 'default' sorting - and the ability to alter the sort be handled 'in page'.
If it is a table you are sorting - there are numerous JavaScript/jQuery libraries out there to handle sorting within the page, e.g.
- tableSorter (http://tablesorter.com/docs/)
- sorttable (http://www.kryogenix.org/code/browser/sorttable/)
... and many more
there is even
- tinysort (http://tinysort.sjeiti.com/) for any node type e.g. <li>
0
 
Julian HansenCommented:
@lwadwell

This sounds like the sorting should be done client side with JavaScript/jQuery etc
You have a dataset with a 1000 records - your view shows 10 of these sorted on name.  You reverse the sort - so now the last 10 records are required.

Yes you can buffer all 1000 records - but if there are more?

Server side sorting is a very common practice - especially for generic solutions where the size of the dataset can be large.

The solution can be improved to return the data via AJAX - but the principle remains the same just the delivery changes - and that is beyond the scope of this question anyway.

@GaryC123 - I think you are over simplifying the problem. There could be a requirement where you have mutliple sort columns - the sort value is then set to the column name of the column you want to sort on - and its presence or absence is then not suitable for determining a direction.

Sessions are useful when you need to maintain state data on a view - for instance if you have the option for setting how many rows to view or if you want to sort on multiple columns etc.

This is not necessarily a solution for this question but just something to think about if the author is planning on requiring other state information retained between views.
0
 
Dave BaldwinFixer of ProblemsCommented:
I use a coded method but I use the code as an index into an array rather than using a switch statement.  Each column that is sortable has it's own codes for ASC and DESC.
0
 
lwadwellCommented:
@julianH ... sorry, poor choice of words ... I meant "This sounds like the sorting could be done client side with JavaScript/jQuery etc"
I was just offering another option - I was unaware that the number of items being sorted was so large and that there was paging involved ... I didn't see that when I read through the question and comments.
0
 
Julian HansenCommented:
@lwadwell nothing wrong with your post - I am filling in gaps - it was not expressly stated that the dataset is large or paging involved - I include that is additional info because we do not have a complete picture of what the specifics are and my experience on ee is if you assume something about a question you often get wacked later when additional information indicates the thread you were following is not feasible.
0
 
lwadwellCommented:
@julianH ... that is why I asked "... what is being sorted on the page? ... is it a table, a list or what?"
0
 
Julian HansenCommented:
Dunnah - all I have to go on is the original post - but trying to read between the lines and cover all bases.

What we have to go on is:

The fact that it is sorting something indicates a table.
The switch statement says possibly more than one column
The field in question is card_number which indicates possibly a client database - in fact possibly a shop - if you look at rgranlund's other questions.

So I put two and two together ...
0
 
Ray PaseurCommented:
I would be wary of using an external input in a query.  I think I would abstract the signal from the (potential) noise with something like this.

http://www.laprbass.com/RAY_temp_rgranlund.php
http://www.laprbass.com/RAY_temp_rgranlund.php?s=d
http://www.laprbass.com/RAY_temp_rgranlund.php?s=x
http://www.laprbass.com/RAY_temp_rgranlund.php?s=a

<?php // RAY_temp_rgranlund.php
error_reporting(E_ALL);

// SET THE DEFAULT ORDER
$order = 'ASC';

// CHECK THE CLIENT INPUT
$signal = !empty($_GET['s']) ? $_GET['s'] : 'A';
$signal = trim($signal);
$signal = substr($signal,0,1);
$signal = strtoupper($signal);
switch($signal)
{
    case 'A': $order = 'ASC';  break;
    case 'D': $order = 'DESC'; break;
    default:  $order = 'ASC';
}

echo "YOU CHOSE <b>$order</b> FOR YOUR ORDER CLAUSE";

Open in new window

0
 
Ray PaseurCommented:
To anyone reading this question in the future, the security mantra that professionals observe is "accept only known good values."  Do not use external values in a query; use an abstraction instead.  

If your script is not modifying the data model, put the arguments into the URL parameters (GET-method request).  The reason for doing this is that your site will have better SEO if the search engines can find all the pages.  If the query data set is kept in the session, the pages are, by definition, hidden from the search engines.  And your clients can't just "post a link" or bookmark a page.

best regards to all, ~Ray
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 7
  • 3
  • 3
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now