-1

我想将 PHP 中的日期时间保存到我的数据库中,但我不能。数据库中的日期时间值始终设置为0000-00-00 00:00:00. 我究竟做错了什么?

我的代码:

$today = new DateTime();
$dt = $today->format('Y-m-d H:i:s');
$sql = "UPDATE wp_posts SET  post_date = $dt, post_date_gmt = $dt WHERE ID = $id";
4

5 回答 5

6

尝试加引号:

$today = new DateTime();
$dt = $today->format('Y-m-d H:i:s');
$sql = "UPDATE wp_posts SET  post_date = '$dt', post_date_gmt = '$dt' WHERE ID = $id";
于 2013-10-16T11:35:04.970 回答
4

简单地说,日期时间是字符串,而不是整数。

$today = new DateTime();
$dt = $today->format('Y-m-d H:i:s');
$sql = "UPDATE wp_posts SET  post_date = '$dt', post_date_gmt = $dt WHERE ID = $id";

效果会更好:)

于 2013-10-16T11:35:43.947 回答
0

为什么不将mysql的时间戳功能 用于新表

$sql = CREATE TABLE newtb (current_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
or 
$sql = CREATE TABLE newtb (current_time DATETIME DEFAULT NOW());

修改表

$sql = CREATE TABLE newtb MODIFY current_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
or 
$sql = CREATE TABLE newtb MODIFY current_time DATETIME DEFAULT NOE();
于 2013-10-16T11:55:10.230 回答
0

你可以使用,

$dt = date("Y-m-d H:i:S");
$sql = "UPDATE wp_posts SET  post_date = '$dt', post_date_gmt = '$dt' WHERE ID = $id";
于 2013-10-16T11:36:04.550 回答
0

您应该使用 mysql inbuit now() 函数,而不是使用 PHP 中的日期时间,而无需在 php 中编写额外的代码行。

    $sql = "UPDATE wp_posts SET  post_date = now(), post_date_gmt = now() WHERE ID = $id";

n 你也可以在你的表字段中设置 Now() 所以你不需要设置为查询,当记录将插入更新时,它会自动设置当前日期时间。

    CREATE TABLE tablename
    (
        fiedlId int NOT NULL,
        fieldName varchar(50) NOT NULL,
        fieldDate datetime NOT NULL DEFAULT NOW(),
        PRIMARY KEY (fiedlId)
    )

干杯!!

于 2013-10-16T11:47:09.670 回答