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')
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')";
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!