JAVAGeek
JAVAGeek

Reputation: 2794

managing View Count of webpage

I am creating a jsp page where a single news item is shown, just like the single question on this StackOverflow page. I need to store the view count in a database.

I can simply increment the view count in the database this way:

`UPDATE table SET views=views+1 WHERE newsId=4458;`

But what if a single user hits that page again and again and again, say 50 times... In this case, my view count will not represent unique visitors to the site. How can I avoid this?

I want something like StackOverflow's view count system.

Upvotes: 2

Views: 1915

Answers (3)

Cato Minor
Cato Minor

Reputation: 3099

You may want to reference spencer7593's answer here, where he basically suggests having both (1) a view count column, for quickly generating your webpages and (2) a separate views table, which records the user id and timestamp pertaining to each view, for the sake of analytics.

I would suggest that this views table could also be used to query if a viewing has occurred for a particular user with a particular piece of content in the last day (or week) when determining if the view count column should be incremented. By checking if a view of a certain item has occurred only in the last day (or week), the DB queries should be substantially less expensive while still protecting the integrity of your view count.

Upvotes: 1

Anthony
Anthony

Reputation: 427

well one solution could be you make a new table (lets say its called views) with the following columns 'viewid' 'newsid' 'ipaddress' (obviously newsid is the foreign key) every time someone visits ur website u check if his ip is already in that table for that news item.

Select count(*) AS count FROM views WHERE newsid=1234 AND ipaddress=123.456.125

if count equals 0 you insert like this

INSERT INTO views('newsid', 'ipaddress') VALUES(1234, 123.146.125)

Now when you want to fetch the viewcount:

Select count(*) AS count FROM views WHERE newsid=1234

you can enhance this by adding another column called 'count' and 'lastviewed' (type datetime) to the table views. Lets say you allow every ip to be counted another time if the day doesnt match. This way you will get a pretty accurate viewcount :)

to fetch the new viewcount you can simply use SUM

Select SUM(count) AS count WHERE newsid=1234

Good luck :)

Upvotes: 1

Himanshu.MarJAVA
Himanshu.MarJAVA

Reputation: 525

i say use a counter in Javscript . Increment the variable on body onclick. eg:

<script language=”javascript”>
function pageCounter()
{
var counter = 0;
counter = counter++;

}
</script>

<body onclick = “pageCounter()”>

and you can update the value with onclose ..

Upvotes: -1

Related Questions