PHP日期不会插入Mysql

时间:2016-01-06 19:26:42

标签: php mysql date

我有一个HTML表单,有~30个变量通过php插入到mysql中。除日期外,所有其他变量都正确插入。我已经看过这里和其他地方发布的许多其他问题,但仍然空洞。

最初我只是在HTML表单(年,月,日)上设置了3个输入,如下所示:

     <span class="form-sub-label-container" style="vertical-align: top">
        <input class="form-textbox" id="year_6" name="lengthOf[0]" type="date" value="" />
        <span class="date-separate"> &nbsp;- </span>
        <label class="form-sub-label" for="year_6" id="sublabel_year" style="min-height: 13px;"> Start Date </label>
      </span>

     <span class="form-sub-label-container" style="vertical-align: top">
        <input class="form-textbox" id="month_6" name="lengthOf[1]" type="date" size="2" maxlength="2" value="" />
        <span class="date-separate"> &nbsp;- </span>
        <label class="form-sub-label" for="month_6" id="sublabel_month" style="min-height: 13px;"> Month </label>
      </span>

     <span class="form-sub-label-container" style="vertical-align: top">
        <input class="form-textbox" id="day_6" name="lengthOf[2]" type="date" size="2" maxlength="2" value="" />
        <label class="form-sub-label" for="day_6" id="sublabel_day" style="min-height: 13px;"> Day </label>
      </span>

这部分的php是:

$LengthOfService = $_POST['lengthOf'][0]."-".$_POST['lengthOf'][1]."-".$_POST['lengthOf'][2];

print_r($LengthOfService)会显示格式正确的日期yyyy-mm-dd,但是在保存日期的列中(它是DATE类型),它显示的是。

SOOOOO,然后我决定尝试将HTML表单上的输入类型更改为日期,因此只有1个POST变量可以加载而不是3:

          <span class="form-sub-label-container" style="vertical-align: top">
            <input class="form-textbox" id="year_6" name="lengthOf" type="date" value="01/01/2000" />
            <label class="form-sub-label" for="year_6" id="sublabel_year" style="min-height: 13px;"> Start Date </label>
          </span>

所以现在php只是:

$LengthOfService = $_POST['lengthOf'];

那仍然是一个没有火,所以继续保持阅读,并决定去尝试格式化它,即使它似乎已经正确格式化。

$LenthOfService = date("Y-m-d", strtotime($_POST['lengthOf']));

仍然在mysql专栏中显示,所有print_r($LengthOfService)仍然生成正确的格式......

仅供参考,这是我插入mysql的方式:

$insert = "INSERT INTO table (ColumnNames) VALUES ('$Values')";

mysql_query($insert)
   or die (mysql_error());

希望我已经为某些人提供了足够的信息,以便能够分辨出我做错了什么或者我可以尝试的任何其他步骤。我也没有收到任何错误。

1 个答案:

答案 0 :(得分:0)

我测试过:

$LenthOfService = date("Y-m-d", strtotime($_POST['lengthOf']));
$insert = "INSERT INTO table (ColumnNames) VALUES ('$LenthOfService')";
echo $insert;

我得到了:

  

INSERT INTO table(ColumnNames)VALUES(&#39; 2016-01-06&#39;)

我建议您检查并确保没有传递NULL,进行调试,打印查询,就像我上面所做的那样。