villeroy
villeroy

Reputation: 65

Update a datetime variable in mysql

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?

Upvotes: 4

Views: 29076

Answers (2)

Zane Bien
Zane Bien

Reputation: 23125

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'";

Upvotes: 3

Ron
Ron

Reputation: 1336

Try this:

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

Upvotes: 3

Related Questions