Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

sql - PHP session for tracking unique page views

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Problems:

  1. You are updating in tblCount EACH time, because your session is closed each time your script finishes. SO: Put the session_start()call as the FIRST LINE in code.
  2. It's not permitted to set an integer as $_SESSION variable. So if you set $_SESSION[$pagenumber] = 'something', then you gain the following notice:

( ! ) Notice: Unknown: Skipping numeric key 1 in Unknown on line 0

Quite... not understandable. For details see this answer.

Solution:

Add your $pagenumber as index in an array (here pagenumbers) and that array inside the $_SESSION variable. No notice anymore.

session_start();

$pagenumber = 1;

if (!isset($_SESSION['pagenumbers'])) {
    $_SESSION['pagenumbers'] = array();
}

if (!isset($_SESSION['pagenumbers'][$pagenumber])) {
    updateViews($pagenumber);
    $_SESSION['pagenumbers'][$pagenumber] = $pagenumber;
}

echo 'Page number: ' . $_SESSION['pagenumbers'][$pagenumber] . '<br/>';
$views = getViews($pagenumber);
echo '<pre>Viewed ' . print_r($views, true) . ' times</pre>';

Note: I used my functions to test. They just replace your db-processing code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...