将csv导入mysql

时间:2012-11-15 23:05:38

标签: php mysql csv import

我在这个问题上看到了几个问题,但没有一个能够帮助我。

这是我正在使用的脚本。

<?php  

//connect to the database 
$connect = mysql_connect("localhost","username","password"); 
mysql_select_db("mydatabase",$connect); //select the table 
// 

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; 

} 

?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
<title>Import a CSV File with PHP & MySQL</title> 
</head> 

<body> 

<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?> 

<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> 
  Choose your file: <br /> 
  <input name="csv" type="file" id="csv" /> 
  <input type="submit" name="Submit" value="Submit" /> 
</form> 

</body> 
</html> 

它可以正常工作,但您无法定义标题行。

我想要做的是,如果可能的话是从第一行获取每一列并使用它来定义项目将放在数据库中的列。

所以我想将$data[0]拆分成csv文件中定义的每一列。我尝试过使用LOAD DATA LOCAL INFILE,但由于某些原因它不适用于我。

1 个答案:

答案 0 :(得分:2)

您可能想首先抓住第一行并从中创建列列表字符串:

<?php

if ($_FILES[csv][size] > 0) { 

    //get the csv file 
    $file = $_FILES[csv][tmp_name]; 
    $handle = fopen($file,"r"); 

    // get headers
    $columns = fgetcsv($handle,1000,",","'");
    $column_list = implode(",",$columns);

    //loop through the csv file and insert into database 
    while ($data = fgetcsv($handle,1000,",","'")) { 
        if ($data[0]) { 
        for ($i=0;$i<count($columns);$i++){
            $data[$i]="'".mysql_real_escape_string($data[$i])."'";
        }
        $values = implode(",",$data);

        $query = "INSERT INTO contacts ($column_list) ($values)";

        mysql_query($query);

        } 
    }

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

}