Sort variable lose value when paginated

Hi stackoverflow elements.

I have a little problem, here I have an ad site that I want to sort by latest date, highest, lowest price. This works well for sorting ads, but when you click on page links, ads are sorted by default as recent ads.

<select name="Sort_Ads" id="Sort_Ads" onchange="document.getElementById('formName').submit()">
    <option>Most Recent Ads</option>
    <option>Price: High to Low</option>
    <option>Price: Low to High</option>
</select>

if(isset($_POST['Sort_Ads']))
    {   
        $sortit = $_POST['Sort_Ads'];
        if($sortit == "Most Recent Ads") $sort = "ad_id DESC";
        else if($sortit == "Price: Low to High") $sort = "ad_price ASC";
        else if($sortit == "Price: High to Low") $sort = "ad_price DESC";
    }

      

And this request of mine "SELECT * FROM ads ORDER BY $sort $limit"

works fine.

The only problem is that the sorting is restored on the pagination, so we only see ads sorted on the first page.

And one more thing: after refreshing the page, the dropdown is set to the first option, but the items are sorted in order. Please, how can I set the dropdown value as it was before the page reload? Because if the user clicks on "Sort maximum to low" after reloading the page, the latest ads option will be selected, and if they want to sort it by latest ads, this is not possible because they have already been selected, but the items are sorted as the highest price or what has always been chosen previously.

I think it can be done with JavaScript, so please, I don’t have enough JavaScript skills, I would be very happy if someone does it. Thank you in advance!

+3


source to share


1 answer


You will need to remember the sort order in the php session. Example:

$_SESSION['sortorder'] = $sortit;

      

Now you remember the sort order in the session variable, so the next step would be:

if(isset($_POST['Sort_Ads']))
{   
        $sortit = $_POST['Sort_Ads'];
        $_SESSION['sortorder'] = $sortit;
        if($sortit == "Most Recent Ads") $sort = "ad_id DESC";
        else if($sortit == "Price: Low to High") $sort = "ad_price ASC";
        else if($sortit == "Price: High to Low") $sort = "ad_price DESC";
}
elseif(isset($_SESSION['sortorder']))
{   
        $sortit = $_SESSION['sortorder'];
        if($sortit == "Most Recent Ads") $sort = "ad_id DESC";
        else if($sortit == "Price: Low to High") $sort = "ad_price ASC";
        else if($sortit == "Price: High to Low") $sort = "ad_price DESC";
}

      

Update:



You can delete a specific session variable:
unset($_SESSION['variableName']);

      

OR remove all session variables:

session_destroy();

      

It is now up to you in what state you want to disable session variables.

+1


source







All Articles