2

is it possible to insert a csv file into a table and instruct the query to always ignore the first row from the csv file. Users will be uploading files but the first row will be the column headings so I need the query to ignore the first row. My script looks like this at the moment:

<?php
include 'datalogin.php';

      move_uploaded_file($_FILES["fileCSV"]["tmp_name"],
      "quiz/" . $_FILES["fileCSV"]["name"]);

    $objCSV = fopen("quiz/".$_FILES["fileCSV"]["name"], "r");
        while (($objArr = fgetcsv($objCSV, 1000, ",")) !== FALSE) {
        $strSQL = "INSERT INTO ex_question1 ";
        $strSQL .="(id,tn,qnr,qtype,pic,question,option1,option2,option3,option4) ";
        $strSQL .="VALUES ";
        $strSQL .="('".$objArr[0]."','".$objArr[1]."','".$objArr[2]."','".$objArr[3]."','".$objArr[4]."','".$objArr[5]."','".$objArr[6]."','".$objArr[7]."','".$objArr[8]."','".$objArr[9]."') ";
        $objQuery = mysql_query($strSQL);
    }
    fclose($objCSV);

    echo "Import completed.";
?> 
1

2 Answers 2

3

Simply call fgetcsv($objCSV, 1000, ",") once before going into the loop:

 $objCSV = fopen("quiz/".$_FILES["fileCSV"]["name"], "r");
 fgetcsv($objCSV, 1000, ","); // skip first row
 while (($objArr = fgetcsv($objCSV, 1000, ",")) !== FALSE) {
    $strSQL = "INSERT INTO ex_question1 ";
    $strSQL .="(id,tn,qnr,qtype,pic,question,option1,option2,option3,option4) ";
    $strSQL .="VALUES ";
    $strSQL .="('".$objArr[0]."','".$objArr[1]."','".$objArr[2]."','".$objArr[3]."','".$objArr[4]."','".$objArr[5]."','".$objArr[6]."','".$objArr[7]."','".$objArr[8]."','".$objArr[9]."') ";
    $objQuery = mysql_query($strSQL);
}
fclose($objCSV);

NB. your code is prone to SQL injections, please escape your input variables properly or use prepared statements!

Sign up to request clarification or add additional context in comments.

Comments

2

Consider even LOAD DATA command and IGNORE option

http://dev.mysql.com/doc/refman/5.1/en/load-data.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.