Jump to content

Convert form inputs for date into a mysql date format


MTWKfal

Recommended Posts

I have tried a large number of "solutions" to  this but everytime I use them I see 0000-00-00 in my date field instead of  the date even though I echoed and can see that the date looks correct.

 

Here's where I'm at:

I have a drop down for the month (1-12) and date fields (1-31) as well as a text input field for the year.  Using the POST array, I  have combined them into the xxxx-xx-xx format that I am using in my field as a date field in mysql. 

 

<code>

$date_value =$_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];

echo $date_value;

</code>

 

This outputs 2012-5-7 in my test echo but 0000-00-00 in the database.

 

I have tried unsuccessfully to use in a numberof suggested versions of:

strtotime()

mktime

 

Any help would be extremely appreciated.

I am aware that I need to validate this data and insure  that it is a valid date. That I'm okay with. I would like some help on getting it into the database.

 

 

 

 

Link to comment
Share on other sites

You can either convert it to a UNIX timestamp with PHP and then convert it into MySQL's format with MySQL, or just convert it into MySQL format all in one go.

$year  = $_POST['year'];
$month = $_POST['month'];
$day   = $_POST['day'];

$timestamp = strtotime($year.'-'.$month.'-'.$day);

$sql = "INSERT INTO table (date) VALUES (FROM_UNIXTIME($timestamp))";

 

$year  = $_POST['year'];
$month = $_POST['month'];
$day   = $_POST['day'];

$sql = "INSERT INTO table (date) VALUES (STR_TO_DATE('$year-$month-$day', '%Y-%m-%d'))";

Link to comment
Share on other sites

Thank you thank you thank you. That works.

Good deeds do not go unpunished so I  have a second question.

 

Would that work for time also. I have a field that is TIME.

People would enter something like 1:30 into the form.

 

 

 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.