Reputation: 2480
i have a example table to store posts like
id|title|content|
now i want count view post
like
What is the way to do that thanks
Upvotes: 0
Views: 3778
Reputation: 27894
You should have a field in your table to store the views count, so you can update the count of viewers with something similar to:
UPDATE `table` SET `views` = `views` + 1 WHERE `id`= $post_id
You may want to avoid spamming by refreshing the page or make sure its a unique viewer. There are several ways you can do that.
If you want to be serious about it you will have to use a table to store IP addresses and relate them to viewed posts in order to not count again, like Gautam3164 suggested.
But creating new records every time a client view a post can be too computationally expensive and, unless its strictily necessary for the case, it should be avoided.
You can instead abuse the $_SESSION
to store the IDs of the recently viewed posts, in order to not increment the counter if the same client view them again.
For instance:
if (!isset($_SESSION['recent_posts'][$post_id])) {
mysql_query("UPDATE `table` SET `views` = `views` + 1 WHERE `id`= $post_id");
$_SESSION['recent_posts'][$post_id] = 1;
}
It should solve the spam problem in a very simple and cheap way.
Upvotes: 1
Reputation: 28763
You may need to store the IP
address of the viewer using $_SERVER['REMOTE_ADDR']
of the page was opened and store it in DB
with that page id
and each time you need to check for the maintaining the unique IP
addresses.
Means you need to enable the increment of the page view count
for the single IP address.
1) First Check for the DB that whether the page view with the current IP
address($_SERVER['REMOTE_ADDR']
).
2) If is already exists then do nothing.
3) If there is no ,then add a row into DB with the current page id and ip address.
4) Then extract/count the number of views as counting the rows from DB with that page id.
Every time you need to repeat these things.You can also use LOGIN
system for mainting the page count.
Upvotes: 0
Reputation: 936
The best way doing that would be using cookies you can refer to this for it.
Upvotes: 0
Reputation: 1764
You can make a new table called Counter as example the table contains:
post_id|views
when ever the user visit the page you increment this counter
or you can add a field called views in the same posts table
if you want to count unique views you may store IP ADDRESS as will and check if the ip exists you don't increment that view.
You can get the ip address in php like this:
$_SERVER['REMOTE_ADDR'];
Upvotes: 0
Reputation: 2764
For that you have to add one column in your table.
For example lets say,
You have column name Views
You have to put update
query on the top of the page like this
UPDATE table SET Views= Views+1 WHERE ID= 'current page id'
Upvotes: 0