php 更新mysql中的日期时间变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11350099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:19:22  来源:igfitidea点击:

Update a datetime variable in mysql

phpmysqldatetime

提问by villeroy

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

我正在尝试使用DateTime变量更新我的 MySQL 数据库。

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

Now the SQL update:

现在 SQL 更新:

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

If I var_dumpthe $datevariable, it shows the right properties:

如果我var_dump$date变量,它会显示正确的属性:

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?

但它只是不会被插入。如果我尝试 NOW() 而不是 $date,它可以完美运行。我的错误是什么?

采纳答案by Ron

Try this:

尝试这个:

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

回答by Zane Bien

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