使用cakephp将数据从csv导入mysql

时间:2014-01-27 07:47:58

标签: php mysql cakephp csv

我想使用cakephp将数据从csv导入到mysql表中 当我运行该函数时,它会在我的表中放置空值,我相信它是我的$ data数组的格式,这是我的代码。

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
    )
)

错误日志即时获取,

...无

我相信我的下一个错误是在我的保存方法中。

这是我的数据文件,只是包含。

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%工作:)

2 个答案:

答案 0 :(得分: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] : '';

答案 1 :(得分: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;

    }