Im using jQuery datepicker
the format of the datepicker is this 08/25/2012
i have errors when inserting to my database it insert only 0000-00-00 00 00 00
my codes 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';
?>
im 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
altField
together with itsaltFormat
option:Or, if you're happy for users to see the date in
YYYY-MM-DD
format, simply set thedateFormat
option 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
DateTime
object: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
DATETIME
orTIMESTAMP
column for holding a date value; I recommend you consider using MySQL'sDATE
type instead. As explained in TheDATE
,DATETIME
, andTIMESTAMP
Types:You must make sure that the date format is YYYY-MM-DD on your jQuery output. I can see jQuery returns MM-DD-YYYY, which is not the valid MySQL date format and this is why it returns an error.
To convert it to the right one you could do this:
Then you will get formatted date that will be valid MySQL format, which is YYYY-MM-DD, i.e. 2012-08-25
I would also recommend using mysql_real_escape_string as you insert data into database to prevent SQL injections as a quick solution or better use PDO or MySQLi.
Your insert query using
mysql_real_escape_string
should rather look like this: