Search code examples
phpmysqldatetimedate-arithmetic

Object of class DateTime could not be converted to string in my query. What am I doing wrong here?


I have the following query in php/mysql:

$q2 = $conn3->prepare("SELECT (t.start_time + INTERVAL t.text_duration SECOND) as end_time FROM texts t WHERE t.start_time <= :starttime AND (t.start_time + INTERVAL t.text_duration SECOND) >= :starttime AND t.plot_id = :plot_id LIMIT 1"); 
$q2->bindValue(':starttime', $start_timestamp);
$q2->bindValue(':plot_id', $plot_id);
$q2->execute();
$check2 = $q2->fetch(PDO::FETCH_ASSOC);

$start_time is a datetime object defined as follows:

$date = new DateTime();
$start_timestamp = $date->add(DateInterval::createFromDateString('10 minutes'));

When I run it, I get the following error:

Catchable fatal error:  Object of class DateTime could not be converted to string in ...

How can I fix it?


Solution

  • You only have a DateTime object when you called DateTime::add(). You still have to convert it to a timestamp. Use DateTime::getTimestamp() to do that. You still need to convert it to a datetime value. Use DateTime::format() to do this.

    $start_timestamp = $date->add(DateInterval::createFromDateString('10 minutes'))->format('Y-m-d H:i:s');