Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql date created (not to update when record updated)

I'm doing a mysql table and i have one column that has current timestamp on update. This is great because i can see exactly when someone uploads something. But i dont want the column to change when they edit their upload. Is it best to stick with one column named "date created" and have NO on update or go with two columns "date created & "date modified" - if so whats the best practice for column attributes, and PHP update statements?

like image 394
benhowdle89 Avatar asked Dec 29 '22 01:12

benhowdle89


1 Answers

I usually like to have a separate "CreateDate" and "LastModifiedDate".

As for setting it, it would be nice if you could just set the default value for the CreateDate column to NOW(), but MySQL doesn't allow that.

So, the easiest option would be to use an insert trigger to do it:

CREATE TRIGGER tbl_insert BEFORE INSERT ON `tbl`
    FOR EACH ROW SET NEW.CreateDate = NOW(), NEW.LastModifiedDate = NOW();

ETA:

You can use a TIMESTAMP field with a default value of CURRENT_TIMESTAMP and the ON UPDATE CURRENT_TIMESTAMP constraint for the LastModifiedDate as well. Unfortunately you can't have two such TIMESTAMP columns on the same table, so the trigger is necessary to handle the CreateDate column.

like image 160
Eric Petroelje Avatar answered Jan 05 '23 17:01

Eric Petroelje