Inserting Date Formats into MySQL Using PHP
When working with the MySQL database, it's essential to format date values correctly during insertion. A common issue is inserting dates in the incorrect format, leading to database errors.
Problem:
You're using the jQuery datepicker, which returns dates in 'MM/DD/YYYY' format. However, MySQL expects dates in specific formats, such as 'YYYY-MM-DD', 'YY-MM-DD', or 'YYYYMMDD'. Inserting dates in the incorrect format will result in '0000-00-00 00 00 00' being inserted.
Solution:
There are several ways to resolve this issue:
<input type="hidden">
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
$dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']); $date = $dt->format('Y-m-d'); // Formatted string $timestamp = $dt->getTimestamp(); // UNIX timestamp
$parts = explode('/', $_POST['date']); $date = "$parts[2]-$parts[0]-$parts[1]";
Caution:
Additional Notes:
The above is the detailed content of How to Correctly Insert Dates from jQuery Datepicker into MySQL Using PHP?. For more information, please follow other related articles on the PHP Chinese website!