我想将 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";
尝试加引号:
$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";
简单地说,日期时间是字符串,而不是整数。
$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";
效果会更好:)
为什么不将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();
你可以使用,
$dt = date("Y-m-d H:i:S");
$sql = "UPDATE wp_posts SET post_date = '$dt', post_date_gmt = '$dt' WHERE ID = $id";
您应该使用 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)
)
干杯!!