Visitor Counter Script Using PHP

If you have noticed that many websites display visitor's numbers on site. In this tutorial, I am going to explain to you how to create a simple visitor counter script using core PHP. First, create a table called visitor_counter by executing the below SQL statement.

CREATE TABLE `visitor_counter` ( `counts` int(10) NOT NULL default '0' )

 

Now create one file called counter.php and paste the below content.

<?php
// Connect to server and select database.
$con      = mysqli_connect("localhost", "root", "password", "test") or die(mysqli_error());

//select values from visitor_counter table
$sql     = "SELECT * FROM visitor_counter";
$result  = mysqli_query($con, $sql);
$row     = mysqli_fetch_array($result);
$counter = $row['counts'];

// setting counter = 1, if we have no counts value
if (empty($counter)) {
  $counter = 1;
  $sql1    = "INSERT INTO visitor_counter(counts) VALUES('$counter')";
  $result1 = mysqli_query($con, $sql1);
}

echo "You 're visitors No. ";
echo $counter;

// Incrementing counts value
$plus_counter = $counter+1;
$sql2         = "update visitor_counter set counts='$plus_counter'";
$result2      = mysqli_query($con, $sql2);

mysqli_close($con);
?>

 

Script Logic

(1) Database Connection
- You have to provide the database credentials to connect with your database.

(2) Select Total Numbers of Users
- Execute a simple select query to get the total count from the database table. if total = 0 it means the first visitor. In this case inserts the value in the table.

(3) Display Record
- Display the total count as a visitor count.

(4) Increment
- Increment the total number by 1 to update the total numbers of counts.

 

That's it..!! Your simple visitor counter script with PHP and MySQL is ready. You can make changes as per your requirements and use this logic in any framework.


 

Ketan Patel

As a backend and ecommerce developer, I have extensive experience in implementing robust and scalable solutions for ecommerce websites and applications. I have a deep understanding of server-side technologies and have worked with various programming languages. I have experience in integrating with payment gateways, and other third-party services.