问:我正在创建一个脚本,它将从 CSV 文件填充 mysql 表。
在一项操作中,它需要浏览 2 个 csv 文件。
第一张表用于 tbl_order,第二张表用于 tbl_order_details
我想统一 tbl_order 和 tbl_order_details 的 id,但我只是得到第一个批处理循环,后续的 id 没有插入到 tbl_order_details。
这是我的代码。
<?php
include('dbconnection.php');
if(isset($_POST['submit'])){
$csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)){
if(is_uploaded_file($_FILES['file']['tmp_name'])){
$csvFile = fopen($_FILES['file']['tmp_name'], 'r');
$csv_order_desc = fopen($_FILES['orders_desc']['tmp_name'], 'r');
while(($line = fgetcsv($csvFile)) !== FALSE){
$id = $line[0];
$status = $line[1];
$result = mysqli_query($con, "SELECT MAX(id) FROM tbl_order");
$row = mysqli_fetch_row($result);
$new_id = $row[0] + 1;
$query = "INSERT INTO tbl_order (id, status) VALUES ('$new_id', '$status')";
$result = $con->query($query);
while(($row_order_desc = fgetcsv($csv_order_desc)) !== FALSE){
$desc_id = $row_order_desc[0];
$order_item_name = $row_order_desc[1];
if($id == $desc_id){
$query = "INSERT INTO tbl_order_details (order_id, order_item_name) VALUES ('$new_id', '$order_item_name')";
$result = $con->query($query);
}
}
}
fclose($csvFile);
echo "<script>alert('Success');</script>";
}else{
$qstring = '?status=err';
}
}else{
$qstring = '?status=invalid_file';
答:您需要在每个内部循环$csv_order_desc之后将指针放回文件的开头;while否则它将停留在最后并fget_csv始终返回 false。
在您的代码中,您可以添加:
} //end while
rewind($csv_order_desc); //this is the important line to add
} //end while
fclose($csvFile);
fclose($csv_order_desc); //just close this one too