Datetime Format Insertion into MySQL using PHP's date() Function
Inserting dates into a MySQL database using PHP's date() function requires adherence to a specific format for the MySQL datetime data type.
The issue with the provided format date('Y-M-D G:i:s') lies in the use of 'M' and 'D', representing textual values for month and day respectively. MySQL, however, expects numeric representations of these components, such as '02' for February and '06' for the 6th.
To rectify this, the correct format to use in the date() function for inserting into a MySQL datetime column is:
date('Y-m-d H:i:s')
This format uses the numeric equivalents 'm' for month and 'd' for day, ensuring compatibility with the MySQL datetime data type.
For example, the following code snippet demonstrates the correct usage of the date() function for inserting a datetime value into a MySQL database:
<?php $datetime = date('Y-m-d H:i:s'); $query = "INSERT INTO table (datetime_column) VALUES ('$datetime')"; // Execute the query using a database connection. ?>
The above is the detailed content of How to Correctly Format Dates for MySQL DateTime Columns using PHP\'s date() Function?. For more information, please follow other related articles on the PHP Chinese website!