2014-01-27 39 views
1

我想使用cakephp將數據從csv導入到mysql表。
當我運行該函數時,它將空值放入我的表中,我相信它是我的$ data數組的格式,這裏是我的代碼。使用cakephp將數據從csv導入到mysql

var $name = 'ScWidths'; 
    var $scaffold; 

/* 
    function import() { 
      $messages = $this->ScWidth->import('scwidths.csv'); 
      $this->set('messages', $messages); 
    } 

*/

function import() { 
      // to avoid having to tweak the contents of 
      // $data you should use your db field name as the heading name 
      // eg: Post.id, Post.title, Post.description 


      // set the filename to read CSV from 
      $filename = TMP . 'uploads' . DS . 'Sc_widths' . DS . 'scwidths.csv'; 


      // open the file 
      $handle = fopen($filename, "r"); 


      // read the 1st row as headings 
      $header = fgetcsv($handle); 


      // create a message container 
      $return = array(
        'messages' => array(), 
        'errors' => array(), 
      ); 


      // read each data row in the file 
      $i = 0; 
      while (($row = fgetcsv($handle)) !== FALSE) { 
        $i++; 
        $data = array(); 


        // for each header field 
        foreach ($header as $k=>$head) { 

          // get the data field from Model.field 
          if (strpos($head,'.')!==false) { 

            $h = explode('.',$head); 
       #die(debug($h)); 
            $data[$h[0]][$h[1]]=isset($row[$k]) ? $row[$k] : ''; 

          } 

          // get the data field from field 
          else { 
            $data['ScWidth'][$head]=isset($row[$k]) ? $row[$k]: ''; 
          } 

        } 



    $data['ScWidth']['section_id']=1; 
    $this->ScWidth->create(); 





        // success or not :/ 
        if ($this->ScWidth->save($data)) { 
      echo "success"; 

        } 
      } 


      // close the file 
      fclose($handle); 


      // return the messages 
      //return $return; 


    } 

我調試點返回數組

array(
    'ScWidths' => array(
     'chainage' => '0' 

     ), 
     'Left_side' => '3.7' 

     ), 
     'right_side' => '3.7' 

     ), 
     'section_id' => (int) 1 
    ) 
) 

錯誤日誌即時得到,

什麼...

我相信我的下一個錯誤是我的保存方法。

這裏是我的數據文件,只是incase。

ScWidths.chainage,ScWidths.Left_side,ScWidths.right_side 
0,3.7,3.7 
10,3.7,3.7 
20,3.7,3.7 
30,3.7,3.7 
40,3.7,3.7 
50,3.7,3.7 
60,3.7,3.7 
70,3.7,3.7 
80,3.7,3.7 

糾正我的代碼,這是工作100%,如果有人需要一個例子:)

+0

你能請分配採樣xls文件? – Anubhav

回答

2

這裏這條線路是在糾正

$data[$h[0]][$h[1]][$h[2]]=(isset($row[$k])) ? $row[$k] : '';

$h[2]將永遠不會被定義。

當爆炸頭名狀 「sc_widths.chainage」(用 '' 作爲分隔符),你會得到

  • $h[0] = 'sc_widths';
  • $h[1] = 'chainage';

你將永遠不會得到$ h [2]與這些數據。

所以修復您的具體問題是砸$ H [2]是這樣的:

$data[$h[0]][$h[1]]=(isset($row[$k])) ? $row[$k] : '';

+0

omgosh ... THanks ,,,,,,,哇,-... ive改變了它,但奇怪的是它仍然給我零作爲我的表中的條目:O,剛剛更新了我的最新代碼的條目。 – MrD

+0

您的表名和字段名必須與您在數據庫中的內容匹配。例如'Left_side'有一個上部「L」。這可以嗎?所以請確保您的模型和數據正確鏈接到您的實際表格。 –

+0

是的,L應該是這樣的,我會仔細檢查一下其他的一切。一切都正是它應該是......我試圖使用不同的保存方法,並沒有在那裏工作,嗯,這是非常奇怪的。 – MrD

1
Here is working code. 

function import($filename) { 
     $i = null; $error = null; 
     $filename = $_SERVER['DOCUMENT_ROOT'] . '/dashboards/app/webroot/files/' .$filename; 
     $handle = fopen($filename, "r"); 
     $header = fgetcsv($handle); 
     $return = array(
      //'messages' => array(), 
      'errors' => array(), 
     ); 

     while (($row = fgetcsv($handle)) !== FALSE) { 
      $i++; 
      $data = array(); 

      foreach ($header as $k=>$head) { 
       if (strpos($head,'.')!==false) { 
        $h = explode('.',$head); 
        $data[$h[0]][$h[1]]=(isset($row[$k])) ? $row[$k] : ''; 

       } 
       else 
       { 

      $data['Project'][$head]=(isset($row[$k])) ? $row[$k] : ''; 
       } 

      } 


       $id = isset($row[0]) ? $row[0] : 0; 
       if (!empty($id)) {  
       $projects = $this->find('all', array('conditions' => array('Project.item_sku' =>$id))); 
       if (!empty($projects)){ 
       $apiConfig = (isset($projects[0]['Project']) && is_array($projects[0]['Project'])) ? ($projects[0]['Project']) : array(); 
       //debug($apiConfig); 
       //debug($data['Project']); 
       $data['Project'] = array_merge($apiConfig,$data['Project']); 
       }else { 

       $this->id = $id; 

       } 

       } 
       else { 
       $this->create(); 
      } 
      //debug($data); 

      $this->set($data); 
      if (!$this->validates()) { 
       //$this->_flash('warning'); 
       //$errors = $this->ModelName->invalidFields(); 
       if(!empty($this->validationErrors['item_name'])){ 
       $limit = $this->validationErrors['item_name'] ;    
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else if(!empty($this->validationErrors['brand_name'])){ 
        $limit = $this->validationErrors['brand_name'] ;     
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else if(!empty($this->validationErrors['manufacturer'])){ 
        $limit = $this->validationErrors['manufacturer'] ;    
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else if(!empty($this->validationErrors['feed_product_type'])){ 
        $limit = $this->validationErrors['feed_product_type'] ;    
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else if(!empty($this->validationErrors['product_description'])){ 
        $limit = $this->validationErrors['product_description'] ;    
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else if(!empty($this->validationErrors['bullet_point1'])){ 
        $limit = $this->validationErrors['bullet_point1'] ;    
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else if(!empty($this->validationErrors['bullet_point2'])){ 
        $limit = $this->validationErrors['bullet_point2'] ;    
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else if(!empty($this->validationErrors['bullet_point3'])){ 
        $limit = $this->validationErrors['bullet_point3'] ;    
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else if(!empty($this->validationErrors['bullet_point4'])){ 
        $limit = $this->validationErrors['bullet_point4'] ;    
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else if(!empty($this->validationErrors['bullet_point5'])){ 
        $limit = $this->validationErrors['bullet_point5'] ;    
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else if(!empty($this->validationErrors['quantity'])){ 
        $limit = $this->validationErrors['quantity'] ;    
       $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); 
       } 
       else { echo "Welcome Amit....";} 

      } 

      if ($this->saveAll($data)) { 
       // $return['errors'][] = __(sprintf("Listing Skip Row %d failed to save.",$i), true); 
      }/*else { 

       $return['messages'][] = __(sprintf('Listing for Row %d was saved.',$i), true); 
      }*/ 
     } 

     fclose($handle);   
     return $return; 

    }