2016-03-28 87 views
0

您可以帮我介绍为了从HTML表单插入日期到数据库所需的PHP代码。下面是日期格式:从HTML到PHP脚本插入/获取日期到MYSQL数据库

date format

HTML表单:

<form action="insertleave.php" method="post"> 
     <label>Date Filed:</label> 
     <input type="date" name="datefiled"> 

     <label>Date of Leave:</label> 
     <input type="date" name="leavedate"> 
</form> 

PHP:在

if($_POST){ 
    $config = parse_ini_file("phpconfig.ini"); 
    $conn = mysqli_connect($config['host'], $config['username'], $config['password'], $config['dbname']); 

    if (!$conn){ 
     die("Connection failed: " . mysqli_connect_error()); 
    } 

    -----CAN YOU PROVIDE ME WHAT THE CODE IS NEEDED HERE ----- 


    if (mysqli_query($conn, $sql)) { 
     echo "OK!"; 
    } else { 
     echo "Error: " . $sql . "<br>" . mysqli_error($conn); 
    } 
} 
mysqli_close($conn); 
+0

当然,为什么不.. –

回答

1

你必须格式化为您定义的时间/创建字段数据库。因为您选择DATE所以格式为ID Y-m-d。用您的实际表名替换table

您的查询是:

$datefiled = date("Y-m-d", strtotime($_POST['datefiled'])); 
$leavedate = date("Y-m-d", strtotime($_POST['leavedate'])); 
$sql = "INSERT INTO table (DateFiled, LeaveDate) VALUES('$datefiled', '$leavedate')"; 
+0

感谢这么多的人! :) –

+0

永远不会忘记接受答案。 –

+1

好吧,我会给你一个upvote,即使OP不会,但通常关于预备陈述的警告仍然适用。 – Strawberry

0

您的查询会是这样

$sql = "INSERT INTO XXX (DateFiled,LeaveDate) VALUES('".date("Y-m-d", strtotime($_POST['datefiled']))."','".date("Y-m-d", strtotime($_POST['leavedate']))."')"; 

XXX是你的表的名称。它应该帮助你。

+1

''DateFiled','LeaveDate'这可能会产生错误,导致你使用'''。 –

+0

是的,你是正确的,删除​​它。 –

0

在数据库中,日期是以Y-m-d格式插入的,因此您必须在将日期格式插入到数据库之前转换日期格式。

要转换日期格式,你必须做这样的

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

东西之后,在你的插入查询简单地使用变量,它会被插入sucesfully。

注意:在数据库中使用数据字段作为日期,因为它可以平滑您日后工作中的许多内容,如显示日期,显示no。天离开日期 两者之间等