How to Import CSV Data in PHP CodeIgniter Framework

Language

Importing CSV data into applications is a common practice. However, CodeIgniter Framework does not out of the box have this functionality as it does not have a library that does this. We will be using a csvimport.php library written by Bradstinson. This can be downloaded at github. This library converts CSV data to an array which can be looped through and saved into a database table.

Getting Started

First, you must download and install any local web server such as XAMPP/WAMP. After that, open the XAMPP/WAMP's Control Panel and start the "Apache" and "MySQL".

Download the latest version of CodeIgniter 3.1.11.Extract the zipped folder and copy the application folder, system folder, and index.php to the folder you will create in your site root called ciaddressimport. Go to "application/config" folder and edit the Base URL to "http://localhost/ciaddressimport/". Go to your browser and browse "http://localhost/ciaddressimport". You will now see the Codeigniter welcome page. This shows Codeigniter was successfully installed.

Download also Bootstrap for the design. Create new folder inside your "ciaddressimport" naming "assets". Extract the bootstrap and copy the folders then paste it into the "assetes" folder.

Copy the csvimport.php library downloaded from Github into "Applications/Libraries" folder. The library will be loaded in our controller.

Creation of Database

Open PHPMyAdmin and create a database called “ciaddressimport”. Also create a table with the following query.

  1. CREATE TABLE IF NOT EXISTS `addressbook` (
  2. `firstname` varchar(255) DEFAULT NULL,
  3. `lastname` varchar(255) DEFAULT NULL,
  4. `phone` varchar(100) DEFAULT NULL,
  5. `email` varchar(255) DEFAULT NULL,
  6. PRIMARY KEY (`id`)

You can generate some dummy data for the table at

www.generatedata.com

Database Connection

Open database.php in the config (application/config) folder and set your database parameters as follows.

  1. $db['default']['hostname'] = 'localhost';
  2. $db['default']['username'] = 'root';
  3. $db['default']['password'] = '';
  4. $db['default']['database'] = 'ciaddressimport';

Note: This configuration is for Wamp, if you are using Mamp , Xampp or Lamp set yours as required.

Route Configuration

Open the routes.php in "Application/Config folder". Change the default controller from "welcom" to "csv".

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

Autoload Configuration

Open the autoload.php in the "application/config". Then configure to load automatically the "db" library for the database connection and "URL" helper for the base URL usage. Follow the code below.

  1. $autoload['libraries'] = array('database');
  1. $autoload['helper'] = array('url');

Creation of CSV Model

Create a new model file in the model folder called "csv_model.php" inside "application/models". Add the following code:

  1. <?php
  2.  
  3. class Csv_model extends CI_Model {
  4.  
  5. function __construct() {
  6. parent::__construct();
  7.  
  8. }
  9.  
  10. function get_addressbook() {
  11. $query = $this->db->get('addressbook');
  12. if ($query->num_rows() > 0) {
  13. return $query->result_array();
  14. } else {
  15. return FALSE;
  16. }
  17. }
  18.  
  19. function insert_csv($data) {
  20. $this->db->insert('addressbook', $data);
  21. }
  22. }
  23. /*END OF FILE*/

Creation of Controller

Create a New controller called csv.php in the controllers folder and add the following code:

  1. <?php
  2.  
  3. class Csv extends CI_Controller {
  4.  
  5. function __construct() {
  6. parent::__construct();
  7. $this->load->model('csv_model');
  8. $this->load->library('csvimport');
  9. }
  10.  
  11. function index() {
  12. $data['addressbook'] = $this->csv_model->get_addressbook();
  13. $this->load->view('csvindex', $data);
  14. }
  15.  
  16. function importcsv() {
  17. $data['addressbook'] = $this->csv_model->get_addressbook();
  18. $data['error'] = ''; //initialize image upload error array to empty
  19.  
  20. $config['upload_path'] = './uploads/';
  21. $config['allowed_types'] = 'csv';
  22. $config['max_size'] = '1000';
  23.  
  24. $this->load->library('upload', $config);
  25.  
  26.  
  27. // If upload failed, display error
  28. if (!$this->upload->do_upload()) {
  29. $data['error'] = $this->upload->display_errors();
  30.  
  31. $this->load->view('csvindex', $data);
  32. } else {
  33. $file_data = $this->upload->data();
  34. $file_path = './uploads/'.$file_data['file_name'];
  35.  
  36. if ($this->csvimport->get_array($file_path)) {
  37. $csv_array = $this->csvimport->get_array($file_path);
  38. foreach ($csv_array as $row) {
  39. $insert_data = array(
  40. 'firstname'=>$row['firstname'],
  41. 'lastname'=>$row['lastname'],
  42. 'phone'=>$row['phone'],
  43. 'email'=>$row['email'],
  44. );
  45. $this->csv_model->insert_csv($insert_data);
  46. }
  47. $this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
  48. redirect(base_url().'csv');
  49. //echo "<pre>"; print_r($insert_data);
  50. } else
  51. $data['error'] = "Error occured";
  52. $this->load->view('csvindex', $data);
  53. }
  54.  
  55. }
  56.  
  57. }
  58. /*END OF FILE*/

Creation of the Interface

Go to your views (application/views) folder and create file called csvindex.php Add the following code:

  1. <!DOCTYPE HTML>
  2. <head>
  3. <meta charset="utf-8">
  4. <title>Adddress Book Project</title>
  5. <link href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap.css" type="text/css" rel="stylesheet" />
  6. <link href="<?php echo base_url(); ?>assets/css/styles.css" type="text/css" rel="stylesheet" />
  7.  
  8. <script src="<?php echo base_url(); ?>assets/js/jquery.js" type="text/javascript"></script>
  9. <script src="<?php echo base_url(); ?>assets/bootstrap/js/bootstrap.min.js"></script>
  10. </head>
  11.  
  12. <body>
  13.  
  14. <div class="navbar navbar-inverse navbar-fixed-top">
  15. <div class="navbar-inner">
  16. <div class="container">
  17. <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
  18. <span class="icon-bar"></span>
  19. <span class="icon-bar"></span>
  20. <span class="icon-bar"></span>
  21. </a>
  22. <a class="brand" href="#">My Address book</a>
  23. <div class="nav-collapse collapse">
  24. <ul class="nav">
  25. <li class="active"><a href="<?php echo base_url(); ?>"><i class="icon-home"></i>Home</a></li>
  26. <li><a href="#about">About</a></li>
  27. </ul>
  28. </div><!--/.nav-collapse -->
  29. </div>
  30. </div>
  31. </div>
  32.  
  33. <div class="container" style="margin-top:50px">
  34. <br>
  35.  
  36. <?php if (isset($error)): ?>
  37. <div class="alert alert-error"><?php echo $error; ?></div>
  38. <?php endif; ?>
  39. <?php if ($this->session->flashdata('success') == TRUE): ?>
  40. <div class="alert alert-success"><?php echo $this->session->flashdata('success'); ?></div>
  41. <?php endif; ?>
  42.  
  43. <h2>CI Addressbook Import</h2>
  44. <form method="post" action="<?php echo base_url() ?>csv/importcsv" enctype="multipart/form-data">
  45. <input type="file" name="userfile" ><br><br>
  46. <input type="submit" name="submit" value="UPLOAD" class="btn btn-primary">
  47. </form>
  48.  
  49. <br><br>
  50. <table class="table table-striped table-hover table-bordered">
  51. <caption>Address Book List</caption>
  52. <tr>
  53. <th>First Name</th>
  54. <th>Last Name</th>
  55. <th>Phone</th>
  56. <th>Email</th>
  57. </tr>
  58. </thead>
  59. <?php if ($addressbook == FALSE): ?>
  60. <tr><td colspan="4">There are currently No Addresses</td></tr>
  61. <?php else: ?>
  62. <?php foreach ($addressbook as $row): ?>
  63. <tr>
  64. <td><?php echo $row['firstname']; ?></td>
  65. <td><?php echo $row['lastname']; ?></td>
  66. <td><?php echo $row['phone']; ?></td>
  67. <td><?php echo $row['email']; ?></td>
  68. </tr>
  69. <?php endforeach; ?>
  70. <?php endif; ?>
  71. </tbody>
  72. </table>
  73.  
  74.  
  75. <hr>
  76. <footer>
  77. <p>&copy;My Address Book</p>
  78. </footer>
  79.  
  80. </div>
  81.  
  82.  
  83.  
  84. </body>
  85. </html>

Demo

Explanations

In the model file ci_model.php, on lines 10-17, we queried our address book table to get all address book records. The data retrieved will be displayed in the csvindex.php view. Lines 19-21 contains the query that inserts each row of records into the table.

In the controller file csv.php, on lines 7-8, we loaded the csvimport.php library and csv_model.php model in the CSV class constructor. On lines 11-14, we created a default index method that fetches the address from the database and sends it to the csvindex.php view. On lines 16-53, The "csvimport" method handles the CSV import functionality. First, we initialize the upload error to an empty string, Next, we set some configuration parameters for the file that is uploaded which included the upload location, the allowed file type which is CSV, and the maximum size of an uploaded file. Then we try to upload the file and if it fails we set the error message and call the csvindex.php view to show the error. However, if the upload was successful, we get the file path of the file uploaded, we then call the get_array method of the csvimport library and assign it to a variable called $csv_array. But if the get_array method failed, we show appropriate error in the csvindex.php view. We then loop through the $csv_array variable using the foreach loop. While looping through the $csv_array data, we insert the records one at a time into the addressbook table by calling the insert_csv method of the csv_model class. Once the loop is complete, we then set a session message called "success" and redirect the user to the home page. This success message is then displayed in the home page and the new records inserted are displayed in the table.

Note: The csvimport.php library assumes the first row of your csv file is the column name

In the csvindex.php view, on lines 37 to 39 we check if there is an error message, then we display the error. We also check if there is a session message called "success", then we display the success message. Lines 45-48 displays the upload form. As you can see we set the enctype="multipart/form-data" because it contains file upload. On lines 62-73, we loop through the "addressbook" data and display all the records.

That's the end of this tutorial. I hope this tutorial will help you with what you are looking for.

Enjoy Coding :)

Explore more on this website for more Tutorials and Free Project Source Codes.

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

Submitted byokay (not verified)on Thu, 06/05/2014 - 14:18

where is the importcsv library, i tries running the codes with my "modifications" but it just showed 404 page not found, and that page is the importcsv
Submitted byokay (not verified)on Thu, 06/05/2014 - 16:10

In reply to by okay (not verified)

okay so i have downloaded from git the csvimport library and copy and pasted in my application/libraries folder but 404 not found error is still showing, kindly help on this coz im stuck thanks in advance
Submitted byWiBe (not verified)on Wed, 12/02/2015 - 21:27

In reply to by okay (not verified)

Just rename file to Csvimport and it's ready to use... ;)
Submitted byRiana Dwiningtyas (not verified)on Wed, 08/27/2014 - 21:35

I wonder, is it possible to import csv, that is exported sql database with multiple tables, and put it on mysql as multiple tables too? I’ve seen several tutorials and it’s just imports csv with one table. thanks for reply..
Submitted byMunna Khan (not verified)on Sun, 09/14/2014 - 00:33

Message: Undefined offset: 1 Filename: libraries/Csvimport.php Line Number: 146

In this template made for csv import here i got a problem... I used an image tag in php file.. but it dosent load the image in the view .. strangely i removed al js and css still the image dosent load.. for checking path i made an html file and it loaded the image... can you please answer my query????
Submitted byviet huy dong (not verified)on Wed, 12/10/2014 - 00:34

the upload path does not appear to be valid controller : var $upload_dir="template/images/product/"; if($this->form_validation->run() == false) { $this->load->vars($data); $this->load->view('administrator/admin_template'); } else { $config['upload_path']=$this->upload_dir; $config['allowed_types']= 'gif|png|jpg'; $config['max_size']='2048'; $this->load->library('upload',$config); if(!$this->upload->do_upload('img')) { $data['error']=$this->upload->display_errors(); $this->load->vars($data); $this->load->view('administrator/admin_template'); } else { $img=$this->upload->data(); $images=$this->upload_dir.$img['file_name']; $this->product_model-> addProduct($Name,$Mo_ta,$Noi_dung,$Trang_thai,$category2,$Tinh_nang,$Gia,$images); $this->session->set_flashdata('message','Thêm sản phẩm '.$Name.' thành công!'); redirect(base_url().'administrator/product','refresh'); } }
Submitted bySuman Sapkota (not verified)on Sun, 05/24/2015 - 10:23

Hello I tried this code in my machine. I got error during uploading csv file, it says The filetype you are attempting to upload is not allowed. How can i fix this ??
Submitted byDarshan (not verified)on Sat, 07/18/2015 - 12:45

Got error Message: Undefined offset: 1 Filename: libraries/Csvimport.php Line Number: 146 reply
Submitted bySanju Panicker (not verified)on Thu, 08/20/2015 - 14:31

error(Unable to load the requested class: excel) or csv i tried by changing the above code for excel from csv. For csv also not working. what to do????? help
Submitted byPeter M (not verified)on Sat, 04/30/2016 - 09:31

Thank you very much. With a few changes I was able to upload my database with base information. I included Ion Auth code to validate it was the administrator doing the task.
Submitted byarima (not verified)on Fri, 11/18/2016 - 17:19

do i really need to change the path in the routes ?
Submitted byHaytham (not verified)on Thu, 03/09/2017 - 17:52

How to define the "Vertical Bar" separator in mimes for csv files? for example myfile.csv content 2016-09-25 00:00:48|2016-09-26 00:00:43|UAE|Toyota|Eric|Male|[email protected]
Submitted byMark Pape (not verified)on Sat, 04/15/2017 - 14:15

class Csv extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('csv_model'); $this->load->library('csvimport'); } function index() { $this->load->library('session'); $data['addressbook'] = $this->csv_model->get_addressbook(); $this->load->view('csvindex', $data); } function importcsv() { $data['addressbook'] = $this->csv_model->get_addressbook(); $data['error'] = ''; //initialize image upload error array to empty $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'csv'; $config['max_size'] = '1000'; $this->load->library('session'); $this->load->library('upload', $config); // If upload failed, display error if (!$this->upload->do_upload()) { $data['error'] = $this->upload->display_errors(); $this->load->view('csvindex', $data); } else { $file_data = $this->upload->data(); $file_path = './uploads/'.$file_data['file_name']; if ($this->csvimport->get_array($file_path)) { $csv_array = $this->csvimport->get_array($file_path); foreach ($csv_array as $row) { $insert_data = array( 'firstname'=>$row['firstname'], 'lastname'=>$row['lastname'], 'phone'=>$row['phone'], 'email'=>$row['email'], ); $this->csv_model->insert_csv($insert_data); } $this->session->set_flashdata('success', 'Csv Data Imported Succesfully'); redirect(base_url().'csv'); //echo "
"; print_r($insert_data);
            } else
                $data['error'] = "Error occured";
            $this->load->view('csvindex', $data);
        }

    }
Submitted byAvinash_singh (not verified)on Thu, 07/13/2017 - 02:00

function importcsv() { $res = $this->getAllLocation(); ini_set('auto_detect_line_endings', true); if ($_FILES ['csv_name'] != '') { $adminId=$this->session->userdata('admin_id'); //$language=$this->input->post('selLanguage'); //setSAActivityLogs('Transaction_activity','SAKeywordscv',"upload By :- ".$adminId); $error = array(); $line_error = 1; $base_url = base_url(); $file_name = time() . $_FILES ["csv_name"] ["name"]; move_uploaded_file($_FILES ["csv_name"] ["tmp_name"], "./uploads/keywordcsv/" . $file_name); $upfile = "./uploads/keywordcsv/$file_name"; $fp = fopen($upfile, "r"); $n = 0; $k = 0; $duplicate = array(); $flag = 0; while ($line1 = fgets($fp)) { $importData = str_getcsv($line1, ',', '"'); if ($importData [0] != '') { if ($n > 0) { $txtid = $importData[0]; $location_name = $importData[1]; //echo $location_name;exit; for ($i = 0; $i getAllLocation(); if ($res[$i]->location_name == $location_name) { $duplicate[$k] = $location_name; $k++; $flag = 1; } } if ($flag == 0) { $data = array('county_id' => $txtid, 'location_name' => $location_name, 'status' => 1); // print_r($data);exit; $this->db->insert('data_location', $data); } $flag = 0; } $n ++; } } $this->create_log(" Location Csv", "Location","upload By :- ".$adminId); $this->session->set_userdata('duplicate', $duplicate); //$str=implode(" ", $duplicate); return true; } return false; }
Submitted byleif Albert (not verified)on Wed, 08/21/2019 - 04:23

I just downloaded this "How to Import CSV Data in Codeigniter" But does not work there is enough help to get
Submitted bySomeDude (not verified)on Fri, 02/17/2023 - 18:34

Nothing Happening when I click on upload. File not upload and nothing in Database.

Add new comment