将日期/时间从 PHP 保存到 SQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8794764/
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
Save date/time from PHP to SQL
提问by chris05
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):
我想将日期和时间从 PHP 保存到 SQL。这是插入新记录的 SQL 语句(在类中的方法中找到):
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?
在我的 .php 页面中,我使用 .php 调用当前日期和时间$_SERVER['REQUEST_TIME']
。但我仍然收到错误“日期时间值不正确”。我可以用什么来获取日期?
回答by Ben D
Your timestamp can be generated:
您的时间戳可以生成:
$timestamp = date('Y-m-d H:i:s');
This should mimic the mysql timestamp and datetime formats.
这应该模仿 mysql 时间戳和日期时间格式。
Assuming that the mysql has its timestamp synchronized with the php server in question, you can also just use the mysql current timestamp functions:
假设 mysql 的时间戳与相关的 php 服务器同步,您也可以只使用 mysql 当前时间戳函数:
NOW() or CURRENT_TIMESTAMP or CURRENT_TIMESTAMP()
NOW() 或 CURRENT_TIMESTAMP 或 CURRENT_TIMESTAMP()
回答by Mithrandir
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.
一旦您的条目写入表中,MySQL 就会插入当前日期。
回答by dana
it is only a guess, but $_SERVER['REQUEST_TIME'] returns a float, not a valid datetime format.
这只是一个猜测,但 $_SERVER['REQUEST_TIME'] 返回一个浮点数,而不是有效的日期时间格式。
回答by Andre Martov
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');
回答by Ryan Stortz
date_default_timezone_set('US/Eastern');
$cur_date=date("Y-m-d");
回答by MichD
You can use SQL's own CURRENT_TIMESTAMP value to get an automatically formatted timestamp.
您可以使用 SQL 自己的 CURRENT_TIMESTAMP 值来获取自动格式化的时间戳。
As for $_SERVER['REQUEST_TIME'], you can just use time()or microtime()instead.
至于 $_SERVER['REQUEST_TIME'],你可以使用time()或microtime()代替。
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.
如前所述,REQUEST_TIME 以及 time() 和 microtime() 返回一个UNIX 时间戳,它基本上是自 UNIX 纪元以来经过的秒数,这与 DATETIME 字段所期望的格式不同。