Link to home
Start Free TrialLog in
Avatar of kenjpete
kenjpete

asked on

Problem with inserting date into MySQL using PHP post form variable

I have an HTML form using the jquery datepicker to insert the date into a MySQL database using PHP post form variable. Everytime I try to insert the date it inserts the date as 0000-00-00. I've been looking around for the solution and I can't seem to find it. My code is below.

PHP:
$release_date=$_POST['release_date'];
$date=strtotime($release_date);

HTML:
<input type="text" name="release_date" id="datepicker" size="40" required>

SQL:
$sql = "INSERT INTO books(title, description, price, release_date, quantity, active) VALUES ('$title','$description','$price',$date,'$quantity','$active');";

The release_date field in my database table is set to DATE.
Avatar of arnold
arnold
Flag of United States of America image

Why not use now() and let the server time apply.  Rather than trying to convert something that might not be in the correct format to be converted.  You are not validating so my guess is that the data provided does not match the format.
If the user must insert, you shou,d make sure the format of the date provided is correct.
From http://php.net/manual/en/function.date.php ...
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
You can shorten it to this for just DATE.
$today = date("Y-m-d");                   // 2001-03-10 (the MySQL DATE format)
MySQL is very picky about the format for a DATE field.  Which is why I always use dropdowns instead of allowing users to type in unformatted dates.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kenjpete
kenjpete

ASKER

Ok a combination of things worked.....first here is the code:

PHP:
$release_date=strtotime($_POST['release_date']);
$date=date('c', $release_date);

SQL:
$sql = "INSERT INTO books(title, description, price, release_date, quantity, active) VALUES ('$title','$description','$price','$date','$quantity','$active');";

Ray that article was spot on....using the date('c') function properly formatted the date, and Brian you were correct, I need to wrap the $date in single quotes in my SQL statement.
I might look at it just a little differently (pidgin code):

PHP:
$release_date=strtotime($_POST['release_date']);
if (!$release_date)
{
    trigger_error('Invalid Date: ' . $_POST['release_date'], E_USER_WARNING); // TEST FOR FAILURE!
}
else
{
    $date=date('c', $release_date);
}