更新mysql时间戳

时间:2012-07-03 12:55:57

标签: php mysql timestamp

我有一个带有字段的表:

  

'last_modified - timestamp NOT NULL'

  • 我将默认值设置为当前时间戳。但是这只适用于从phpMyAdmin更新或插入而不是从我的脚本更新或插入。

我试过了

$sql = sprintf("UPDATE %s SET timestamp=now(), %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);

它似乎仍然无法正常工作。如何在脚本中按表更新或插入时更新时间戳?

还有一个脚本输出示例:

  

更新关于SET timestamp = now(),page_header ='页眉在这里',sub_header ='Sub header goes here',content_short ='这是关于about page的简短说明',content ='这是完整内容描述'WHERE id ='1'

的地方

4 个答案:

答案 0 :(得分:9)

可能是我误读了,但您的列名是 last_modified (键入 timestamp ),因此查询应为:

UPDATE about SET last_modified=now(), 
page_header = 'Page header goes here', 
sub_header = 'Sub header goes here', 
content_short = 'This is where a short description of the about page goes', 
content = 'This is where the full content description goes' 
WHERE id='1'

答案 1 :(得分:1)

如果您使用reserved word作为表格或列名,那么您需要引用它

$sql = sprintf("UPDATE %s SET `timestamp`=now(), %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);

在这种情况下,您使用时间戳作为列名,因此您需要引用它

要自动更新时间戳,如果您只有1个时间戳列,则可以依赖mysql本身,或者在定义时间戳列时可以添加ON UPDATE CURRENT_TIMESTAMP,有关详细信息,请参阅TIMESTAMP initialisation

答案 2 :(得分:0)

如果您想在每次记录发生某些事情时更新时间戳(即最后修改日期/时间),那么最好将其留在DB中。您不能依赖字段定义中的默认值,因为它仅适用于INSERT(创建记录/字段时),使用 SET last_modified = GETDATE()[或GETUTCDATE()] 实际的功能可能因实际的SQL服务器而异。

“Ivan Buttinoni”绝对正确,包括我在内的任何人都没有注意到它 - 你的字段名称错误,但上述评论仍然适用。

答案 3 :(得分:0)

如果你有类似Framework的东西,不允许“now()”这个字段 - 只需将字段设为NOT NULL并在保存之前将PHP变量(model->字段)设置为null。