I’m using jQuery datepicker
the format of the datepicker is this 08/25/2012
I have errors when inserting to my database it inserts only 0000-00-00 00 00 00
My code is:
<?php
$id = $_POST['id'];
$name = $_POST['name'];
$date = $_POST['date'];
$sql = mysql_query( "INSERT INTO user_date VALUE( '', '$name', '$date')" ) or die ( mysql_error() );
echo 'insert successful';
?>
I’m sure my insert is correct.
As stated in Date and Time Literals:
Therefore, the string
'08/25/2012'is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):Configure Datepicker to provide dates in a supported format using an
altFieldtogether with itsaltFormatoption:Or, if you’re happy for users to see the date in
YYYY-MM-DDformat, simply set thedateFormatoption instead:Use MySQL’s
STR_TO_DATE()function to convert the string:Convert the string received from jQuery into something that PHP understands as a date, such as a
DateTimeobject:and then either:
obtain a suitable formatted string:
obtain the UNIX timestamp:
which is then passed directly to MySQL’s
FROM_UNIXTIME()function:Manually manipulate the string into a valid literal:
Warning
Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don’t know what I’m talking about, or how to fix it, read the story of Bobby Tables.
Also, as stated in the introduction to the PHP manual chapter on the
mysql_*functions:You appear to be using either a
DATETIMEorTIMESTAMPcolumn for holding a date value; I recommend you consider using MySQL’sDATEtype instead. As explained in TheDATE,DATETIME, andTIMESTAMPTypes: