View Full Version : Count article view
11-01-2007, 11:04 AM
I'm about to make a php CMS system where I can add articles through a web interface. The articles are stored in a MySQL database. I plan to implement a feature that counts the views of the articles. I guess this can be done so that the views count is stored in a field in the database table.
Can anyone suggest a method to count the number of views for each specific article? Such a field in the MySQL table would be handy, because it can be used to filter show lists of the most popular articles and so on.
11-01-2007, 12:33 PM
what you would do is pull out a row called views when you pull out the content then simply update the row to $views++ everytime its viewed its storing how many times it's been viewed but when you echo "Article seen $views"; make sure you have already ++'d it
11-01-2007, 03:18 PM
Thank you. I think something like you describe is the way to go. I found this tutorial which explains exactly what I need: http://www.phpfreaks.com/tutorials/6/0.php
11-01-2007, 03:57 PM
Actually, that way would be silly. Why download the content and then send it back? If you can avoid roundtrips with SQL, then do.
UPDATE articles SET views = views + 1 WHERE id = ?
This would be on the page that displays the article.
11-03-2007, 01:25 PM
I use this piece of code to store the views in my database. It is placed on top of each document, before the html start tag:
if ( isset($_GET['id']) )
$condition = "WHERE articleid = '" . $_GET['id'] . "'";
$connection = ConnectTo("MyDatabase");
mysql_query("UPDATE articles SET views=(views + 1) WHERE articleid = '" . $_GET['id'] . "'");
This piece of code works perfect on the first page the user clicks on, but if the user clicks on another article this is not counted. Is there some way to get around this problem, so that each article is counted?
11-05-2007, 04:45 PM
No one that know of a way to get around this problem? :confused:
11-05-2007, 04:51 PM
It's only counting the first page because the session variable persists across all pages viewed while the session is active. So make an array of articles viewed and just check to see if the article id is in it.
if(!is_array($_SESSION['viewed_articles']) || !in_array($_GET['id'], $_SESSION['viewed_articles']))
// increment view counter
$_SESSION['viewed_articles'] = $_GET['id'];
Powered by vBulletin® Version 4.2.2 Copyright © 2015 vBulletin Solutions, Inc. All rights reserved.