如何在导入数据库表时限制csv的第一行

时间:2013-04-15 09:37:20

标签: php

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 contacts (contact_first, contact_last, contact_email) VALUES 
                ( 
                    '".addslashes($data[0])."', 
                    '".addslashes($data[1])."', 
                    '".addslashes($data[2])."' 
                ) 
            "); 
        } 
    } while ($data = fgetcsv($handle,1000,",","'")); 
    // 

    //redirect 
    header('Location: import.php?success=1'); die; 

} 

?> 
  

在上面的导入过程中,csv文件中的第一行也插入到数据库中,任何人都可以帮助我在很快插入HElp时限制第一行

2 个答案:

答案 0 :(得分:1)

$lineNr = 1;
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] && $lineNr!=1) { 
            mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES 
                ( 
                    '".addslashes($data[0])."', 
                    '".addslashes($data[1])."', 
                    '".addslashes($data[2])."' 
                ) 
            "); 
            $lineNr++;
        } 
    } while ($data = fgetcsv($handle,1000,",","'")); 
    // 

    //redirect 
    header('Location: import.php?success=1'); die; 

} 

答案 1 :(得分:0)

使用

fgetcsv($handle);
if ( $data = fgetcsv($handle,1000,",","'") )

之前

do{ ...

不要忘记用以下文件关闭文件:

fclose( $handle );

在重定向之前。