简体   繁体   English

使用PHP将多个CSV上传到mysql

[英]Uploading Multiple CSV into mysql using PHP

I got this code for importing multiple csv file into database but when i tried to upload only one file is being uploaded. 我有这个代码用于将多个csv文件导入数据库,但是当我尝试上传时,只有一个文件正在上传。 I tried many things but just couldn't find a way. 我尝试了很多东西但却找不到办法。

<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;
        }       
    }
?>

You are allowing multiple files so you need to loop over these multiple file references in the $_FILES array. 您允许多个文件,因此您需要在$_FILES数组中循环遍历这些多个文件引用。

Your script was also open to SQL Injection Attack Even if you are escaping inputs, its not safe! 你的脚本也对SQL注入攻击开放即使你正在逃避输入,它也不安全! So I used a prepared and parameterised query prepared parameterized statements 所以我用一个准备好的参数化查询编写了参数化语句

Preparing the statement once and executing it multiple times is one of the ways you can leverage prepared statements to save you execution time. 准备一次语句并多次执行它是您利用预准备语句来节省执行时间的方法之一。

<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++;
            }       
        }
    }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM