user1227914
user1227914

Reputation: 3514

what is the best way to sort "recently viewed pages" by date with php and cookies?

I am using the following code to store recently viewed pages with cookies in the user's browser and then retrieve the pages at a later time to show them.

The problem with my current way I noticed is that it will only sort the pages by ID, starting from the highest ID down but because I am showing only a maximum of 12 pages, it's not really sorting them by visit date (ie. recent ones first), but by ID.

The cookie is set like this:

setcookie('recently_visited['.$_REQUEST['page_id'].']', 
$_REQUEST['page_id'], time() + 86400);

And then retrieved via:

        $cookie_array = array_reverse($_COOKIE['recently_visited'], true);
        $cookie_array = array_values($cookie_array);

        for($i = 0; $i <= 11; $i++){

            if(isset($cookie_array[$i])){
                $new_array[] = $cookie_array[$i];
            }

        }

        $recently_cookie = implode(",",$new_array);

        // making sure the cookie content contains only numbers

        if (ctype_digit(str_replace(",", "", $recently_cookie))) {
          $clean_string = '1';
        } else {
          $clean_string = '0';
        }

        if($recently_cookie) {

        if ($clean_string == '1'){

        // get the pages for display

        $sql_select_recent_items = $db->query("SELECT page_id, name        
        FROM db_pages WHERE page_id IN (".$recently_cookie.") LIMIT 0,12");

    }

What would be the easiest way to sort them, but by visit date? The most recent ones first.

I know it's not possible to get the expiration date of the cookies so that is out of the question.

Upvotes: 1

Views: 266

Answers (1)

Muhammad Abdul-Rahim
Muhammad Abdul-Rahim

Reputation: 2010

Let SQL take care of it for you. If you're sorting by id then:

SELECT page_id, name
FROM db_pages
WHERE page_id IN (".$recently_cookie.")
ORDER BY page_id ASC
LIMIT 0,12

If you have an actual column for date you can alter the page_id accordingly. ASC is for ascending order, DESC is for descending order.

SIDE NOTE

Your current code opens up the possibility of SQL Injection. Handling this scenario is beyond the scope of this question, but it is well worth looking into.

Upvotes: 1

Related Questions