doudeng2057 2016-08-04 05:38
浏览 41

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

my controller looks:

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

        } 

My model looks:

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

my csv file looks: enter image description here

My database table looks: enter image description here

Its works fine.

My requirement is, I want to update data from uploaded csv file. And I have to upload same csv file with updated data again. On that upload, if the csv data is already exists in table, I need to update that data and I need to insert into the table if their is any new record in updated csv file that uploaded.

what all modification should I done? Is there any other better way to make it possible?

  • 写回答

1条回答 默认 最新

  • doujia9833 2016-08-04 06:07
    关注
                    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作