dqh1984 2015-09-12 09:28
浏览 35

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

I am trying to insert records using csv. I want to upload csv to my Application and want to import it in database. Now I have a users table so i want to create users by importing user's csv file. I Know a little about file uploads but nil about importing it into database please help .

See I have done the file upload using : Controller:

       public function upload_csv()

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


The Another Controller Upload_file

public function upload_it() {
    //load the helper

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



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


And The view:

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

    <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" />


Now How do i import a uploaded file into my database ??

  • 写回答

2条回答 默认 最新

  • dongliao1860 2015-09-12 09:36

    From a 2 second Google and the PHP docs:

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

    Then you can loop through the Array and UPDATE your DB

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
  • duanlv5084 2016-08-31 08:41

    First change the default_controller value in route.php which lies inside config folder.

    $route['default_controller'] = "csv";

    Create a controller as csv.php

    class csv extends CI_Controller
        public $data;
        public function __construct()
        function index()
        function uploadData()

    And create a model as csv_model.php

    class csv_model extends CI_Model
        function __construct()
        function uploadData()
            $fp = fopen($_FILES['userfile']['tmp_name'],'r') or die("can't open file");
            while($csv_line = fgetcsv($fp,1024))
                if($count == 1)
                }//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];
                $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");
            return $data;

    And at last create a view as uploadCsvView.php

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

    And create mysql table where data is going to be inserted:

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

    And most important point:

    MySql and Csv file should both be same

    Sample csv data is in the following link:





  • ¥15 有人会思科模拟器嘛?
  • ¥30 遇到一个的问题,请教各位
  • ¥20 matlab报错,vflux计算潜流通量
  • ¥15 我该如何实现鼠标按下GUI按钮时就执行按钮里面的操作的方法
  • ¥15 关于#硬件工程#的问题:我这边有个锁相环电路没有效果
  • ¥15 20款 27寸imac苹果一体机装win10后,蓝牙耳机和音响放歌曲卡顿断断续续.
  • ¥15 VB.NET 父窗体调取子窗体报错
  • ¥15 python海龟作图如何改代码使其最后画出来的是一个镜像翻转的图形
  • ¥15 我不明白为什么c#微软的官方api浏览器为什么不支持函数说明的检索,有支持检索函数说明的工具吗?
  • ¥15 在我想检测ros是否成功安装时输入roscore出现以下