PHP mysql insert date format
When using a jQuery datepicker with a format of 'MM/DD/YYYY' to insert dates into a MySQL database, you may encounter errors with the inserted date being stored as '0000-00-00 00:00:00'. This issue arises because the 'MM/DD/YYYY' format is not recognized as a valid date literal by MySQL.
According to the MySQL documentation on Date and Time Literals, MySQL recognizes DATE values in the following formats:
To resolve this issue, you can explore the following options:
Create a DateTime object from the jQuery datepicker string:
$date = \DateTime::createFromFormat('m/d/Y', $_POST['date']);
Then, format the date into a supported format:
$date_string = $dt->format('Y-m-d');
Convert the jQuery datepicker string to a MySQL-compatible format using the STR_TO_DATE() function:
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
Split the jQuery datepicker string into parts for month, day, and year, then create a MySQL-compatible string:
$parts = explode('/', $_POST['date']); $mysql_date = "$parts[2]-$parts[0]-$parts[1]";
Configure the datepicker to output dates in a supported format using the dateFormat or altField altFormat options:
$( "selector" ).datepicker({ dateFormat: "yyyy-mm-dd" });
or
$( "selector" ).datepicker({ altField: "#actualDate" altFormat: "yyyy-mm-dd" });
Caution:
It's important to protect against SQL injection by using prepared statements. Additionally, consider using the DATE data type in MySQL for storing dates, as it is designed specifically for this purpose.
The above is the detailed content of How to Properly Insert Dates from a jQuery Datepicker into a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!