Counter and sessions problem

I have a dynamic php page which generates product information from a mySQL database. I would like to have a counter which records how many times the page is viewed but as such uses sessions to stop unacurate counter results.

I have set up a table with 2 columns. The product id and count as fields and am using this php code to write to the database;


<?php
session_start();
if(isset($_SESSION['views']))
    $_SESSION['views'] = $_SESSION['views']+ 1;
else
    $_SESSION['views'] = 1;
?>

this sets up the session and then this code writes to the database based on the value of the session;

<?php
if ($_SESSION['views'] == 1) {
        mysql_query("UPDATE product_count SET count=count+1 where id = $pid");
}
>?

this works but when I try and view a different product it won’t update the count. I believe that this is because the session is set. How can I set it that if the same page is refreshed, the counter won’t add but on the other hand if another product is viewed then the session is reset and the counter is updated?

Thanks.


<?php
session_start();

if(false === isset($_SESSION['viewed_products'])){
    $_SESSION['viewed_products'] = array();
}

if(false === in_array($product_id, $_SESSION['viewed_products'])){
    array_push($_SESSION['viewed_products'], $product_id);
    mysql_query('UPDATE product SET view_count = view_count + 1 WHERE id = ' . (int)$product_id . ' LIMIT 1');
}

?>

:wink:

Would you be able to explain a little of how this works? I like to understand a solution rather than just copy and paste. Thanks for the quick response btw.

Cheers.

Sure, I must admit, adding a snippet or two along with these random posts of mine would indeed go a long way!

Comments added. :smiley:


<?php
#start a session
session_start();

#if the user has not seen any products yet, create a store (array) ready for them.
if(false === isset($_SESSION['viewed_products'])){
    $_SESSION['viewed_products'] = array();
}

#if the product id is not in the store, the user has not seen it before, so...
if(false === in_array($product_id, $_SESSION['viewed_products'])){
    #add the product id to the store...
    array_push($_SESSION['viewed_products'], $product_id);
    #update the view count in the database
    mysql_query('UPDATE product SET view_count = view_count + 1 WHERE id = ' . (int)$product_id . ' LIMIT 1');
}
?>

This approach also allows you to display ‘other products you looked at’ functionality, whereas your previous solution did not.

brilliant, thanks so much. People like you and sites like these make learning so much fun.