通过PHP将CSV导入MySQL

时间:2014-03-13 08:01:52

标签: php mysql sql csv

我想导入一个看起来像。:

的CSV文件
"Berichtname:"  "Test2" 

"Berichtstatus:"    "Die Berichterstellung ist erfolgreich beendet."    


"Name"  "Wert"  "Einheit"   "Objektbeschreibung"    "Zustand"   "Typ"   "L/S"   "Parameter" "Min"   "Max"   
"B4'TAA3'MtEF'AFGl05'CumEg" "99,7"  "kWh"   "kum. Wirkenergie"  ""  "Real Zahl" "5/3"   "PrVal" "-340282200000000000000000000000000000000.00"   "340282200000000000000000000000000000000.00"    
"B4'TZ03'MtrEl'MtrEl05'Pwr" "10"    "kW"    "Wirkleistung"  "S" "Real Zahl" "5/3"   "PrVal" "-340282200000000000000000000000000000000.00"   "340282200000000000000000000000000000000.00"

我试图导入文件,但没有任何成功..我想要的是跳过前6行,只添加最后两行。

有人可以帮助我吗?

<?php 

//database connection details
$connect = mysql_connect('XXXXXXXXXXX','XXXXXXXXXXXX','XXXXXXXXXXX');

if (!$connect) {
 die('Could not connect to MySQL: ' . mysql_error());
 }

//your database name
$cid =mysql_select_db('XXXXXXXXXXX',$connect);

// path where your CSV file is located
define('CSV_PATH','');

// Name of your CSV file
$csv_file = CSV_PATH . "export.csv";

if (($getfile = fopen($csv_file, "r")) !== FALSE) { 
        $data = fgetcsv($getfile, 1000, ",");
        while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
         $num = count($data); 
         for ($c=0; $c < $num; $c++) {
             $result = $data; 
             $str = implode(",", $result); 
             $slice = explode(",", $str);
             $col1 = $slice[0]; 
             $col2 = $slice[1];
             $col3 = $slice[2]; 

// SQL Query to insert data into DataBase

$query = "INSERT INTO daten(sensor,wert)
VALUES('".$col1."','".$col2."')";

$s=mysql_query($query, $connect ); 
     }
   } 
  }

echo "File data successfully imported to database!!"; 
mysql_close($connect); 
?>

1 个答案:

答案 0 :(得分:0)