2015-10-16 94 views
0

我試過代碼是如何使用php將數據從excel導出到mysql?

$source = fopen('filename.csv', 'r') or die("Problem open file"); 
    while (($data = fgetcsv($source, 1000, ",")) !== FALSE) 
    { 
     $name = $data[0]; 
     `$mobile = $data[1]; 


     mysql_query("INSERT INTO `table` (`name`,`mobile`) VALUES ('".$name."','".$mobile ."') "); 


    } 
    fclose($source); 

,但只需要最後一個記錄......

回答

0

下面是一個簡單的方法來做到這一點,使用PHP fgetcsv()mysqli()

1.連接到庫MySQLi:

$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db"); 

2.打開CSV文件:

$source = fopen('filename.csv', 'r') or die("Problem open file"); 

3.循環讀取CSV,把你的插入查詢的變量:

$query=""; 
do { 
    if ($fields[0]) { 
     $query.="INSERT INTO `table_name` (`name`, `mobile`) VALUES 
      ( 
       '".addslashes($fields[0])."', 
       '".addslashes($fields[1])."' 
      ) 
     ;"; 
    } 
} while ($fields = fgetcsv($source,1000,",","'")); 

4. EXCUTE查詢並關閉mysqli:

if($mysqli->multi_query($query)) echo "Data successfuly added"; 
$mysqli->close(); 

fgetcsv documentation

Myqli multiquery documentation

0

爲什麼不直接添加使用MySQL整個文件,而不是通過線打破它呢?喜歡的東西

LOAD DATA INFILE 'filename.csv' INTO TABLE table FIELDS TERMINATED BY ','; 

,或者如果你有需要進入特定領域的特定列,

LOAD DATA INFILE 'filename.csv' INTO TABLE table FIELDS TERMINATED BY ',' (@c1, @c2) 
set name = @c1, mobile = @c2;