Vipul Singh
Vipul Singh

Reputation: 163

retrieve Datetime object from mysql database in php

I have a specific problem regarding the mysql Datetime format to store the date and time together in table, so I have stored values in the table and now I want to retrieve those values and then compare that time with current datetime but things are going horribly wrong. this is what i tried so far..

<?php
    date_default_timezone_set('Asia/Calcutta');
    require_once('connect.php');

    $query="select matchTime from fixture_list where value1='Mumbai'";
    if($result= mysqli_query($con,$query)){
        while($row=mysqli_fetch_assoc($result)){
            print_r($row);
        }
        mysqli_free_result($result);
    }

    //$target = new DateTime('2018-07-27 01:00:00');
    $target = new DateTime($query);
    $now = new DateTime;
    $diff = $target->diff($now);

    if ($target > $now) {
        echo $diff->format('%a days, %h hours, %i minutes to go');
    } 
    else {
        echo $diff->format('%a days, %h hours, %i minutes too late');
    }
?>

My only purpose is to get the datetime value in string propbably which has been stored in the database and pass it to $target variable and then compare with $now, this is the error I m getting "Array ( [matchTime] => 2018-07-27 00:00:00 ) Array ( [matchTime] => 2018-07-27 00:00:00 ) Array ( [matchTime] => 2018-07-28 01:00:00 ) Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (select matchTime from fixture_list) at position 0 (s): The timezone could not be found in the database'"

Upvotes: 0

Views: 1833

Answers (1)

Nick
Nick

Reputation: 147146

This line:

$target = new DateTime($query);

should be:

$target = new DateTime($row['matchTime']);

Upvotes: 1

Related Questions