Search code examples
phpmysqltimerlamp

Retrieving Mktime values from Mysql using PHP


On my website I am attempting to make a countdown timer. The same code for the timer works if I tell it the value of the column and it works on a test php page. The problem is that the mktime value is not being read right from the mysql database. However if I put the column to output inside of an echo it outputs fine. The column that contains the data is called expire. The other values I am loading from mysql are inside of he echo however all connection statements are made before I call any. I am using the mysqli_fetch_array to call the values.

$target = mktime($row['expire']);
$today = time();
$difference = $target-$today;
$hours = $difference/3600;
$minutes = ($hours-floor($hours))*60;
echo('ENDS IN: '.floor($hours).' Hrs '.floor($minutes).' Mins');
Yes the document is HTML that it gets included into

The way I formatted the expire column in mysql was standard as Hr,Min,Sec,MM,DD,YYYY. The actual content of the column is "21,0,0,7,12,2017"

Thanks in advance, David.


Solution

  • The problem is, that you get a string from your database in $row['expire']. But mktime() is an integer only function. So, first you need a workaround to explode and convert your string to integers, before it will work with mktime().

    Please delete the following line from your code:

    $target = mktime($row['expire']);
    

    Try this instead:

    $timeparts = array_map('intval', explode(',', $row['expire']));
    $target = mktime($timeparts[0],$timeparts[1],$timeparts[2],$timeparts[3],$timeparts[4],$timeparts[5]);
    

    Hope it was helpful. But please do not save timevalues as a string in your database. Read about other possibilities in the manual.