简体   繁体   中英

Save date/time from PHP to SQL

I want to save the date and time from PHP to SQL. Here is the SQL statement to insert new record (found in a method within a class):

INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
            value (:headline, :text, :date, :rating, :product_id, :username)

And in my .php page, I call the current date and time using $_SERVER['REQUEST_TIME'] . But still I'm getting the error "Incorrect datetime value". What can I use to get the date?

Your timestamp can be generated:

$timestamp = date('Y-m-d H:i:s');

This should mimic the mysql timestamp and datetime formats.

Assuming that the mysql has its timestamp synchronized with the php server in question, you can also just use the mysql current timestamp functions:

NOW() or CURRENT_TIMESTAMP or CURRENT_TIMESTAMP()

Does it have to be the exact request time? You could make your life easier and simply use:

INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
            value (:headline, :text, now(), :rating, :product_id, :username)

MySQL inserts the current date as soon your entry is written to the table.

它只是一个猜测,但$ _SERVER ['REQUEST_TIME']返回一个浮点数,而不是一个有效的日期时间格式。

If you need the current time you can do it like that:

INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
INSERT INTO tbl_reviews ('$headline', '$text', CURDATE(), '$rating', '$product_id', '$username');
date_default_timezone_set('US/Eastern');
$cur_date=date("Y-m-d");

You can use SQL's own CURRENT_TIMESTAMP value to get an automatically formatted timestamp.

As for $_SERVER['REQUEST_TIME'], you can just use time() or microtime() instead.

As mentioned, REQUEST_TIME, as well as time() and microtime() return a UNIX timestamp , which is basically the amount of seconds that have passed since the UNIX epoch, which is not the same format as a DATETIME field expects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM