停止从CSV插入第一行

时间:2014-05-22 19:13:21

标签: php mysql csv

我当前从CSV导入,我似乎无法弄清楚如何停止插入第一行。

if ($_FILES[csv][size] > 0) {
//get the csv file 
$file = $_FILES[csv][tmp_name]; 
$handle = fopen($file,"r");     
//loop through the csv file and insert into database 

do { 
    if ($data[0]) { 
        mysql_query("INSERT INTO TABLE (id,type) VALUES 
        (
        '".addslashes($data[0])."', 
        '".addslashes($data[1])."'
        )");
        } 
} 
while ($data = fgetcsv($handle,0,",",'"'));

echo "Done";
}

任何帮助都会很棒!

2 个答案:

答案 0 :(得分:3)

如果你要做的就是跳过第一个,然后放弃do并将你的循环变成常规的while,并确保在循环之前调用fgetcsv()一次。

if ($_FILES[csv][size] > 0) {
    //get the csv file 
    $file = $_FILES[csv][tmp_name]; 
    $handle = fopen($file,"r");     
    //loop through the csv file and insert into database 

    //Get some data first, and do nothing with it.
    $data = fgetcsv($handle,0,",",'"');

    while ($data = fgetcsv($handle,0,",",'"')) { 
        if ($data[0]) { 
            mysql_query("INSERT INTO TABLE (id,type) VALUES 
            (
            '".addslashes($data[0])."', 
            '".addslashes($data[1])."'
            )");
        } 
    } 

    echo "Done";
}

答案 1 :(得分:0)

在循环调用fgetcsv之前 -

if ($_FILES[csv][size] > 0) {
    //get the csv file 
    $file = $_FILES[csv][tmp_name]; 
    $handle = fopen($file,"r");
    $data = fgetcsv($handle); // this calls the first row     
    //loop through the csv file and insert into database