简体   繁体   English

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

[英]Each time uploading csv file, how to update the database table content using 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: 我的csv文件看起来如下: 在此处输入图片说明

My database table looks: 我的数据库表如下所示: 在此处输入图片说明

Its works fine. 它的作品很好。

My requirement is, I want to update data from uploaded csv file. 我的要求是,我想从上传的csv文件更新数据。 And I have to upload same csv file with updated data again. 而且我必须再次上传具有更新数据的同一csv文件。 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. 在该上载中,如果表中已经存在csv数据,则我需要更新该数据,并且如果它们是上载的已更新csv文件中的任何新记录,则需要插入该表中。

what all modification should I done? 我应该怎么做所有修改? Is there any other better way to make it possible? 还有其他更好的方法使之成为可能吗?

                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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM