How to Export MySQL Data to CSV Using PHP?
Exporting data to a CSV (Comma Separated Values) file is a common task for data management. CSV files are easy to use for offline storage and data transfer between different programs. In this guide, we will walk you through the steps to export MySQL data to a CSV file using PHP. This tutorial will help you effortlessly manage your data export needs.
Step 1 : Create the Database Table :
First, you need a MySQL database with a table containing the data you want to export. For this example, we will use a users
table.
CREATE TABLE users (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
phone VARCHAR(15) NOT NULL,
created DATETIME NOT NULL,
status ENUM('Active', 'Inactive') NOT NULL DEFAULT 'Active',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Step 2 : Create the Database Config File :
Create a dbconfig.php
file to handle the database connection.
connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
Step 3 : Create the Export Script :
Create a file named exportcsvfile.php
to handle the export functionality.
query("SELECT * FROM users ORDER BY id DESC");
// If the query returns rows
if ($query->num_rows > 0) {
// Loop through the rows and write them to the CSV file
while ($row = $query->fetch_assoc()) {
fputcsv($output, $row);
}
}
// Close the file
fclose($output);
exit();
?>
Step 4 : Create the Main File to Trigger Export :
Create an index.php
file to provide a user interface for triggering the export.
Export MySQL Data to CSV using PHP
User List
#ID
Name
Email
Phone
Created
Status
query("SELECT * FROM users ORDER BY id DESC");
if ($query->num_rows > 0) {
while ($row = $query->fetch_assoc()) {
?>
= $row['id'] ?>
= $row['name'] ?>
= $row['email'] ?>
= $row['phone'] ?>
= $row['created'] ?>
= $row['status'] ?>
No records found...
Conclusion :
Exporting MySQL data to a CSV file using PHP is straightforward. This guide covers the entire process, from setting up the database to writing the export script and creating a user interface. By following these steps, you can efficiently export data and provide it for download in a widely used format. Happy coding!