Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to count page views in PHP/MySQL?

Tags:

php

mysql

And by best I mean most efficient, right now placing this on my post.php file is the only thing I can think of:

$query = mysql_query(" UPDATE posts SET views + 1 WHERE id = '$id' "); 

is there a better way, a method that would consume less server resources. I ask because if this was a small app I would have no problem with the above, but I am trying to build something that will be used by a lot of people and I want to be as query conscious as possible.

like image 411
Joe Avatar asked Jan 21 '11 18:01

Joe


People also ask

How do you count page views?

The total number of page views divided by the total number of visits during the same timeframe. Sophisticated users may also want to calculate average page views per visit for different visitor segments. “Page Views” is a fairly generous measurement. If you land on a page, that's a pageview.

How will you write hit counter using session explain in PHP?

session_start() :It is a first step which is used to start the session. It is a standard call. The session_start() should be used whenever the session variable is used. $_SESSION['views'] :This is the session variable which is used to store views count for a user's session.


1 Answers

If you're interested in conserving resources and still using SQL for reporting, and precise # doesn't matter, you could try sampling like this (modify sample rate to suit your scale):

$sample_rate = 100; if(mt_rand(1,$sample_rate) == 1) {     $query = mysql_query(" UPDATE posts SET views = views + {$sample_rate} WHERE id = '{$id}' ");     // execute query, etc } 
like image 151
Kyle Wild Avatar answered Sep 23 '22 21:09

Kyle Wild