Home >Database >Mysql Tutorial >How to Fix '0000-00-00 00:00:00' Date Insertion Errors in PHP and MySQL?
PHP MySQL Insert Date Format: Resolving Invalid Date Issue
Inserting a date into a MySQL database can sometimes result in an error where the database inserts only '0000-00-00 00 00 00' despite the correct date format in the code. This issue arises when the date format is not recognized by MySQL.
To resolve this issue, it is essential to follow the specified date formats that MySQL accepts:
In the given code, the date is received in the format '08/25/2012', which is not recognized by MySQL. Therefore, we need to modify the date format to one of the supported formats.
Options for Resolving the Date Format Issue:
altField and <code data-type="javascript">altFormat to specify the format in which the date is passed to the PHP script. For example, <code data-type="javascript">altFormat: "yyyy-mm-dd".
Use STR_TO_DATE() Function: Convert the date string to MySQL's supported format using the STR_TO_DATE() function. Example:
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
Use DateTime Object: Convert the date string into a PHP DateTime object, obtain the formatted string, and use it in the insert query. Example:
$dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']); $date = $dt->format('Y-m-d'); INSERT INTO user_date VALUES ('', '$name', '$date')
Manipulate Date String: Manually manipulate the date string to convert it into a valid MySQL format. Example:
$parts = explode('/', $_POST['date']); $date = "$parts[2]-$parts[0]-$parts[1]"; INSERT INTO user_date VALUES ('', '$name', '$date')
Additional Considerations:
The above is the detailed content of How to Fix '0000-00-00 00:00:00' Date Insertion Errors in PHP and MySQL?. For more information, please follow other related articles on the PHP Chinese website!