I am trying to insert 2 dates in UK format (dd/mm/yyyy) to a MySQL database in the MySQL US date format.
I am using str_to_date. The first instance of str_to_date works as expected, but the second instance always inserts the same date as the first instance of str_to_date, even though the original dates are different.
$date_1 = "10/01/2016";
$date_2 = "16/02/2016";
$sql = "INSERT INTO customers (date_1, date_2)
VALUES (STR_TO_DATE( '$date_1', '%m/%d/%Y %h:%i' ), STR_TO_DATE( '$date_2', '%m/%d/%Y %h:%i' ))";
What is the correct way of handling multiple instances of str_to_date in a MySQL insert statement?
Thank you
The format string of str_to_date()
tells MySQL what format the first argument's date value is in. It's not how to format the value going in to mysql (e.g. the destination) format. str_to_date's output is ALWAYS a native mysql date/time value, which is yyyy-mm-dd hh:mm:ss
Since you're saying the input format is monday/day
, but are providing day/month
values and NO time values, you get wonky results.
Try
24/01/2016
STR_TO_DATE( '$date_1', '%d/%m/%Y' )
instead. Note the removal of the time format characters. Your input string has no time values at all.
mysql> select str_to_date('24/01/2016', '%m/%d/%Y %h:%i');
+---------------------------------------------+
| str_to_date('24/01/2016', '%m/%d/%Y %h:%i') |
+---------------------------------------------+
| NULL |
+---------------------------------------------+
1 row in set, 1 warning (0.00 sec)
mysql> select str_to_date('24/01/2016', '%d/%m/%Y');
+---------------------------------------+
| str_to_date('24/01/2016', '%d/%m/%Y') |
+---------------------------------------+
| 2016-01-24 |
+---------------------------------------+
1 row in set (0.00 sec)