Simple Page View Counter Using PHP and MySQL

In this post we will learn how to display page view counter using PHP and MySQL. Simple steps to create page view counter. In this approach we create database and mysql table to store the page view count. On each view of page we store page view counter increased by 1 and if it is first time then simply store page view counter value 1. In this approach we store page view counter with respective URL so that we get page view count of each page separately. To create page view counter we have to follow some steps which are as follows:

Simple Page View Counter Using PHP and MySQL
Simple Page View Counter Using PHP and MySQL

Database : test
Table : pageview
index.php
Just copy the mysql query and put this in sql query box and execute it. Using this query page view table will create to store the page view count.
MySQL

CREATE TABLE IF NOT EXISTS `pageview` (
  `id` int(25) NOT NULL,
  `pageurl` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `userip` bigint(20) NOT NULL,
  `totalview` bigint(20) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=33 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

PHP

<?php 
//DB Config
mysql_connect('localhost','user','password');
mysql_select_db('db name');

//Page URL 
$page_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
 
//check for count
$query = mysql_query("SELECT * FROM `pageview` WHERE `pageurl`='".$page_url."' "); 
$rows = mysql_fetch_array($query); 
$counter = $rows['totalview']; 
if(empty($counter)) 
{
 $counter = 1;
 mysql_query("INSERT INTO `pageview` SET `pageurl`='".$page_url."',`totalview`='".$counter."'"); 
} 
//increase counters by 1 on page load
 $counter = $counter+1;
 mysql_query("UPDATE `pageview` SET `totalview`='".$counter."' WHERE `pageurl`='".$page_url."'");
 if($counter)
 {
 echo "Visitor:".$counter;
 } ?>

Demo


Using the above snippet we successfully create page view count using PHP and MySQL. If we want to create unique page visitor then we can use $_SERVER[‘REMOTE_ADDR’]; and store it in database and then check for IP address on each page view. Simple way to create page view counter with PHP. That’s it.

Leave a Reply

Your email address will not be published. Required fields are marked *