Import CSV Data in Codeigniter v1 PHP Script

Import CSV Data in Codeigniter v1 PHP Script

Importing CSV data into application is a common practice. However, Codeigiter 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. Let’s get started.

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

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

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

 
 

CREATE TABLE IF NOT EXISTS `addressbook` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(255) DEFAULT NULL,
`lastname` varchar(255) DEFAULT NULL,
`phone` varchar(100) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;

 

 

You can generate some dummy data for the table at
www.generatedata.com

"Open database.php in the config folder and set your database parameters as follows. This can be found around lines 51

 
 

$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.

Open the routes.php in Application/Config folder. Around lines 41, Change the default controller to csv:

 
 

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

 

Create a new model file in the model folder called csv_model.php. 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*/

 

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) {
$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 "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}

}

}
/*END OF FILE*/

 

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

 
 

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Adddress Book Project</title>
<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" />

<script src="<?php echo base_url(); ?>assets/js/jquery.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/bootstrap/js/bootstrap.min.js"></script>
</head>

<body>

<a class="navbar navbar-inverse navbar-fixed-top">
<a class="navbar-inner">
<a class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">My Address book</a>
<a class="nav-collapse collapse">
<ul class="nav">
<li class="active"><a href="<?php echo base_url(); ?>"><i class="icon-home"></i>Home</a></li>
<li><a href="#about">About</a></li>
</ul>
</a><!--/.nav-collapse -->
</a>
</a>
</a>

<a class="container" style="margin-top:50px">
<br>

<?php if (isset($error)): ?>
<a class="alert alert-error"><?php echo $error; ?></a>
<?php endif; ?>
<?php if ($this->session->flashdata('success') == TRUE): ?>
<a class="alert alert-success"><?php echo $this->session->flashdata('success'); ?></a>
<?php endif; ?>

<h2>CI Addressbook Import</h2>
<form method="post" action="<?php echo base_url() ?>csv/importcsv" enctype="multipart/form-data">
<input type="file" name="userfile" ><br><br>
<input type="submit" name="submit" value="UPLOAD" class="btn btn-primary">
</form>

<br><br>
<table class="table table-striped table-hover table-bordered">
<caption>Address Book List</caption>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php if ($addressbook == FALSE): ?>
<tr><td colspan="4">There are currently No Addresses</td></tr>
<?php else: ?>
<?php foreach ($addressbook as $row): ?>
<tr>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
<td><?php echo $row['phone']; ?></td>
<td><?php echo $row['email']; ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>


<hr>
<footer>
<p>©My Address Book</p>
</footer>

</a>



</body>
</html>

 

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 thequery 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 that try to upload the file, 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 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.

 

 

 

Comments

Popular posts from this blog

Motos Android Mame Game Download

StatusNet Micro Blog PHP Script Free Download

1941 Counter Attack (Japan) Windows Game Download