Ribal
Ribal

Reputation: 1

Is it a good way to count unique visitors?

<?php

    $date = date("Y-m-d"); //Return current date in yyyy-mm-dd format
    $userIP = $_SERVER['REMOTE_ADDR'];// Stores remote user ip address

    $query = "SELECT * FROM `unique_visitors` WHERE `date` = '$date'";
    $result = mysqli_query($connection,$query);

    if($result->num_rows == 0)// this block will execute when there is no record of current date in database
    {
        $insertQuery = "INSERT INTO `unique_visitors` (`date`,`ip`) VALUES ('$date','$userIP')";
        mysqli_query($connection,$insertQuery);
    }
    else
    {
        $row = $result->fetch_assoc();//Extracts result row from result object

        if(!preg_match('/'.$userIP.'/i',$row['ip']))//Will execute When Current ip is not in databse
        {
            $newIP = "$row[ip] $userIP"; //Combine previous and current user ip address with a separator for updating in database
            $updateQuery = "UPDATE `unique_visitors` SET `ip`='$newIP', `views`=`views`+1 WHERE `date` = '$date' ";
            mysqli_query($connection,$updateQuery);
        }
    }
?>

Is there a better way to count unique visitors in my website or this simple code is fine to insert into my website?

Upvotes: 0

Views: 63

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 158005

Here is the basic PHP/mysqli code for the approach you taken. You have to create an unique index for two fields, date and ip. And everything would work with just a single query.

<?php

$userIP = $_SERVER['REMOTE_ADDR'];// Stores remote user ip address

$sql = "INSERT INTO unique_visitors (date, ip, views) VALUES (curdate(),?,1)
          ON DUPLICATE KEY UPDATE views = views + 1";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $userIP);
$stmt->execute();

$sql = "SELECT count(*) FROM unique_visitors WHERE date = curdate()";
$result = $connection->query($sql);
$visitors = $result->fetch_row()[0];

Upvotes: 2

Related Questions