在Codeigniter上将CSV导入数据库

时间:2018-02-28 07:35:11

标签: php codeigniter csv codeigniter-3

我刚刚开始学习Codeigniter(CI),我想将CSV文件导入数据库。

我跟着https://codeigniter.com/user_guide/libraries/file_uploading.html 但仍然困惑。

如何从上传表单中捕获文件?

在PHP native上,代码是

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

请帮忙。谢谢。

3 个答案:

答案 0 :(得分:0)

如何从上传表单中捕获文件?
上传完成后使用$this->upload->data()

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

Check the documentation for more details

答案 1 :(得分:0)

这可以帮到你。

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

    }
}

答案 2 :(得分:0)

你可以试试这个:

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

控制器:

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

型号:

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