How to export MySQL data to CSV file in CodeIgniter
To export MySQL data to a CSV file in a CodeIgniter application, you can follow these steps:
Step 1: Set Up Your CodeIgniter Project
Make sure you have CodeIgniter installed and your project set up. If not, follow the official CodeIgniter Installation Guide.
Step 2: Create a Controller
Create a new controller in your CodeIgniter application that will handle the export functionality. For example, you can create a controller called CsvExport.php.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class CsvExport extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Your_model'); // Load your model to fetch data } public function export() { // Fetch data from your database $data = $this->Your_model->fetchData(); // Define the CSV file name $filename = 'exported_data.csv'; // Create or open the CSV file for writing $csv_file = fopen('path_to_export_directory/' . $filename, 'w'); // Write the CSV headers $csv_headers = array("Column1", "Column2", "Column3"); // Replace with your column names fputcsv($csv_file, $csv_headers); // Write the data to the CSV file foreach ($data as $row) { fputcsv($csv_file, $row); } // Close the CSV file fclose($csv_file); // Set the appropriate headers to download the file header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename="' . $filename . '"'); readfile('path_to_export_directory/' . $filename); exit; } }
Replace Your_model with the name of your model and customize the controller according to your database structure.
Step 3: Create a Model
Create a model that fetches the data you want to export. Replace Your_model with the actual model name.
<?php class Your_model extends CI_Model { public function fetchData() { // Fetch data from your database $this->db->select("column1, column2, column3"); // Replace with your columns $query = $this->db->get("your_table_name"); // Replace with your table name return $query->result_array(); } }
Step 3: Create a Route
Create a route in your config/routes.php file to map the controller's export function to a URL.
$route['csv-export'] = 'CsvExport/export';
Step 5: Access the Export Page
Access the export functionality by visiting the URL associated with the export function in your browser. For example, if you defined the route as csv-export, you can access it by visiting http://yourdomain.com/csv-export.
Step 6: Download the CSV
When you access the URL, the CSV file will be generated, and your browser will prompt you to download it.
This code will export data from your database table to a CSV file using CodeIgniter. Make sure to customize the controller, model, and database queries to match your specific requirements. Additionally, handle any error checking and validation as needed.