我可以从我的csv文件导入数据,但CSV文件中的日期不会保存。这是CSV文件中的数据。这两个日期没有保存。
计划1项目1 asdasd学术部门1/20/2018 1/21/2018高
PHP代码:
<?php
require_once "connect.php";
if ($_FILES['file']['name']) {
$filename = explode(".", $_FILES['file']['name']);
if ($filename[1] == "csv") {
$handle = fopen( $_FILES['file']['tmp_name'], "r" );
while ($data = fgetcsv($handle)) {
$project_id = mt_rand();
$item1 = mysqli_real_escape_string($conn, $data[0]);
$item2 = mysqli_real_escape_string($conn, $data[1]);
$item3 = mysqli_real_escape_string($conn, $data[2]);
$item4 = mysqli_real_escape_string($conn, $data[3]);
$item5 = mysqli_real_escape_string($conn, $data[4]);
$item6 = mysqli_real_escape_string($conn, $data[5]);
$item7 = mysqli_real_escape_string($conn, $data[6]);
$sql = "INSERT INTO project (project_id ,project_name, program, description, department, start_date, end_date, priority, status)
VALUES ('$project_id', '$item2', '$item1', '$item3', '$item4', '$item5', '$item6','$item7','Ongoing')";
mysqli_query($conn, $sql);
}
fclose($handle);
}
}
?>
答案 0 :(得分:0)
我认为格式不好。
尝试这样的事情:
$item5 = date("Y-m-d", strtotime($item5)) ; // $item5 = "2018-01-20"
之前插入表格。
答案 1 :(得分:0)
DATE
类型的字段需要格式为YYYY-mm-dd
的日期。
$item5 = date('Y-m-d', strtotime($item5));
$item6 = date('Y-m-d', strtotime($item6));
使用此代码,您可以为这两个日期设置格式YYY-mm-dd
。
完整代码:
<?php
require_once "connect.php";
if ($_FILES['file']['name']) {
$filename = explode(".", $_FILES['file']['name']);
if ($filename[1] == "csv") {
$handle = fopen($_FILES['file']['tmp_name'], "r");
while($data = fgetcsv($handle)) {
$project_id = mt_rand();
$item1 = mysqli_real_escape_string($conn, $data[0]);
$item2 = mysqli_real_escape_string($conn, $data[1]);
$item3 = mysqli_real_escape_string($conn, $data[2]);
$item4 = mysqli_real_escape_string($conn, $data[3]);
$item5 = mysqli_real_escape_string($conn, $data[4]);
$item6 = mysqli_real_escape_string($conn, $data[5]);
$item7 = mysqli_real_escape_string($conn, $data[6]);
$item5 = date('Y-m-d', strtotime($item5));
$item6 = date('Y-m-d', strtotime($item6));
$sql = "INSERT INTO project (project_id ,project_name, program, description, department, start_date, end_date, priority, status)
VALUES ('$project_id', '$item2', '$item1', '$item3', '$item4', '$item5', '$item6','$item7','Ongoing')";
mysqli_query ($conn, $sql);
}
fclose($handle);
}
}
?>
答案 2 :(得分:0)
正如已经指出的那样,您的日期格式错误。
除了其他答案,您还可以使用STR_TO_DATE()
函数直接在MySQL中转换日期:
STR_TO_DATE('$item5','%c/%e/%Y')
所以在你的例子中:
INSERT INTO project (project_id ,project_name, program, description, department, start_date, end_date, priority, status)
VALUES ('$project_id', '$item2', '$item1', '$item3', '$item4', STR_TO_DATE('$item5','%c/%e/%Y'), STR_TO_DATE('$item6','%c/%e/%Y'),'$item7','Ongoing')
有关格式说明符的详细信息,请参阅DATE_FORMAT()