简体   繁体   中英

import csv data starting row 2 into mysql database

This is the code that i used when i import the csv data, but what should i do to make it import the data starting from 2nd row ? Since the First row is the column names itself (ID,Student Name,Subject Code,Subject Name,Unit,Grade) .

if (isset($_POST["submitgrade"])){
if ($_FILES["file"]["name"]){
    $filename = explode('.',$_FILES["file"]["name"]);
    if ($filename[1] == 'csv')
        $handle = fopen($_FILES["file"]["tmp_name"], "r");
    while ($data = fgetcsv($handle))
    {
        $item1 = mysqli_real_escape_string($con, $data[0]);
        $item2 = mysqli_real_escape_string($con, $data[1]);
        $item3 = mysqli_real_escape_string($con, $data[2]);
        $item4 = mysqli_real_escape_string($con, $data[3]);
        $item5 = mysqli_real_escape_string($con, $data[4]);
        $item6 = mysqli_real_escape_string($con, $data[5]);
        $grade = "INSERT into subj (username,name,code,title,unit,grade) values ('$item1','$item2','$item3','$item4','$item5','$item6')";
        mysqli_query($con,$grade);
    }
    fclose($handle);
    echo 'Upload Grade Success';
}}

Right before the while loop starts to iterate through the CSV file, write the statement $data = fgetcsv($handle) once. Then start the loop as it is. The loop will start from the 2nd row in the CSV file.

You can just add a counter and a variable for easy access. $startAtLine will start at line 1 in this case.

<?php
if (isset($_POST["submitgrade"])){
    if ($_FILES["file"]["name"]){

        //These two lines are added
        $startAtLine = 0;
        $counter = 0;

        $filename = explode('.',$_FILES["file"]["name"]);
        if ($filename[1] == 'csv')
            $handle = fopen($_FILES["file"]["tmp_name"], "r");
        while ($data = fgetcsv($handle))
        {
            if(++$counter<$startAtLine)
                continue;
            $item1 = mysqli_real_escape_string($con, $data[0]);
            $item2 = mysqli_real_escape_string($con, $data[1]);
            $item3 = mysqli_real_escape_string($con, $data[2]);
            $item4 = mysqli_real_escape_string($con, $data[3]);
            $item5 = mysqli_real_escape_string($con, $data[4]);
            $item6 = mysqli_real_escape_string($con, $data[5]);
            $grade = "INSERT into subj (username,name,code,title,unit,grade) values ('$item1','$item2','$item3','$item4','$item5','$item6')";
            mysqli_query($con,$grade);
        }
        fclose($handle);
        echo 'Upload Grade Success';
    }}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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