php 将时间插入数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22703765/
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
Inserting time into database
提问by TheViralGriffin
The below piece of code isn't working the way it is supposed to
下面的代码没有按照预期的方式工作
$t = date('Y-d-m H:i:s',time());
$query = "INSERT INTO time VALUES('$t')";
if(mysql_query($query))
echo "Date and Time are added";
I have created a table named time
with only one column now
and DATETIME
as datatype. Even though the PHPscript executes successfully in the browser by printing "Date and Time are added"
.
The database isn't updating the way it is supposed to be. Rather than the current time, it gets initialized to default value.
Do suggest the way to rectify the problem.
我创建了一个名为表time
只有一列now
,并DATETIME
为数据类型。即使PHP脚本通过打印在浏览器中成功执行"Date and Time are added"
。
数据库没有按照它应该的方式更新。而不是当前时间,它被初始化为默认值。
请提出解决问题的方法。
回答by Companjo
You can use NOW()
您可以使用 NOW()
$query = "INSERT INTO `time` (`now`) VALUES (NOW())";
回答by Sadikhasan
Try with this format
试试这个格式
$t = date('Y-m-d H:i:s');
$query = "INSERT INTO time (now) VALUES('$t')";
if(mysql_query($query))
echo "Date and Time are added";
OR
或者
$query = "INSERT INTO time (now) VALUES(NOW())";
回答by Grand Marshal Braev
<?php
/* YOU NEED TO ESTABLISH FIRST A CONNECTION */
$con=mysqli_connect("Host","Username","Password","Database"); /* REPLACE THE NECESSARY HOST, USERNAME, PASSWORD, AND DATABASE */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$t = date('Y-d-m H:i:s');
$query = mysqli_query($con,"INSERT INTO time (now) VALUES ('$t')");
echo "Date and Time are added";
?>
回答by Vagabond
Change the value of $t from
将 $t 的值从
$t = date('Y-d-m H:i:s',time());
to
到
$t = date('Y-m-d H:i:s');
Even better method would be to write your insert query like this:
更好的方法是像这样编写插入查询:
$query = "INSERT INTO `time` VALUES ('".date('Y-m-d H:i:s')."')";