Home >Database >Mysql Tutorial >Why Does `date('Y-M-D G:i:s')` Fail to Insert into MySQL's `DATETIME` Column?

Why Does `date('Y-M-D G:i:s')` Fail to Insert into MySQL's `DATETIME` Column?

Susan Sarandon
Susan SarandonOriginal
2024-12-02 09:47:10474browse

Why Does `date('Y-M-D G:i:s')` Fail to Insert into MySQL's `DATETIME` Column?

PHP date() Formatting for MySQL DATETIME Insertion

When inserting values into a MySQL datetime column, it's crucial to use the correct format in your PHP code. The date() function can be used to prepare data in the desired format, but using incorrect parameters can lead to unexpected results.

Error with "M" and "D" Parameters

In the described problem, using date('Y-M-D G:i:s') consistently inserted "0000-00-00 00:00:00." This is because the "M" and "D" parameters represent textual representations of the month and day, not the numeric values expected by MySQL. The correct numeric formats are "m" and "d."

Solution: Numeric Date Formatting

To resolve the issue, use the following format in the date() function: date('Y-m-d H:i:s'). This format uses "m" for the numeric month and "d" for the numeric day. It also uses "H" for the 24-hour format of the hour.

Example:

$date = date('Y-m-d H:i:s');
$sql = "INSERT INTO table_name (datetime_column) VALUES ('$date')";

Using this corrected formatting will ensure that dates are inserted into the MySQL datetime column in the expected format.

The above is the detailed content of Why Does `date('Y-M-D G:i:s')` Fail to Insert into MySQL's `DATETIME` Column?. 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