Home  >  Article  >  Backend Development  >  How to Format Dates for MySQL datetime Insertion Using PHP\'s date() Function?

How to Format Dates for MySQL datetime Insertion Using PHP\'s date() Function?

DDD
DDDOriginal
2024-11-02 15:21:02875browse

How to Format Dates for MySQL datetime Insertion Using PHP's date() Function?

How to Use date() Function in PHP for MySQL datetime Insertion

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.

Incorrect Format: date('Y-M-D G:i:s')

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).

Correct Format: date('Y-m-d H:i:s')

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.

Example

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn