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
Release: 2024-12-02 09:47:10
Original
509 people have browsed it

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')";
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template