skip to Main Content

I have implemented a SQL database to track the number of visitors to my website on a daily basis. The intention is to display this visitor count at the bottom of the website. However, I’m facing an issue where the counter doesn’t reset after 24 hours and continues to increment.

I would greatly appreciate it if someone could help me identify the problem in my code.

Here’s the relevant code snippet in php where I’m performing the count:

here is the code in php:

<?php

$mysqliCounter = new mysqli(
    "localhost","User","pass","website_db"
);

// Check connection
if ($mysqliCounter -> connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqliCounter -> connect_error;
    exit();
}

$mysqliCounter->query('INSERT INTO `views` (`id`, `time`) VALUES (NULL, CURRENT_TIMESTAMP)');

After the code, I have implemented the following logic to perform the counting:

Today Visitors:
<?php

echo $mysqliCounter->query(
    'SELECT * FROM views WHERE time > ''
    . date("Y-m-d H:i:s" , time() -86400) . "'")
           ->num_rows

?>

2

Answers


  1. Try this
    Today Visitors:

    <?php echo $mysqliCounter->query('SELECT * FROM views WHERE time >= CURDATE() ') ->num_rows; ?>

    Login or Signup to reply.
  2. Thanks to @YourCommonSense for better idea.

    You have to first convert both the dates into char and compare in where condition like below.

    // Changing `SELECT *` to `SELECT COUNT(*)`, since we dont want any rows to be fetched.
    // We need only the total number of rows present based on `where` condition.
    // This will avoid unnecessary memory loads and query will executes faster, comparatively.
    echo $mysqliCounter->query('SELECT COUNT(*) FROM views WHERE DATE(time) = CURDATE()')->fetch_row[0];
    

    In the above code, we are converting the timestamp into date and comparing it with current date.

    We will get the count of all selected rows based on current date.

    NOTE : The current date will be based on the location of the server.

    RECOMMENDED IDEA

    (For small scale applications/website)

    Instead of using your DB, why dont you use filesystem and use one single file for each day.

    Creating / Appending a file on each visit.

    $oldCount = file_get_contents('hits'.date('Ymd')); // We dont need extn.
    $newCount = (int)$oldCount++;
    $f = fopen('hits'.date('Ymd'), 'w');
    flock($f, LOCK_EX | LOCK_NB);
    fwrite($f, $newCount);
    flock($f, LOCK_UN);
    fclose($f);
    
    echo $newCount;
    

    PHP’s flock() function will force the script to follow queque system to write to the same file. filewriter will lock the file and writes to it and unlocks and next filewriter will follow and so on . . .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search