2014-01-25 44 views
0

我想解析一個小的CSV文件並將記錄插入到MySQL中。CSV - 不上載所有記錄

我遇到的問題是,CSV有150行,但只有2似乎插入:

 $file = new SplFileObject($uploadedFile); 

     $separator = ','; 
     $rowCounter = 1; 
     $errors = array(); 

     $fh = fopen($uploadedFile, 'r'); 
     if(!$fh) die('File no good!'); 

     // Get headings 
     $headings = fgetcsv($fh, 0, ','); 
     $num_cols = count($headings); 
     $num_rows = 1; 

     // Read the file as csv 
     while ($row = $file->fgetcsv($separator)) { 

      //missed product if num columns in this row not the same as num headings 
      if (count($row) != $num_cols) { 
       $row = array_pad($row, $num_cols, NULL); 
      } 

      for ($i=0; $i<count($headings); $i++) { 
       $raw_prod[$headings[$i]] = $row[$i]; 
      } 

      $item = new Item(); 
      $item->name = $raw_prod['NAME']; 
      $item->age = $raw_prod['AGE']; 
      $item->location = $raw_prod['LOCATION']; 
      $item->save(); 
     } 

如果我var_dump($item)我得到的所有150條記錄,但只有2曾經得到的插入。

我只是不明白爲什麼會這樣

感謝

+0

臨近結束時,您使用的是'$ data_row '數組,但我看不到定義或填充的位置。 –

+0

更新爲使用'$ raw_prod' – user789122

回答

0

此行

while ($row = $file->fgetcsv($separator)) { 

應該

while (($row = $file->fgetcsv($separator)) !== false) { 
+0

添加該檢查仍會插入2行,但會殺死我的頁面 – user789122