0

I'm trying to make a sorting, using links and GET method with them. I'll provide the code first and then explain what I'm trying to achieve. There could be a better way by using AJAX, and making it dynamic (I think?), but I want to start off with this first.

Code:

if(isset($_GET['order'])){$order = $_GET['order'];}else{$order = 0;}
if(isset($_GET['field'])){$order_field = $_GET['field'];}

switch($order)
{
    case 0: 
        $order_next = "DESC";
        break;
    case "DESC":
        $order_next = "ASC";
        break;
    case "ASC":
        $order_next = 0;
        break;
}

And later, in the HTML page I have this snippet:

<? 
if($order == 0)
{
    printf("<a href='admin.php?field=lastname&order=%s'>Last</a>
    ", $order_next);
}
else
{
    printf("<a href='admin.php?field=%s&order=%s'>Last</a><a class='sort_desc' href='admin.php?field=%s&order=%s'></a>
    ", $order_field, $order_next, $order_field, $order_next);
}
?>

Okay. I have a link Last, which should have 3 positions, default, DESC order, ASC order.
When I click on it once, it should send via GET method, that the field I clicked was "Lastname" field, and I need the next position (from default (without sorting) to next one (DESC in this case)). I can't quite catch the error on the code, or I don't understand something, doesn't the page reload properly or something? When I click the link, the $order and $order_field is read from the GET method, but nothing else happens. The switch doesn't work for some reason, and $order_next doesn't change into the new value, and there is only 1 link, instead of 2:
Default: Link "Last" DESC: Link "Last" + link with the triangle picture pointing down.

P.S: Sorry if I might not explain this too well, but I tried. Thank you for your time!

3 Answers 3

2

Change case 0: to case "0": and all will be good with the world :-)

This is because switch uses Loose Comparison

To understand why, just run this code and see the result:

var_dump("DESC" == 0);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this already made part of it work! Thanks you so much! P.S: Got the second part working too!
@Arno - I would rather that you do a if($order == "0")
0

Change the test comparison from:

if($order == 0)

to

if($order === 0)

1 Comment

And this answered the second question. Thank you so much!
0

Your Switch statement is getting caught each time on case 0. If you change your 0 in the code to "0" as follows:

$order = "0";
case "0":
if($order == "0")

it will work as planned :)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.