Search code examples
phpmysqldatabasetimercountdown

Countdown timer PHP error


I am trying to make a countdown timer which displays how many days until the product expires, and when there are 0 days, I want to display a message saying that it has expired:

<?php
$target =  mktime(0, 0, 0, 1, 7, 2013) ;
$today = time () ;
$difference =($target-$today) ;
$days =(int) ($difference/86400) ;
if ($today == $target)
{
print "this product has expired";
}
else
{
print "This product expires in $days days";
}
?>

When you visit the page, it always displays the second message, even though today is the same date as the target date.

If possible as well, could you tell me how to display the minutes and seconds without reloading the page? I would also like to update a MySQL Database when there are 0 days/minutes left, is this possible? There does not need to be a start/stop button.


Solution

  • I think you already got the solution. But if someone is still looking for this solution then this might help. In this solution we can split days,hours,mins,seconds.

    Reverse timer from javascript:
    
    var target_date = new Date('Aug 01 2014 20:47:00').getTime();
        var days, hours, minutes, seconds;
        var countdown = document.getElementById('timeremaining');
        var countdownTimer = setInterval(function () {
            var current_date = new Date().getTime();
            var seconds_left = (target_date - current_date) / 1000;
    
            days = parseInt(seconds_left / 86400);
            seconds_left = seconds_left % 86400;
    
            hours = parseInt(seconds_left / 3600);
            seconds_left = seconds_left % 3600;
            minutes = parseInt(seconds_left / 60);
            seconds = parseInt(seconds_left % 60);
    
            if(days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0 )
            {
               document.getElementById('timeremaining').innerHTML = '';
               clearInterval(countdownTimer);              
            }
            else
            {       
                if(days>0)
                  {
                     days= days+'d,';
                  } 
                  else
                  {
                     days='';
                  }            
                countdown.innerHTML ='( ' + days + checkTime(hours) + ':'+ checkTime(minutes) + ':' + checkTime(seconds) +' remaining)';    
            }
        }, 1000);
    
        function checkTime(i) {
            if (i < 10) {i = '0' + i};  
            return i;
        }