MySQL auto-store datetime for each row

北战南征 提交于 2019-11-27 17:42:05
OMG Ponies

You can use DEFAULT constraints to set the timestamp:

ALTER TABLE
 MODIFY dt_created datetime DEFAULT CURRENT_TIMESTAMP

ALTER TABLE
 MODIFY dt_modified datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Then you wouldn't have to specify NOW() in your INSERT/UPDATE statements.

Reference: TIMESTAMP properties

If you're using phpmyadmin you can do this by :

ALTER TABLE  `tablename` CHANGE  `dt`  `dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

should be the correct code.

Well, you can't have both:

mysql doc:

It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.

Sad, isn't it?

You could however use null instead of now() following this tip

GrayWizardx

Similar question was asked here "Timestamp for MySQL" the timestamp field will update every time it is accessed. You might also consider a Trigger placed on the table in question to automatically populate those fields for you. Depending on the environment some shops/businesses do not like the use of triggers and so you might have to find alternate work arounds.

user3110005

In phpmyadmin you can set

OR use this query

ALTER TABLE  `tablename`
    CHANGE  `dt_created`  `dt_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!