Home >>Codeigniter Tutorial >Export MySQL data to CSV file in CodeIgniter

Export MySQL data to CSV file in CodeIgniter

Export MySQL data to CSV file in CodeIgniter

To import and export data CSV(Comma Separated Values) is the most popular file format for Web Development.

You can either use fputcsv() PHP method or directly write the comma-separated content on the file in PHP for creating CSV file.

In this tutorial, We are going to guide you how you can export MySQL data in CSV file in CodeIgniter project.

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(ExportController.php)


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

class ExportController extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->helper('url');
		$this->load->model('ExportModel');
	}
	
	public function index()
	{
		$data = array();
		$data['usersData'] = $this->ExportModel->getUserDetails();
		$this->load->view('export_view',$data);
	}

	// Export data in CSV format
	public function exportCSV()
	{
		
		//csv file name
		$filename = 'users_'.date('Ymd').'.csv';
		header("Content-Description: File Transfer");
		header("Content-Disposition: attachment; filename=$filename");
		header("Content-Type: application/csv; "); 

		// get data
		$usersData = $this->ExportModel->getUserDetails();

		// file creation
		$file = fopen('php://output', 'w');

		$header = array("srno","Name","Mobile","Email");
		fputcsv($file, $header);

		foreach ($usersData as $key=>$line){
		 fputcsv($file,$line);
		}

		fclose($file);
		exit;
	}
}

Model(ExportModel.php)


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class ExportModel extends CI_Model 
{
    function getUserDetails(){
        
        $response = array();
           
        // Select record
        $this->db->select('*');
        $q = $this->db->get('tbl_user');
        $response = $q->result_array();
        
        return $response;
    }

}
}

View(export_view.php)


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<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>
	<title>Export MySQL data to CSV file in CodeIgniter</title>
</head>
<body>

	<!-- Export Data -->
	<a href='<?php echo  base_url('/ExportController/exportCSV'); ?>'>Export</a><br><br>

	<!-- User Records -->
	<table class="table table-bordered">
		<thead>
			<tr>
				<th>Name</th>
				<th>Email</th>
				<th>Mobile</th>
			</tr>
		</thead>
		<tbody>
			<?php
			foreach($usersData as $key=>$val)
			{
				echo "<tr>";
				echo "<td>".$val['name']."</td>";
				echo "<td>".$val['email']."</td>";
				echo "<td>".$val['phone']."</td>";
				echo "</tr>";
			}
			?>
		</tbody>
	</table>
</body>
</html>

Output

Total Downloads : 53

Login / Register To Download

No Sidebar ads