将日期/时间从 PHP 保存到 SQL
我想将 PHP 中的日期和时间保存到 SQL 中。下面是插入新记录的 SQL 语句(在类中的方法中找到):
INSERT INTO tbl_reviews (headline, text, date, rating, product_id, username)
value (:headline, :text, :date, :rating, :product_id, :username)
在我的 .php 页面中,我使用 $_SERVER['REQUEST_TIME']
调用当前日期和时间。但我仍然收到错误“日期时间值不正确”。我可以用什么来获取日期?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
可以生成您的时间戳:
这应该模仿 mysql 时间戳和日期时间格式。
假设 mysql 的时间戳与相关 php 服务器同步,您也可以只使用 mysql 当前时间戳函数:
NOW() 或 CURRENT_TIMESTAMP 或 CURRENT_TIMESTAMP()
Your timestamp can be generated:
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()
是否必须是准确的请求时间?您可以让您的生活更轻松,只需使用:
一旦您的条目写入表中,MySQL 就会插入当前日期。
Does it have to be the exact request time? You could make your life easier and simply use:
MySQL inserts the current date as soon your entry is written to the table.
这只是一个猜测,但 $_SERVER['REQUEST_TIME'] 返回一个浮点数,而不是有效的日期时间格式。
it is only a guess, but $_SERVER['REQUEST_TIME'] returns a float, not a valid datetime format.
如果您需要当前时间,可以这样做:
If you need the current time you can do it like that:
您可以使用 SQL 自己的 CURRENT_TIMESTAMP 值来获取自动格式化的时间戳。
至于$_SERVER['REQUEST_TIME'],您可以使用 time()或 microtime() 代替。
如前所述,REQUEST_TIME 以及 time() 和 microtime() 返回一个 UNIX 时间戳,其中基本上是自 UNIX 纪元以来经过的秒数,这与 DATETIME 字段期望的格式不同。
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.