By Alvin Alexander. Last updated: June 19, 2024
Here's a quick example of how to default a MySQL timestamp field to "now", i.e., the current date and time.
The following MySQL table definition shows a field named date_created
that uses the SQL now
function to record the timestamp for when the row was created:
create table users ( id int unsigned auto_increment not null, username varchar(32) not null, password varchar(32) not null, date_created timestamp default now() ) ENGINE=InnoDB;
Just to highlight it, the "MySQL timestamp default to now" field is this one:
date_created timestamp default now()
If you do a SQL insert into this table like this — skipping over the date_created
field:
INSERT INTO users (username, password) VALUES ('FOO', 'BAR');
the date_created
timestamp field will default to the time the record was inserted into the MySQL table. By skipping over the field, you tell MySQL to use that default value of now
.