Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP not displaying time from database correctly

Tags:

php

I have a script that count downs the time until an event start

enter image description here

Start date and start time is retrieved from a database.

My Problem

Days is calculated correctly but hours are the same for each event and does not get calculated correctly

while(){
$gameDate = $row['event_date'];
$time=$row['event_time'];

        $calcDate = $gameDate.$time;
        $calcDate =  strtotime(str_replace('/', '-', $gameDate)); 
        $remaining = $calcDate - time();
        $days_remaining = floor($remaining / 86400);
        $hours_remaining = floor(($remaining % 86400) / 3600); 
}

EVENTS table

enter image description here

Again notice in the 1st image how hours are displayed as 13 for both events even though it is different times for both events in the database

Any idea what I am doing wrong here or how I can improve the script?

like image 953
Timothy Coetzee Avatar asked Jul 09 '15 11:07

Timothy Coetzee


1 Answers

You have an error in this line:

$calcDate =  strtotime(str_replace('/', '-', $gameDate));

Replace $gameDate by $calcDate which contains your full date + time string you created one line before:

$calcDate =  strtotime(str_replace('/', '-', $calcDate));

Or just make it this way:

$data = array(
   array('event_date' => '2015-07-13', 'event_time' => '15:00'),
   array('event_date' => '2015-07-11', 'event_time' => '20:00')
);

foreach ($data as $row) {
   $calcDate =  strtotime(str_replace('/', '-', $row['event_date'].$row['event_time'])); 
   $remaining = $calcDate - time();
   $days_remaining = floor($remaining / 86400);
   $hours_remaining = floor(($remaining % 86400) / 3600); 
   echo $days_remaining." ".$hours_remaining."\n";
}

Working code: http://sandbox.onlinephpfunctions.com/code/128a284a176098ede0dfc7bc18cfc5f7081d2afa

So you avoid to mix up the different variables. ;-)

like image 92
André Avatar answered Oct 05 '22 23:10

André