I want to use sessions to track unique page views. Not a very robust method, I know, but sufficient for what I want to do.
On the first page load the session variable is set and a field in the database increments. On subsequent page views it does not increment, because the increment is conditional on the session variable not being set.
This is my code:
$pagenumber = 1;
//other stuff here...
session_start();
if (!isset($_SESSION[$pagenumber])) {
$storeview = mysqli_query($dbconnect, "UPDATE tblcount SET views=views+1 WHERE id='$pagenumber'");
$_SESSION[$pagenumber] = $pagenumber;
}
echo $_SESSION[$pagenumber];
$Recordset1 = mysqli_query($dbconnect, "SELECT views FROM tblcount WHERE id = '$pagenumber'");
$row_Recordset1 = mysqli_fetch_assoc($Recordset1);
echo "Viewed ".$row_Recordset1['views']." times";
The first echo is only there for testing. It echoes the value just fine on page refresh and the increment works the first time, but the view count continues to increment on every page refresh, which it shouldn't. I can't see why.
I found a similar question:
PHP: Unique visits/hits to specific items using cookies/ip but I ran into a similar issue with the solution offered there.
Help appreciated!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…