I have this code :
$id = $_GET['id'];
mysql_query("UPDATE threads SET views = views + 1 WHERE id = '$id'");
but when I click refresh over and over the counter increases with e开发者_开发知识库ach refresh.
How can I protect this counter from this with sessions or any other way?
You could set a session variable with (hasBeenCounted) and if that is set, you do not increment.
if(!isset($_SESSION['hasBeenCounted'])
{
$id = $_GET['id'];
mysql_query("UPDATE threads SET views = views + 1 WHERE id = '$id'");
$_SESSION['hasBeenCounted'] = "counted";
}
EDIT:
session_start():
will need to be at the very top of any page that you intend to use sessions on.
One way to do this is to use sessions. However, in the end, that's not really scalable. As a user moves through your site, you could potentially have a massive session file. Additionally, every time a user creates a new session, you will record that view anyway.
If you only want to record a single view for a single user, you need to store that that user viewed the thread. Depending on whether your site only allows logged in users to view threads, or if your site is open to the public, you'll have to store something unique about each user in a separate table, structured something like this (your mileage will vary on field types):
CREATE TABLE `thread_views` ( `id` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , `thread_id` INT( 10 ) UNSIGNED NOT NULL , `user_id` INT( 10 ) UNSIGNED NOT NULL , `ts` TIMESTAMP NOT NULL )
Every time a user views the thread, you'll need to check this table. If there's no record in thread_views
, insert one, and the increment the views
column in your threads
table. If there is a row in thread_views
, then you know the user has already viewed the thread.
I think sessions with cookies are your best shot. You would probably want to set the cookie after the first visit, and then if the cookie is already set you don't update your view counter.
The syntax will be similar to this:
$expire=time()+2592000; //This is set to expire in 1 month (in seconds)
setcookie("visitor", "Already Visited", $expire);
This is how I would implement it:
if !(isset($_COOKIE["visitor"]))
{
$expire=time()+2592000; //This is set to expire in 1 month (in seconds)
setcookie("visitor", "Already Visited", $expire);
$id = $_GET['id'];
mysql_query("UPDATE threads SET views = views + 1 WHERE id = '$id'");
}
$id = $_GET['id'];
if(!isset($_SESSION['hasBeenCounted']) || $_SESSION['hasBeenCounted'] != $id)
{
mysql_query("UPDATE threads SET views = views + 1 WHERE id = '$id'");
$_SESSION['hasBeenCounted'] = $id;
}
I've modified the code and it works now.
精彩评论