我获得了用于将多个csv文件导入数据库的代码,但是当我尝试上传时,仅上传了一个文件。我尝试了很多事情,但找不到方法。
<form name="import" method="post" enctype="multipart/form-data">
<div class="col-lg-6 col-xs-6">
<input type="file" name="file[]" multiple /><br />
</div><!-- ./col -->
<input type="submit" class="form-control"name="submit" value="Submit" />
</form>
<?php
include ("connection.php");
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
fgetcsv($handle);
while(($filesop = fgetcsv($handle, 10000, ",")) !== false)
{
$ITEM_CODE_MX =$filesop[1];
$addqtyqry = mysqli_query($link,"INSERT INTO salesreceiptlinedetail
(ItemRef_FullName)
VALUES ('".$ITEM_CODE_MX."')");
$c = $c + 1;
}
}
?>
答案 0 :(得分:0)
您允许多个文件,因此需要在$_FILES
数组中循环访问这些多个文件引用。
您的脚本也向SQL Injection Attack开放 甚至if you are escaping inputs, its not safe! 因此,我使用了预先准备好的参数化查询prepared parameterized statements
一次准备语句并多次执行是利用准备好的语句节省执行时间的方法之一。
<form name="import" method="post" enctype="multipart/form-data">
<div class="col-lg-6 col-xs-6">
<input type="file" name="file[]" multiple /><br />
</div><!-- ./col -->
<input type="submit" class="form-control"name="submit" value="Submit" />
</form>
<?php
include ("connection.php");
if(isset($_POST["submit"])) {
//prepare the insert before you start looping
$ins_stmt = $link->prepare('INSERT INTO salesreceiptlinedetail
(ItemRef_FullName) VALUES(?)';
// check the prepare worked and the the query is correctly coded
if (FALSE === $ins_stmt) {
echo 'Error: '.$link->error;
exit;
}
foreach ( $_FILES['file']['tmp_name'] as $file ) {
$handle = fopen($file, "r");
$c = 0;
// read and ignore headers
fgetcsv($handle);
while(($filesop = fgetcsv($handle, 10000, ",")) !== false) {
$ins_stmt->bind_param('s', $filesop[1]);
$ins_stmt->execute();
$c++;
}
}
}
?>