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 a database and MySQL table to store the page view count. On each view of the page we store page view counter increased by 1 and if it is the first time then simply store page view counter value 1.
In this approach, we store the page view counter with the respective URL so that we get the page view count of each page separately.
To create a page view counter we have to follow some steps which are as follows:
Database : test
Table : pageview
index.php
Just copy the MySQL query and put this in the 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; } ?>
[sociallocker]Download[/sociallocker]
Using the above snippet we successfully create page view count using PHP and MySQL.
If we want to create a unique page visitor then we can use $_SERVER[‘REMOTE_ADDR’]; and store it in the database and then check for IP address on each page view.
The simple way to create a page view counter with PHP. That’s it.