我的代码运行良好。但有一个小问题,比如我的 csv 文件列号随着时间不断变化。并且不可能每次都更改我的代码中的索引号。所以我找到了一个解决方案,比如我可以按列名而不是数字读取 csv。如何根据代表列号的列名获取 csv 文件的记录? 提前致谢。
if ($_POST["upload"] == "freight") {
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
$branch=$_POST["freight"];
while (($filesop = fgetcsv($handle, 3000000, ",")) !== false) {
$invoice_number = $filesop[3];
$freaight3 = $filesop[12];
$freaight2 = substr($freaight3, 0, -2);
if($freaight2=="")
{
$freaight2=0;
}
$with_tax = $filesop[10];
$with_tax2 = substr($with_tax, 0, -2);
$Invoice_Number = $branch."_" .$invoice_number;
$update_freaight = "UPDATE xyz SET `Total_Freight`=" . $freaight2 . ",`Value_With_Tax`='" . $with_tax2 . "' where `Invoice_Number`='" . $Invoice_Number . "'";
// echo $update_freaight;
$update = mysqli_query($con, $update_freaight);
}
if ($update) {
$massage = "You database has imported successfully. You have inserted " . $c . " recoreds";
} else {
$massage = "Sorry! There is some problem.";
}
}
最佳答案
最终通过 11 个小时的搜索,我自己完成了。这不是正确的方法,但在逻辑上是正确的!
$file = $_FILES['file']['tmp_name'];
$csv = array_map("str_getcsv", file("$file",FILE_SKIP_EMPTY_LINES));
$keys = array_shift($csv);
for($i=0;$i<=sizeof($keys);$i++)
{
$name=$keys[$i];
if($name=="xyz") {
$xyz = $i;
continue;
}
else if($name=="abc") {
$abc = $i;
continue;
}
else if($name=="tax") {
$tax = $i;
continue;
}
}
if ($_POST["upload"] == "freight") {
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
$branch=$_POST["freight"];
while (($filesop = fgetcsv($handle, 3000000, ",")) !== false) {
$xyz = $filesop[$xyz];
$abc = $filesop[$abc];
$freaight2 = substr($abc, 0, -2);
if($freaight2=="")
{
$freaight2=0;
}
$with_tax = $filesop[$tax];
$with_tax2 = substr($with_tax, 0, -2);
$Invoice_Number = $branch."_" .$invoice_number;
$update_freaight = "UPDATE xyz SET `Total_Freight`=" . $freaight2 . ",`Value_With_Tax`='" . $with_tax2 . "' where `Invoice_Number`='" . $Invoice_Number . "'";
// echo $update_freaight;
$update = mysqli_query($con, $update_freaight);
}
if ($update) {
$massage = "You database has imported successfully. You have inserted " . $c . " recoreds";
} else {
$massage = "Sorry! There is some problem.";
}
}
关于php - 如何使用 PHP 将列名而不是索引号的 CSV/excel 文件上传到 MySql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35836998/