每次上传csv文件时,如何使用codeigniter更新数据库表内容?

时间:2016-08-04 05:38:18

标签: php codeigniter csv

我的控制器看起来:

 public function menu() {
        $data['menu'] = $this->AdminModel->get_menu();
        $this->load->view('admin/csvindex', $data);
    }



    public function importcsv() 
    {
        $data['menu'] = $this->AdminModel->get_menu();
        $data['error'] = '';    //initialize image upload error array to empty

        $config['upload_path'] = './assets/uploads/';
        $config['allowed_types'] = 'csv';
        $config['max_size'] = '1000';

        $this->load->library('upload', $config);


        // If upload failed, display error
        if (!$this->upload->do_upload()) 
        {
            $data['error'] = $this->upload->display_errors();

            $this->load->view('csvindex', $data);
        } 
        else 
        {
            $file_data = $this->upload->data();
            $file_path =  './assets/uploads/'.$file_data['file_name'];

            if ($this->csvimport->get_array($file_path)) 
            {
                $csv_array = $this->csvimport->get_array($file_path);
                foreach ($csv_array as $row) 
                {


                    $insert_data = array(
                        'mid'=>$row['mid'],
                        'category'=>$row['category'],
                        'name'=>$row['name'],
                        'price'=>$row['price'],
                        'description'=>$row['description'],
                    );
                    $this->AdminModel->insert_csv($insert_data);
                }
                $this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
                redirect(base_url().'Admin/menu');

            } else 
                $data['error'] = "Error occured";
                $this->load->view('csvindex', $data);
            }

        } 

我的模特看起来:

public function get_menu() 
{     
    $query = $this->db->get('menu');
    if ($query->num_rows() > 0) 
    {
        return $query->result_array();
    } 
    else 
    {
        return FALSE;
    }
}



public function insert_csv($data) 
{
    $this->db->insert('menu', $data);
}

我的csv文件看起来: enter image description here

我的数据库表看起来: enter image description here

它的工作正常。

我的要求是,我想更新上传的csv文件中的数据。我必须再次使用更新的数据上传相同的csv文件。在上传中,如果csv数据已经存在于表中,我需要更新该数据,如果它们是已上载的更新csv文件中的任何新记录,我需要插入表中。

我应该做什么修改?还有其他更好的方法可以实现吗?

1 个答案:

答案 0 :(得分:0)

                Yhea, please follow below steps after upload
            1) add public variable in class just after class not in any function
                public $fields;            /** columns names retrieved after parsing */
                public $separator  =   ',';    /** separator used to explode each line */
                public $enclosure  =   '"'; 

            2) get all non exists data


            $result =   $this->parse_file_csv($path); //path to csv file
            $this->getNonExistsAdd('table_name', $result);
            $this->checkandupdate('table_name',$result,'name'); //table_name of your, assuming name is unique and haven't changed

            function parse_file_csv($p_Filepath){
            $file           =   fopen($p_Filepath, 'r');
            $this->fields   =   fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
            $keys_values        =   explode(',',$this->fields[0]);
            $content            =   array();
                    $keys           =   $this->escape_string($keys_values);
            $i=0;
                    while(($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false )
            {
                       $content[$i]['mid']=$this->escape_string($row[0]); // first column
                        $content[$i]['category']=$this->escape_string($row[1]); // second column
                        $content[$i]['name']=$this->escape_string($row[2]); // third column
                        $content[$i]['price']=$this->escape_string($row[3]); // fourth column
                        $content[$i]['description']=$this->escape_string($row[4]);// fifth column

                $i++;
                    }
                    fclose($file);
                    return $content;

            }

            function escape_string($data)
            {
                $result =   array();

                if(is_array($data)){
                    foreach($data as $row){
                        $utf_data =  mb_convert_encoding(str_replace('"', '',trim($row)), 'UTF-8', 'UTF-8');
                        $result[]   = str_ireplace('?', '', $utf_data);
                    }
                }else{
                    //return utf8_encode(str_replace('"', '',trim($data)));
                    $utf_data =  mb_convert_encoding(str_replace('"', '',trim($data)), 'UTF-8', 'UTF-8');
                    return str_ireplace('?', '', $utf_data);
                }
                return $result;
            }

        private function checkandupdate($table,$data,$where_column){

                $this->db->update_batch($table, $data, $where_column);
                return ($this->db->affected_rows()?TRUE:FALSE);
            }

    private function getNonExistsAdd($table,$data){
            $new_data = array();

            foreach ($data as $key=>$row){
                $sear_arr = array('name'=>$row['name']);
                //write the query to fetch records on name in where clause as name is unique
                // $res_data is array or row of result from database
                if(empty($res_det)){
                    $new_data[$key] = $data[$key];
                }
            }


            if(!empty($new_data)){
                $this->db->insert_batch($table, $data);
                 return ($this->db->affected_rows()>0?TRUE:FALSE);
            }
            return false;
            }


hope it clears to you