Skip to main content

Import CSV Data into Mysql in Codeigniter

controllers - 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 load_data()
 {
  $result = $this->csv_import_model->select();
  $output = '
   <h3 align="center">Imported User Details from CSV File</h3>
        <div class="table-responsive">
         <table class="table table-bordered table-striped">
          <tr>
           <th>Sr. No</th>
           <th>First Name</th>
           <th>Last Name</th>
           <th>Phone</th>
           <th>Email Address</th>
          </tr>
  ';
  $count = 0;
  if($result->num_rows() > 0)
  {
   foreach($result->result() as $row)
   {
    $count = $count + 1;
    $output .= '
    <tr>
     <td>'.$count.'</td>
     <td>'.$row->first_name.'</td>
     <td>'.$row->last_name.'</td>
     <td>'.$row->phone.'</td>
     <td>'.$row->email.'</td>
    </tr>
    ';
   }
  }
  else
  {
   $output .= '
   <tr>
       <td colspan="5" align="center">Data not Available</td>
      </tr>
   ';
  }
  $output .= '</table></div>';
  echo $output;
 }

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

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

views - 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>
  <br />

  <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/load_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",
   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>
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_user`
--

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

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_user`
--
ALTER TABLE `tbl_user`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_user`
--
ALTER TABLE `tbl_user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;




Comments

Popular posts from this blog

Insert Fetch Update Delete Mysql data in Codeigniter

Database -- -- Table structure for table `tbl_user` -- CREATE TABLE IF NOT EXISTS `tbl_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(200) NOT NULL, `last_name` varchar(200) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=95 ; -- -- Dumping data for table `tbl_user` -- INSERT INTO `tbl_user` (`id`, `first_name`, `last_name`) VALUES (91, 'Harold', 'Jones'), (89, 'Christine', 'Smith'), (88, 'Marker', 'Angela'), (87, 'Romeo', 'Mary'), (86, 'Smith', 'John'); Controller - main.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Main extends CI_Controller { //functions public function index(){ $this->load->model("main_model"); $data["fetch_data"] = $this->main_model->...

How to Generate Excel File in Codeigniter using PHPExcel

Libraries/Excel.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); require_once('PHPExcel.php'); class Excel extends PHPExcel { public function __construct() { parent::__construct(); } } ?> Libraries/IOFactory.php <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); require_once('PHPExcel/IOFactory.php'); class IOFactory extends PHPExcel_IOFactory { public function __construct() { parent::__construct(); } } ?> Controllers/Excel_export.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Excel_export extends CI_Controller { function index() { $this->load->model("excel_export_model"); $data["employee_data"] = $this->excel_export_model->fetch_data(); $this->load->view("excel_export_view", $data); } function action() { $this->load->model(...

Core php login logout and register view delete

Core php login logout and register view delete Database.php CREATE TABLE IF NOT EXISTS register.`users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `trn_date` datetime NOT NULL, PRIMARY KEY (`id`) ); CREATE TABLE IF NOT EXISTS register.`new_record` ( `id` int(11) NOT NULL AUTO_INCREMENT, `trn_date` datetime NOT NULL, `name` varchar(50) NOT NULL, `age`int(11) NOT NULL, `submittedby` varchar(50) NOT NULL, PRIMARY KEY (`id`) ); Auth.php <?php session_start(); if(!isset($_SESSION["username"])){ header("Location: login.php"); exit(); } ?> Dashbaord .php <!DOCTYPE html> <html lang="en"> <head> <title>Dashboard</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.boo...