Home >>Codeigniter Tutorial >Import CSV Data into Mysql in Codeigniter

Import CSV Data into Mysql in Codeigniter

Import CSV Data into Mysql in Codeigniter

Bulk Data Import using CSV feature is very useful features for web application Development.This Import feature will helps to insert bulk data at once instead of one by one and in this way we can reduce the time for inserting data in the database.

This CSV Import features makes it easy to insert a bunch of data in the database on a single click.

In CodeIgniter framework, need to use a custom library to import CSV data.In CodeIgniter there is no system library available to import CSV data.

Through this tutorial, we are going to show you how to import CSV file data into MySQL database in CodeIgniter.

Database table structure(tbl_user)

CREATE TABLE IF NOT EXISTS `tbl_user` (
  `id` int(11) NOT NULL primary key auto_increment,
  `name` varchar(250) NOT NULL,
  `phone` varchar(30) NOT NULL,
  `email` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Controller(Csv_import.php)


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Csv_import extends CI_Controller
 { 
 public function __construct()
 {
  parent::__construct();
  $this->load->model('csv_import_model');
  $this->load->library('csvimport');
 }

 function index()
 {
  $this->load->view('csv_import');
 }

 function display_data()
 {
  $result = $this->csv_import_model->select();
  $output = '
   <h3 align="center">User Details Imported from CSV</h3>
        <div class="table table-bordered">
         <table class="table table-bordered table-striped">
          <tr>
           <th>Sr.No</th>
           <th>Name</th>
           <th>Email</th>
		   <th>Mobile</th>
          </tr>
  ';
  $count = 0;
  if($result->num_rows() > 0)
  {
   foreach($result->result() as $row)
   {
    $count = $count + 1;
    $output .= '
    <tr>
     <td>'.$count.'</td>
     <td>'.$row->name.'</td>
     <td>'.$row->email.'</td>
	 <td>'.$row->phone.'</td>
    </tr>';
   }
  }
  else
  {
   $output .= '
   <tr>
       <td colspan="5" align="center">Data not Available</td>
      </tr>
   ';
  }
  $output .= '</table></div>';
  echo $output;
 }

 function import_csv()
 {
  $file_data = $this->csvimport->get_array($_FILES["csv_file"]["tmp_name"]);
  foreach($file_data as $row)
  {
   $data[] = array(
    'name' => $row["Name"],
     'phone'   => $row["Phone"],
     'email'   => $row["Email"]
   );
  }
  $this->csv_import_model->insert($data);
 }
}

Model(Csv_import_model.php)


<?php
class Csv_import_model extends CI_Model
{
 function select()
 {
  $this->db->order_by('id', 'DESC');
  $query = $this->db->get('tbl_user');
  return $query;
 }

 function insert($data)
 {
  $this->db->insert_batch('tbl_user', $data);
 }
}

View(csv_import.php)


<html>
<head>
    <title>How to Import CSV Data into Mysql using Codeigniter</title>  
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    
</head>
<body>
 <div class="container box">
  <h3 align="center">How to Import CSV Data into Mysql using Codeigniter</h3>
  
  <form method="post" id="import_csv" enctype="multipart/form-data">
   <div class="form-group">
    <label>Select CSV File</label>
    <input type="file" name="csv_file" id="csv_file" required accept=".csv" />
   </div>
   <br />
   <button type="submit" name="import_csv" class="btn btn-info" id="import_csv_btn">Import CSV</button>
  </form>
  <br />
  <div id="imported_csv_data"></div>
 </div>
</body>
</html>

<script>
$(document).ready(function(){

 load_data();

 function load_data()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>csv_import/display_data",
   method:"POST",
   success:function(data)
   {
    $('#imported_csv_data').html(data);
   }
  })
 }

 $('#import_csv').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"<?php echo base_url(); ?>csv_import/import_csv",
   method:"POST",
   data:new FormData(this),
   contentType:false,
   cache:false,
   processData:false,
   beforeSend:function(){
    $('#import_csv_btn').html('Importing...');
   },
   success:function(data)
   {
    $('#import_csv')[0].reset();
    $('#import_csv_btn').attr('disabled', false);
    $('#import_csv_btn').html('Import Done');
    load_data();
   }
  })
 });
 
});
</script>

Output(Before Uploading)
Output(after Uploading)

Total Downloads : 29

Login / Register To Download