从第2行开始将.csv文件插入mysql数据库

时间:2014-06-19 09:40:38

标签: php mysql csv

我正在尝试上传.csv文件,其中用户可以浏览文件并上传文件并将数据插入到mysql db中。但是.csv文件的第1行插入到表中,因为该行包含列名分别是我的代码

<?php
//Connect to Database

if (isset($_POST['submit'])) {
    if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
        echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
    }

    //Import uploaded file to Database
    $handle = fopen($_FILES['filename']['tmp_name'], "r");
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        //db connection
        $import="INSERT into csv(id,user,phone) values('$data[0]','$data[1]','$data[2]')";
        mysql_query($import) or die(mysql_error());
    }

    fclose($handle);
    print "Import done";
}else {
    echo "sorry";
}
?>   

我的表格结构

CREATE TABLE `csv` (
id int(10) NOT NULL DEFAULT '0',
user varchar(10) NOT NULL,
phone int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1

1 个答案:

答案 0 :(得分:1)

$handle = fopen($_FILES['filename']['tmp_name'], "r");
fgetcsv($handle, 1000, ",");  // pop the headers
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) ...

在开始循环其余部分之前,只需致电fgetcsv

事实上,我通常使用这个成语:

$fh = fopen(...);
$headers = fgetcsv($fh);

while ($row = fgetcsv($fh)) {
    $row = array_combine($headers, $row);
    echo $row['columnname'];
}

它允许您按名称而不是索引访问列。