etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Export data from MySQL table to CSV file using PHP

In this article, you will learn how to export data from a MySQL table to a CSV file using the PHP programming language. For this, we will create a user interface that contains an export data button. On clicking this button, the data will be exported to a CSV file and downloaded.





CSV file stands for "Comma-separated-values", as it uses a comma to separate values. This is a widely used file format that stores data in a tabular format. In web development, we can easily import/export to a CSV file, and we can also convert any file format to a CSV file. The data in the MySQL database is stored in rows. With the help of PHP, we can easily store each database row value as a comma-separated sequence.

Export data from MySQL table to CSV file using php



Suppose we have an 'employee' table in our MySQL database. You can either copy and paste this into your database or use your existing data.

CREATE TABLE IF NOT EXISTS `employee` (
  `emp_id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `phone` varchar(100) NOT NULL,
  `created_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `is_enabled` int(11) NOT NULL,
  PRIMARY KEY (`emp_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
INSERT INTO `employee` (`emp_id`, `emp_name`, `email`, `phone`, `created_date`, `is_enabled`) VALUES
(1, 'John', This email address is being protected from spambots. You need JavaScript enabled to view it.', '2323234543', '2019-06-05 15:36:07', 1),
(2, 'Smith', This email address is being protected from spambots. You need JavaScript enabled to view it.', '9898577442', '2019-05-14 15:36:07', 1),
(3, 'Priska', This email address is being protected from spambots. You need JavaScript enabled to view it.', '9393452387', '2019-05-28 15:36:07', 1),
(4, 'Gaga', This email address is being protected from spambots. You need JavaScript enabled to view it.', '8482764537', '2019-06-29 15:36:07', 1);

config.php

Now, let's create a configuration file to connect to the MySQL database. Make sure to replace the 'hostname', 'username', 'password' and 'databasename' with your database credentials and name.

<?php
$conn = new mysqli('hostname', 'username', 'password', 'databasename');
//Check for database connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
?>



Export data to CSV file in PHP

Next, we will create a main PHP file 'index.php' that we will call in the browser. This file contains code to select data from MySQL and display it in tabular format. We have added a button 'Export Data'. When the user clicks on this button, the data will be exported to a CSV file.

index.php

<?php
 include 'config.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Export data from MySQL table to CSV file using php</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<?php
$select = "SELECT * FROM `employee` ";
$result = $conn->query($select);
if($result->num_rows > 0){ 
 echo '<table class="table table-striped">';
 echo '<tr><th>Employee Name</th>'; 
 echo '<th>Email</th>'; 
 echo '<th>Phone</th>';  
 echo '<th>Enabled</th>';  
 echo '</tr>';
 while($row = $result->fetch_object()){
   $status = ($row->is_enabled == '1')?'Yes':'No';
   echo '<tr>';  
   echo '<td>'. $row->emp_name.'</td>';
   echo '<td>'. $row->email.'</td>';
   echo '<td>'. $row->phone.'</td>';
   echo '<td>'. $status.'</td>';
   echo '</tr>';
 }
 echo '</table>';
}
?>
<a href="exportdata.php" class="btn btn-primary">Export Data</a>
</div>
</body>
</html>



exportdata.php

On click the 'Export Data' button, it is directed to this page.

<?php

include 'config.php';

$select = "SELECT * FROM `employee` ";
$result = $conn->query($select);

if($result->num_rows > 0){
    $separator = ",";
    $filename = "employee_" . date('Y-m-d') . ".csv";
    // Set header content-type to CSV and filename
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');
    // create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');

    //set CSV column headers
    $fields = array('ID', 'Name', 'Email', 'Phone', 'Enable');
    fputcsv($output, $fields, $separator);
    
    
    while($row = $result->fetch_object()){ 
        $status = ($row->is_enabled == '1')?'Yes':'No';
        $lineData = array($row->emp_id, $row->emp_name, $row->email, $row->phone, $status);
	fputcsv($output, $lineData, $separator);
    }
	
    fclose($output);
    exit();
}
?>

In the above file, we have set the content type to 'text.csv'. This makes the CSV file downloadable. Also, set the filename in the header.

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');

The 'php://output' is write only stream. It allows us to write to the output buffer mechanism. It sends the CSV file directly to the browser.

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

The 'fputcsv()' function is used to format the field values as a line of CSV and write to the file pointer ($output). The '$separator' is a delimiter and an optional parameter. It allows one character only.

fputcsv($output, $fields, $separator);

At last, we have closed an open file pointer.

fclose($output);




Related Articles

Submit a form data without page refresh using PHP, Ajax and Javascript
PHP MySQL PDO Database Connection and CRUD Operations
How to insert image in database using PHP
Remove duplicates from array PHP
PHP sanitize input for MySQL
PHP random quote generator
PHP String Contains
PHP calculate percentage of total
PHP Fix: invalid argument supplied for foreach
Locking files with flock()
How to Pass an Array as URL Parameter in PHP
How to generate pdf in PHP using MySQL and MPDF Library
How to Export MySQL Table data as CSV file in PHP
Read CSV file & Import data into MySQL with PHP
Save an emoji in MySQL using PHP
Google reCAPTCHA v2 PHP example
Fetch data from database in PHP and display in PDF
How to create a PDF from a form using PHP
Form Validation with PHP




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Fibonacci Series Program in PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple File Upload Script in PHP
-----------------
Simple PHP File Cache
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
How to print specific part of a web page in javascript
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Get Visitor\'s location and TimeZone
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
PHP Programming Error Types
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
Set and Get Cookies in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
How to display PDF file in web page from Database in PHP
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.