2013-04-07 88 views
0

我想上傳一個csv文件,然後顯示列的內容。比我想分配給這個列一個MySQL表和它的列上載內容到數據庫。上傳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先上傳到服務器或者我可以在流處理?

+0

'是否必須首先將CSV上傳到服務器?,是 – Ejaz 2013-04-07 13:09:35

回答

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,",","'")); 

請給予好評,並標記爲答案,如果這可以幫助你。

+0

至少感謝答覆。預計至少得到滿足。 – 2013-04-08 17:20:08