上传csv并将内容解析为mysql

时间:2013-04-07 13:07:15

标签: php mysql csv

我想上传一个csv文件,而不是显示列的内容。比我想给这个列分配一个mysql表和它的列来上传内容到数据库。

**CSV -> Upload (HTML Form)**

**show CSV columns like**

           | select table and show columns in select combo   
-----------------------------------------------------------
id         | dropdown with mysql tabel columns  
-----------------------------------------------------------
name       | dropdown with mysql tabel columns
-----------------------------------------------------------
address    | dropdown with mysql tabel columns

上传到mysql

我没有多少经验,我想知道: 必须先将CSV上传到服务器,还是我可以处理流程?

1 个答案:

答案 0 :(得分:0)

以下是代码:

$host="hostname"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name = "database_name"; // Database name
$tbl_name = "table_name"; // Table name

// Connect to server and select database.
$con = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

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

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

//loop through the csv file and insert into database 
//this loop ignores the first row of CSV file as they are the headers
$flag = true;
do {           
        if ($data[0]) { 
            $count = $count + 1; 
            if($flag)
            {
                $flag=false;
                continue;
            }
            else
            {           
                mysql_query("INSERT INTO $tbl_name (email,password) VALUES 
                    ( 
                        '".addslashes($data[0])."', //CSV equivalent of id
                        '".addslashes($data[1])."', //CSV equivalent of name
                        '".addslashes($data[2])."', //CSV equivalent of address
                    ) 
                ");
        }
    } 
} while ($data = fgetcsv($handle,10000,",","'")); 

如果这对你有所帮助,请进行upvote并标记为答案。