Yogesh Chauhan's Blog

Simple Page Hit Counter in PHP

in PHP on February 26, 2021

To create a simple page hot counter what we need is a mysql table to store the hits and then a PHP script to send the hits to the mysql table and retrieve the hits back.

We can use CREATE TABLE statement to create the table in the mysql database.

Let’s create the table in mysql using this statement:


CREATE TABLE `page_hit_counter_table`
  (`page_hit_counter` 
  INT(255) 
  NOT NULL);

We have the page_hit_counter column set as NOT NULL. Let’s set the value for the column to 0 so that we can increment it every time an user visits the page.


INSERT INTO page_hit_counter VALUES (0);

All set.

The page hit counter column is ready to go and increment.

Let’s add the script to increase the hit counter.

Let’s add a code to make a connection to the database.


mysql_connect("your mysql host address", 
  "username", "password") 
  or die(mysql_error()); 
  mysql_select_db("Your Database Name") 
  or die(mysql_error());

Let’s add code to increase the page hit counter. We’ll use UPDATE statement like any sql (postgresql, mysql etc.).


mysql_query("UPDATE page_hit_counter_table 
  SET page_hit_counter 
  = page_hit_counter + 1");

Let’s retrieve the counter and print it on the blog post page (or any kind of page that you have the counter for).


$page_hit_counter = 
  mysql_fetch_row(mysql_query
  ("SELECT page_hit_counter 
  FROM page_hit_counter_table"));
  echo $page_hit_counter[0]; 

DONE. It should display the page hit counter on your page now.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to add and remove capabilities from a role in WordPress?WordPressUPDATE and DELETE Statements in PostgresPostgresHow to Clone Objects in PHP?MiscellaneousSolution to pod install fails with json error on Mac OS X 10.15 (or Mac OS Catalina)Miscellaneous5 Key Principles Of Good Website UsabilityUI/UXHow to hide and show menu on scroll using JavaScript and CSS?CSS