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
Try this
Today Visitors:
<?php echo $mysqliCounter->query('SELECT * FROM views WHERE time >= CURDATE() ') ->num_rows; ?>
Thanks to @YourCommonSense for better idea.
You have to first convert both the dates into char and compare in
where
condition like below.In the above code, we are converting the
timestamp
intodate
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.
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 . . .