如何用PHP将日期传递给MySQL

时间:2013-11-20 10:05:49

标签: php mysql

我有一个带有此部分的createAdmin.php表单:

<p>Date of Birth:&nbsp; <input maxlength="4" size="4" type = "text" name = "year" value = "" placeholder="YYYY" > -
                 &nbsp; <input maxlength="2" size="2" type = "text" name = "month" value = "" placeholder="MM" > -
                 &nbsp; <input maxlength="2" size="2" type = "text" name = "day" value = "" placeholder="DD" >

缓存这些值:

$year = (int) $_POST['year'];
$month = (int) $_POST['month'];
$day = (int) $_POST['day'];

最后传递给mySQL:

$formBirth = "{$year}{$month}{$day}";
$createAdmin = mysqli_query($db, "INSERT INTO admins (username, hashed_pwd, power, email, name, birth) VALUES (
'{$username}', '{$password}', '{$power}', '{$email}', '{$realName}', STR_TO_DATE('$formBirth', '%Y%m%d'))");

这种方法显然不起作用。有什么想法吗?

4 个答案:

答案 0 :(得分:1)

尝试将所有这些变为变量并使用

$date = $year.'-'.$month.'-'.$day;

答案 1 :(得分:0)

尝试在此处添加/

$formBirth = $year."/".$month."/".$day;

或者:

$formBirth = "{$year}/{$month}/{$day}";

或使用-

$formBirth = $year."-".$month."-".$day;

或者:

$formBirth = "{$year}-{$month}-{$day}";

请参阅Demo

答案 2 :(得分:0)

$formBirth = "{$year}-{$month}-{$day}";

答案 3 :(得分:0)

Date of birth<input type="date"  name="date" />(html 5)
<?php
$formBirth = $_POST['date'];
$createAdmin = mysqli_query($db, "INSERT INTO admins (username, hashed_pwd, power, email, name, birth) VALUES (
'{$username}', '{$password}', '{$power}', '{$email}', '{$realName}',{$formBirth})");

?>

OR use this
<?php 
$year =$_POST['year'];
$month =$_POST['month'];
$day =$_POST['day'];
$formBirth=$year."/".$month."/".$day;

?>