如何使用Codeigniter PHP在数据库中导入CSV?

时间:2015-09-12 09:28:29

标签: php codeigniter csv file-upload import

我正在尝试使用csv插入记录。我想将csv上传到我的应用程序,并希望将其导入数据库。现在我有一个用户表,所以我想通过导入用户的csv文件来创建用户。我知道一些关于文件上传的内容,但是关于将其导入数据库没有问题请帮助。

请参阅我已完成文件上传使用: 控制器:

       public function upload_csv()
      {
            $this->load->helper('form');
            $this->load->helper('url');

            //Set the message for the first time
            $data = array('msg' => "Upload File");

            $data['upload_data'] = '';

            //load the view/upload.php with $data
            $this->load->view('admin/user/upload', $data);

      }

另一个Controller Upload_file

public function upload_it() {
    //load the helper
    $this->load->helper('form');

    //Configure
    //set the path where the files uploaded will be copied. NOTE if using linux, set the folder to permission 777
    $config['upload_path'] = 'application/views/uploads/';

// set the filter image types
    $config['allowed_types'] = 'gif|csv';

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

$this->upload->initialize($config);

$this->upload->set_allowed_types('*');

    $data['upload_data'] = '';

    //if not successful, set the error message
    if (!$this->upload->do_upload('userfile')) {
        $data = array('msg' => $this->upload->display_errors());

    } else { //else, set the success message
        $data = array('msg' => "Upload success!");

  $data['upload_data'] = $this->upload->data();

    }

    //load the view/upload.php
    $this->load->view('admin/user/upload', $data);

}

和观点:

    <code>
    <?php if($upload_data != ''):?>
    <?php var_dump($upload_data);?>

    </code>
    <img scr="<?php echo $upload_data['full_path'];?>">
    <?php endif;?>

    <?php echo form_open_multipart('admin/upload_file/upload_it');?>

    <input type="file" name="userfile" size="20" />

    <br /><br />

    <input type="submit" value="upload" />

    </form>

现在如何将上传的文件导入我的数据库?

2 个答案:

答案 0 :(得分:6)

来自2秒的Google和PHP docs

$csv = array_map('str_getcsv', file('data.csv'));

然后你可以遍历数组并UPDATE你的数据库

答案 1 :(得分:4)

首先更改位于config文件夹中的route.php中的default_controller值。

$ route ['default_controller'] =“csv”;

将控制器创建为 csv.php

<?php
class csv extends CI_Controller
{
    public $data;
    public function __construct()
    {
        parent::__construct();
        $this->load->model('csv_model');
    }
    function index()
    {
        $this->load->view('uploadCsvView',$data);
    }
    function uploadData()
    {
        $this->csv_model->uploadData();
        redirect('csv');
    }
}
?>

将模型创建为 csv_model.php

<?php
class csv_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    function uploadData()
    {
        $count=0;
        $fp = fopen($_FILES['userfile']['tmp_name'],'r') or die("can't open file");
        while($csv_line = fgetcsv($fp,1024))
        {
            $count++;
            if($count == 1)
            {
                continue;
            }//keep this if condition if you want to remove the first row
            for($i = 0, $j = count($csv_line); $i < $j; $i++)
            {
                $insert_csv = array();
                $insert_csv['id'] = $csv_line[0];//remove if you want to have primary key,
                $insert_csv['empName'] = $csv_line[1];
                $insert_csv['empAddress'] = $csv_line[2];

            }
            $i++;
            $data = array(
                'id' => $insert_csv['id'] ,
                'empName' => $insert_csv['empName'],
                'empAddress' => $insert_csv['empAddress']
               );
            $data['crane_features']=$this->db->insert('tableName', $data);
        }
        fclose($fp) or die("can't close file");
        $data['success']="success";
        return $data;
    }
}

最后创建一个视图 uploadCsvView.php

<form action="<?php echo site_url();?>csv/uploadData" method="post" enctype="multipart/form-data" name="form1" id="form1"> 
    <table>
        <tr>
            <td> Choose your file: </td>
            <td>
                <input type="file" class="form-control" name="userfile" id="userfile"  align="center"/>
            </td>
            <td>
                <div class="col-lg-offset-3 col-lg-9">
                    <button type="submit" name="submit" class="btn btn-info">Save</button>
                </div>
            </td>
        </tr>
    </table> 
</form>

创建要插入数据的mysql表:

CREATE TABLE tableName(
    id INT,
    empName VARCHAR( 100 ) ,
    empAddress VARCHAR( 100 ),
    PRIMARY KEY (id)
)

最重要的一点:

  

MySql和Csv文件应该都是相同的

示例csv数据位于以下链接中:

https://drive.google.com/file/d/0B-OuLrage4PpUmtKNkhuS1JrSkE/view?usp=sharing