What are the best practices for automatically filling creation/update dates in MySQL using PHP?
When working with MySQL databases in PHP, it is a common practice to automatically fill creation/update dates for records. This can be achieved by setting the default values for the creation/update date columns to the current timestamp in the database table definition. By doing this, whenever a new record is inserted or an existing record is updated, the creation/update dates will be automatically filled with the current timestamp.
// Set the default values for creation/update dates in the MySQL table definition
CREATE TABLE example_table (
id INT AUTO_INCREMENT PRIMARY KEY,
data VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
// Insert a new record into the table
INSERT INTO example_table (data) VALUES ('example data');
// Update an existing record in the table
UPDATE example_table SET data = 'updated data' WHERE id = 1;