Home > Database > Mysql Tutorial > How to Properly Insert Dates into MySQL DATETIME Columns Using PHP's `date()` Function?

How to Properly Insert Dates into MySQL DATETIME Columns Using PHP's `date()` Function?

Susan Sarandon
Release: 2024-12-01 04:43:27
Original
643 people have browsed it

How to Properly Insert Dates into MySQL DATETIME Columns Using PHP's `date()` Function?

Inserting Dates Into MySQL DATETIME Columns Using PHP's date() Function

When attempting to insert a date into a MySQL datetime column using PHP's date() function, some may encounter issues where "0000-00-00 00:00:00" is inserted instead of the intended date.

One common mistake is using 'M' and 'D' in the date() format string. These characters represent textual representations of the month and day, which MySQL does not recognize. Instead, MySQL expects numeric representations, such as 02 for February and 06 for the 6th day.

To correct this issue, use the numeric equivalents 'm' and 'd' in the date() format string. The correct format for inserting a datetime into a MySQL column is:

date('Y-m-d H:i:s')
Copy after login

This format includes the year (Y), numeric month (m), numeric day (d), hour (H), minute (i), and second (s).

For example, the following code would insert the current date and time into a MySQL datetime column:

$date = date('Y-m-d H:i:s');
$sql = "INSERT INTO `table` (`datetime`) VALUES ('$date')";
Copy after login

By using the correct numeric format, you can ensure that dates are inserted into MySQL datetime columns as expected.

The above is the detailed content of How to Properly Insert Dates into MySQL DATETIME Columns Using PHP's `date()` Function?. 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