Home >Backend Development >PHP Tutorial >How to Format Dates for MySQL datetime Insertion Using PHP\'s date() Function?
When working with MySQL datetime type columns, it's crucial to format the date correctly before inserting it into the database. The date() function in PHP can be used to convert dates into specific formats.
Using the format date('Y-M-D G:i:s') will result in the constant insertion of "0000-00-00 00:00:00" because MySQL expects numeric representations for dates and times. 'M' and 'D', which represent textual month and day, should be replaced with their numeric counterparts: month (01-12) and day (01-31).
To insert dates and times correctly into MySQL datetime type columns, use date('Y-m-d H:i:s'). This format specifies the year (Y), month (m), day (d), hours (H in 24-hour format), minutes (i), and seconds (s) using numeric representations. It matches the expected format by MySQL: YYYY-MM-DD HH:MM:SS.
For example:
<code class="php">$date = date('Y-m-d H:i:s'); $query = "INSERT INTO table (datetime_column) VALUES ('$date')";</code>
This will correctly insert the current date and time into the specified datetime_column column in the MySQL database.
The above is the detailed content of How to Format Dates for MySQL datetime Insertion Using PHP\'s date() Function?. For more information, please follow other related articles on the PHP Chinese website!