I want to save a datetime from PHP into my database, but I cannot. The datetime value in the database is always set as 0000-00-00 00:00:00
. What am I doing wrong?
My code:
$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";
try put quotation marks:
$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";
Simply, datetime is string, not integer.
$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";
will be works better:)
You can just use,
$dt = date("Y-m-d H:i:S");
$sql = "UPDATE wp_posts SET post_date = '$dt', post_date_gmt = '$dt' WHERE ID = $id";
Instead of using date time from PHP you should use mysql inbuit now() function, no need to write extra line of code in php.
$sql = "UPDATE wp_posts SET post_date = now(), post_date_gmt = now() WHERE ID = $id";
n you can alos set Now() in your table field so you dont need to set as query , when record will insert to update it will automatically set the current date time.
CREATE TABLE tablename
(
fiedlId int NOT NULL,
fieldName varchar(50) NOT NULL,
fieldDate datetime NOT NULL DEFAULT NOW(),
PRIMARY KEY (fiedlId)
)
Cheers!!
why don't you use timestamp function of mysql for new table
$sql = CREATE TABLE newtb (current_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
or
$sql = CREATE TABLE newtb (current_time DATETIME DEFAULT NOW());
to modify Table
$sql = CREATE TABLE newtb MODIFY current_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
or
$sql = CREATE TABLE newtb MODIFY current_time DATETIME DEFAULT NOE();