PHP mysql 自动插入时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8662898/
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
PHP mysql auto insert timestamp
提问by user1058275
Say I have a table name auto_parts with these fields.
id, part, price, timestamp
and I insert a new row via php as so:
假设我有一个包含这些字段的表名 auto_parts。
id, part, price, timestamp
我通过 php 插入一个新行,如下所示:
$query = "insert into auto_parts(id, part, price, timestamp)
values(1, 'axle', 200)"
mysql_query($query);
will that automatically add the timestamp. Or do I have to insert a value for timestamp myself?
会自动添加时间戳。还是我必须自己插入时间戳值?
回答by parapura rajkumar
What you need to do is declare timestamp
to be of type in your sql
您需要做的是timestamp
在您的 sql 中声明为类型
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
and modify the query to
并将查询修改为
$query = "insert into auto_parts(id, part, price)
values(1, 'axle', 200)"
mysql_query($query);
回答by Ali Demirci
$query = "insert into auto_parts(id, part, price, timestamp)
values(1, 'axle', 200, 'NOW()')"
mysql_query($query);
回答by David
Do it in SQL itself instead of passing it ... its more efficient ... This is the corresponding post:
在 SQL 本身中执行而不是传递它......它更有效......这是相应的帖子:
回答by Suneel Kumar
I know there are already answers to this question so I am kind of combining all answers and explaining a little bit. There may be two ways to do this,
我知道这个问题已经有了答案,所以我想结合所有答案并稍微解释一下。可能有两种方法可以做到这一点,
- Change your table and make timestamp column to default CURRENT_TIMESTAMP
- 更改您的表并使时间戳列默认为 CURRENT_TIMESTAMP
ALTER TABLE tablename MODIFY timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
ALTER TABLE tablename MODIFY timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
and modify your query like this, timestamp will be inserted automatically
并像这样修改您的查询,时间戳将自动插入
$query = "insert into auto_parts(id, part, price) values(1, 'axle', 200)"; mysql_query($query);
$query = "插入 auto_parts(id, part, price) values(1, 'axle', 200)"; mysql_query($query);
- If you have more than one timestamp table then you can make one as current timestamp and for other one use like this
- 如果您有多个时间戳表,那么您可以将一个作为当前时间戳,并作为其他用途使用
ALTER TABLE tablename MODIFY timestamp TIMESTAMP NOT NULL
ALTER TABLE 表名 MODIFY 时间戳 TIMESTAMP NOT NULL
and modify your query like this
并像这样修改您的查询
$query = "insert into auto_parts(id, part, price, timestamp) values (1, 'axle', 200, now())"; mysql_query($query);
$query = "插入 auto_parts(id, part, price, timestamp) 值 (1, 'axle', 200, now())"; mysql_query($query);