Update a datetime variable in mysql

26,658

Solution 1

Try this:

"UPDATE table SET table.table_date = '{$date->format('Y-m-d H:i:s')}'"

Solution 2

It's not working because you are trying to insert an object directly into a string. What you need to do is convert the object to a usable datetime string first:

$futuredate = $date->format('Y-m-d H:i:s');
$query = "UPDATE table SET table.table_date = '$futuredate'";
Share:
26,658
villeroy
Author by

villeroy

Updated on July 09, 2022

Comments

  • villeroy
    villeroy almost 2 years

    I'm trying to update my MySQL database with a DateTime variable.

    $interval = 'P' . $days . 'DT' . $hours. 'H' . $minutes. 'M' . $seconds . 'S'  ;
    $date = new DateTime("NOW");
    $date->add(new DateInterval($interval));
    

    Now the SQL update:

    $query = "UPDATE table
    SET table.table_date = '$date' ";
    mysql_query($query);
    mysql_query($query);
    

    If I var_dump the $date variable, it shows the right properties:

    object(DateTime)#4 (3) { ["date"]=> string(19) "2012-07-05 20:04:14" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" }
    

    but it just wont be inserted. If I try NOW() instead of $date, it works perfectly. Whats my mistake?

    • Ry-
      Ry- almost 12 years
      You should use PDO or MySQLi instead of the mysql_ extensions, whose use is discourage and which will probably be removed from PHP soon. Using prepared statements should also solve this problem.
    • Gntem
      Gntem almost 12 years
      and why not use NOW() since it works ?
    • villeroy
      villeroy almost 12 years
      because the date should be user-specified and its not now.