How to Add a Visitor Counter to a Website using PHP and MySQL
When a user visit a website and access the the content based on the IP address of the device and it will count the visitors.
First create a table in MySQL database as shown in the picture below
Then write a PHP code to count the visitor
/*visitor counter*/
function total_views($conn, $post_id = null)
{
if($post_id === null)
{
// count total website views
$query = "SELECT sum(total_views) as total_views FROM posts";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = $result->fetch_assoc())
{
if($row['total_views'] === null)
{
return 0;
}
else
{
return $row['total_views'];
}
}
}
else
{
return "No records found!";
}
}
else
{
// count specific page views
$query = "SELECT total_views FROM posts WHERE id='$post_id'";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = $result->fetch_assoc())
{
if($row['total_views'] === null)
{
return 0;
}
else
{
return $row['total_views'];
}
}
}
else
{
return "No records found!";
}
}
}
function is_unique_view($conn, $visitor_ip, $post_id)
{
$query = "SELECT * FROM post_views WHERE visitor_ip='$visitor_ip' AND post_id='$post_id'";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
return false;
}
else
{
return true;
}
}
function add_view($conn, $visitor_ip, $post_id)
{
if(is_unique_view($conn, $visitor_ip, $post_id) === true)
{
// insert unique visitor record for checking whether the visit is unique or not in future.
$query = "INSERT INTO post_views (visitor_ip, post_id) VALUES ('$visitor_ip', '$post_id')";
if(mysqli_query($conn, $query))
{
// At this point unique visitor record is created successfully. Now update total_views of specific page.
$query = "UPDATE posts SET total_views = total_views + 1 WHERE id='$post_id'";
if(!mysqli_query($conn, $query))
{
echo "Error updating record: " . mysqli_error($conn);
}
}
else
{
echo "Error inserting record: " . mysqli_error($conn);
}
}
}
finally add add_view() function at the top of your page
<?php
$post_id =$post['id'];
$visitor_ip = $_SERVER['REMOTE_ADDR']; // stores IP address of visitor in variable
add_view($conn, $visitor_ip, $post_id);
?>
the inside your webpage return the count where you want to be.
<div>
<?php echo number_format($post['total_views']); ?> Views
</div>
if you implement as described we will get the result as a screenshot below in post_views table