简体   繁体   中英

Import CSV to Database on Codeigniter

I just started learning Codeigniter (CI) and I wanted to import CSV file to the database.

I followed the https://codeigniter.com/user_guide/libraries/file_uploading.html but still confused.

How to capture the file from the upload form?

On PHP native, the code is

$_FILES['file']['tmp_name']

Please help. Thank you.

How to capture the file from the upload form ?
Use $this->upload->data() when upload done

$data = $this->upload->data(); # print_r($data)
$data['file_name'];
$data['upload_path']; 

Check the documentation for more details

This can help you.

public function import_uploads()  
{   
    /*Upload csv file into uploads folder*/    
    $config['upload_path'] ='./uploads/';
    $config['allowed_types'] = 'xls|xlsx|csv';
    $this->load->library('upload', $config);
    $this->upload->initialize($config);
    if (!$this->upload->do_upload('attachment'))
    {
        echo  $this->upload->display_errors();
    }
    else
    {
        // echo "<pre>"; print_r($this->upload->data());
        $upload_data = $this->upload->data(); 
        $attachment = $upload_data['file_name'];
        $data = array( 
                'attachment' =>  $attachment,
                ); 
        /*insert Data*/    
        $this->db->insert('xls_import_upload',$data);

    }
}

You can try this:

<input type="file" class="md-input" id="file" name="file" title=""/>

Controllers:

public function import_data(){
    ini_set('memory_limit', '2048M');
    $filename=$_FILES["file"]["tmp_name"];
    if($_FILES["file"]["size"] > 0)
    {
        $file = fopen($filename, "r");
        while (($importdata = fgetcsv($file, 10000, ",")) !== FALSE)
        {

                $data = array(
                    'test1' =>$importdata[0],
                    'test2' =>$importdata[1],

                );

            $insert = $this->common->insert_data($data,$tablename = 'tablename');
        }
        fclose($file);
        $this->session->set_flashdata('success', 'Data are imported successfully..');
    }else{
        $this->session->set_flashdata('success', 'Something went wrong..');
    }
}

Models:

function insert_data($data, $tablename)
{
    if ($this->db->insert($tablename, $data)) {
        return true;
    } else {
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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