2013-02-21 103 views
0

大家好日子,建立一個csv文件的每個記錄的SQL查詢

老實說我卡住了......我想請求你的幫助。我面臨的挑戰如下所示: 1.將CSV文件上傳到服務器。 2.打開CSV文件。 3.解析它,顯示數據&爲csv文件的每個記錄構建一個sql查詢。

現在,我的問題是第3步。我得到儘可能解析和顯示錶中的數據,但我在構建查詢失敗。這裏的任何幫助表示讚賞!

這是我用來解析csv文件並顯示數據的代碼。我想請求你的幫助,我應該如何改變代碼來爲每個文件記錄創建和執行一個sql查詢。

if ($file = fopen("upload/" . $storagename , r)) { 

      echo "File opened.<br />"; 

      $firstline = fgets ($file, 4096); 
      //Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line 
      $num = strlen($firstline) - strlen(str_replace(";", "", $firstline)); 

      //save the different fields of the firstline in an array called fields 
      $fields = array(); 
      $fields = explode(";", $firstline, ($num+1)); 

      $line = array(); 
      $i = 0; 

      //CSV: one line is one record and the cells/fields are seperated by ";" 
      //so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell] 
      while ($line[$i] = fgets ($file, 4096)) { 

       $dsatz[$i] = array(); 
       $dsatz[$i] = explode(";", $line[$i], ($num+1)); 

       $i++; 
      } 

      echo "<table>"; 
      echo "<tr>"; 
      for ($k = 0; $k != ($num+1); $k++) { 
       echo "<td>" . $fields[$k] . "</td>"; 
      } 
      echo "</tr>"; 

      foreach ($dsatz as $key => $number) { 
       //new table row for every record 
       echo "Record <tr>"; 
       foreach ($number as $k => $content) { 
        //new table cell for every field of the record 
        echo "<td>" . $content . " </td>"; 
       } 
      } 

      echo "</table>"; 
     } 

謝謝你的時間。

回答

0

試試這個:

 foreach ($dsatz as $key => $number) { 

    // New code here -lighthart 
      echo "insert into table (" 
       .implode(",", $fields) 
       .") values (" 
       .implode(",",$number).");" 


      //new table row for every record 
      foreach ($number as $k => $content) { 
       //new table cell for every field of the record 
       echo "<td>" . $content . " </td>"; 
      } 
     } 
+0

我很抱歉,但我無法得到它的工作這樣呢,我會明天再試... – SubZero 2013-02-23 20:23:01

+0

得到它的工作,終於來了!非常感謝你! – SubZero 2013-03-08 15:12:34