在MySQL中插入jQuery Date

I have been trying to follow the example shown from this link below:

PHP mysql insert date format

This is my code sample below:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    /** Variables */
    $pdate = isset($_POST['pdate']) ? $_POST['pdate'] : '';
    $org   = mysqli_escape_string($dbcon, trim($_POST['org']));
    $city  = mysqli_escape_string($dbcon, trim($_POST['city']));
    $state = isset($_POST['state']) ? $_POST['state'] : '';
    $rio   = mysqli_escape_string($dbcon, trim($_POST['rio']));

    /** Query */
    $q = "INSERT INTO `survey` (id, pdate, org, city, state, rio,   date_created)
        VALUES (NULL, STR_TO_DATE('$pdate', '%M %d, %Y'), '$org', '$city', '$state', '$rio', NOW())";
?>

/** Changing Datepicker Value **/
jQuery(document).ready(function($) {
    /** Datepicker for the Form */
    $('.selector').datepicker('option', 'dateFormat', 'yy-mm-dd');
});

$pdate = "2015-09-28"; Displays like that according to the <?php echo format ?>

There are two queries that you are using, should I use the STR_TO_TIME() or FROM UNIXTIME()

When I try and follow the 3rd step:

$dt = DateTime::createFromFormat('m/d/Y', $_POST['pdate']);
$pdate = $dt->format('Y-m-d');

After submitting the form, I get undefined variable index.

What is it that I am now missing?

You didn't post the most important information - actual error message - so I can only guess, what's wrong. These are my guesses:

  1. If undefined index is pdate, than you don't have such form control. That could be the raeson, why you have "0000-00-00" as a date in your DB

  2. You have configured Datepicker to output date in a format yy-mm-dd, but you're parsing it as %M %d, %Y in MySQL function STR_TO_DATE or m/d/Y in PHP DateTime's method createFromFormat. That doesn't make a sense.

Since yyyy-mm-dd is MySQL's native format to express a date, you don't need any conversion at all. Just save into a DB what you get from Datepicker.


So I would start with this:

  1. Check what you're getting from your form in PHP, e.g. print what's in $_POST array: var_dump($_POST)
  2. Check if there is a key pdate and contains date in format yyyy-mm-dd
  3. Save it to DB. You're done.

The easiest way to Insert Date Format is to do the following using jQuery Date Format See - http://api.jqueryui.com/datepicker/#option-dateFormat

`jQuery`

$( ".selector" ).datepicker({
    dateFormat: "yy-mm-dd"
});