0

I have CSV file with header and data fields. How can I insert this via SQL query and remove headers. At the moment code that I wrote is working, but it is inserting header as a data into DB.

The code:

   $files  = directory_map('./assets/csv/');
    foreach ($files as $file) :
        $filefile = './assets/csv/' . $file;
        $q = "LOAD DATA LOCAL INFILE '$filefile' INTO TABLE person FIELDS TERMINATED BY ','  
              LINES TERMINATED BY '\n'  (personal_name, personal_lastname, 
              personal_country,personal_address,contact_email,dateadded);";
        $this->db->query($q);           
    endforeach;

2 Answers 2

2

You can use the ignore xx lines clause in load data (the doc on this)[http://dev.mysql.com/doc/refman/5.1/en/load-data.html] skip down about a third of the way:

    $q = "LOAD DATA LOCAL INFILE '$filefile' INTO TABLE person FIELDS TERMINATED BY ','  
          LINES TERMINATED BY '\n' ignore 1 lines (personal_name, personal_lastname, 
          personal_country,personal_address,contact_email,dateadded);";

This will cause the input to skip 1 line of the CSV - which I am assuming is your headers. Skip however many lines are needed to get to the data itself.

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

2 Comments

I am getting this error: Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ignore 1 lines' at line 3
Found the error - ignore 1 lines need to go after LINES TERMINATED BY '\n'. Thanks for help :)
0

Try this: Hope so this will work for you..

$c = 1;
$files  = directory_map('./assets/csv/');

        foreach ($files as $file) :
            if($c==2;) continue;
            $filefile = './assets/csv/' . $file;

            $q = "LOAD DATA LOCAL INFILE '$filefile' INTO TABLE person FIELDS TERMINATED BY ','  LINES TERMINATED BY '\n'  (personal_name, personal_lastname, personal_country,personal_address,contact_email,dateadded);";
            $this->db->query($q);           
$c++;
        endforeach;

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.