How to Import CSV Data in PHP CodeIgniter Framework
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.
You can generate some dummy data for the table at
www.generatedata.comDatabase Connection
Open database.php in the config (application/config) folder and set your database parameters as follows.
- $db['default']['hostname'] = 'localhost';
- $db['default']['username'] = 'root';
- $db['default']['password'] = '';
- $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".
- $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.
Creation of CSV Model
Create a new model file in the model folder called "csv_model.php" inside "application/models". Add the following code:
- <?php
- class Csv_model extends CI_Model {
- function __construct() {
- parent::__construct();
- }
- function get_addressbook() {
- $query = $this->db->get('addressbook');
- if ($query->num_rows() > 0) {
- return $query->result_array();
- } else {
- return FALSE;
- }
- }
- function insert_csv($data) {
- $this->db->insert('addressbook', $data);
- }
- }
- /*END OF FILE*/
Creation of Controller
Create a New controller called csv.php in the controllers folder and add the following code:
- <?php
- class Csv extends CI_Controller {
- function __construct() {
- parent::__construct();
- $this->load->model('csv_model');
- $this->load->library('csvimport');
- }
- function index() {
- $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('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) {
- '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 "<pre>"; print_r($insert_data);
- } else
- $data['error'] = "Error occured";
- $this->load->view('csvindex', $data);
- }
- }
- }
- /*END OF FILE*/
Creation of the Interface
Go to your views (application/views) folder and create file called csvindex.php Add the following code:
- <!DOCTYPE HTML>
- <html>
- <head>
- <meta charset="utf-8">
- <link href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap.css" type="text/css" rel="stylesheet" />
- <link href="<?php echo base_url(); ?>assets/css/styles.css" type="text/css" rel="stylesheet" />
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="navbar-inner">
- <div class="container">
- <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
- </a>
- <div class="nav-collapse collapse">
- <ul class="nav">
- </ul>
- </div><!--/.nav-collapse -->
- </div>
- </div>
- </div>
- <div class="container" style="margin-top:50px">
- <br>
- <?php if (isset($error)): ?>
- <?php endif; ?>
- <?php if ($this->session->flashdata('success') == TRUE): ?>
- <?php endif; ?>
- <form method="post" action="<?php echo base_url() ?>csv/importcsv" enctype="multipart/form-data">
- <input type="submit" name="submit" value="UPLOAD" class="btn btn-primary">
- </form>
- <table class="table table-striped table-hover table-bordered">
- <thead>
- <tr>
- </tr>
- </thead>
- <tbody>
- <?php if ($addressbook == FALSE): ?>
- <?php else: ?>
- <?php foreach ($addressbook as $row): ?>
- <tr>
- </tr>
- <?php endforeach; ?>
- <?php endif; ?>
- </tbody>
- </table>
- <hr>
- <footer>
- </footer>
- </div>
- </body>
- </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
csvimport not found
The upload path does not appear to be valid.
Import CSV with multiple tables
Image Upload
help me
Error uploading file
Hello Error Solve pls help me
Unable to load the requested class: excel
The upload path does not appear to be valid.
Vertical Bar separator
Missing Loader in functions: $this->load->library('session');
"; print_r($insert_data); } else $data['error'] = "Error occured"; $this->load->view('csvindex', $data); } }
The filetype you are attempting to upload is not allowed.
The filetype you are attempting to upload is not allowed..
csv
The filetype you are attempting to upload is not allowed.
The filetype you are attempting to upload is not allowed..
not verified
Nothing Happening
Add new comment
- Add new comment
- 7417 views