4

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?

3
  • 2
    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. Commented Jul 5, 2012 at 18:13
  • and why not use NOW() since it works ? Commented Jul 5, 2012 at 18:16
  • 1
    because the date should be user-specified and its not now. Commented Jul 5, 2012 at 18:17

2 Answers 2

3

Try this:

"UPDATE table SET table.table_date = '{$date->format('Y-m-d H:i:s')}'"
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.