PHP,MySQL - 插入带有标题的CSV文件

时间:2014-09-29 11:51:15

标签: php mysql codeigniter csv

我的 CSV 文件包含标题和数据字段。如何通过SQL查询插入此文件并删除标题。目前我编写的代码正在运行,但是它将标题作为数据插入到DB中。

代码:

   $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 个答案:

答案 0 :(得分:2)

您可以在加载数据中使用ignore xx lines子句(此处的文档)[http://dev.mysql.com/doc/refman/5.1/en/load-data.html]跳过大约三分之一的路径:

    $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);";

这将导致输入跳过CSV的1行 - 我假设是你的标题。跳过需要很多行来获取数据本身。

答案 1 :(得分:0)

试试这个:希望这对你有用..

$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;