将PHP中的Excel工作表上传到数据库仅提供最后一行

时间:2016-11-16 08:00:08

标签: php mysql

我尝试在Excel中将Excel工作表(csv)上传到我的数据库,但它表示成功。但是我要去mysql确认,我注意到只有excel表中的最后一行显示在mysql表中。请帮忙。我不知道还能做什么。

<?php
include ("base.php");

if (isset($_POST['submit'])) {

    //inserting into db
    //getting the file and inserting it in db
    $file = $_FILES['file']['tmp_name'];
    $handle = fopen($file, "r");
    $tot = 0;
    while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

        for ($c=0; $c < 1; $c++) {

            //only run if the first column if not equal to name
            if ($data[0] != 'name') {

                $name = mysqli_real_escape_string($con, $data[0]);
                $reg_no = mysqli_real_escape_string($con, $data[1]);
                $lab = mysqli_real_escape_string($con, $data[2]);
                $test = mysqli_real_escape_string($con, $data[3]);
                $exam = mysqli_real_escape_string($con, $data[4]);
                $total = mysqli_real_escape_string($con, $data[5]); 
                $grade = mysqli_real_escape_string($con, $data[6]);
                $remark = mysqli_real_escape_string($con, $data[7]);

                //inserting into db
                $sql = "INSERT INTO imt303 (name, reg_no, lab, test, exam, total, grade, remark) 
                        VALUES ('$name', '$reg_no', '$lab', '$test', '$exam', '$total', '$grade', '$remark')"; 
            }

        //incrementing    
        $tot++;
        }
    }

    if (mysqli_query($con, $sql)) {

        echo '<script type="text/javascript">alert("Uploaded Successfully!");</script>';
    } else {

        echo '<script type="text/javascript">alert("There is a problem uploading file!");</script>';
    }
}

?>

<html>

<form method="POST" action="test.php" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" name="submit" value="Submit"> 
</form>

</html>

1 个答案:

答案 0 :(得分:0)

您正在重写$ sql值。 $ sql值是分配给最后一个查询的最后一个值。你可以在while循环中包含查询(不是recomanded),或者你创建一个$ sql []数组,你迭代并插入或者我要做的最后一个表单,创建一个带有插入值的主$ sql并在循环中连接值制作一个大插页。