How to Export CSV Files Using PHP and MySQL?

03-Apr-2023

.

Admin

How to Export CSV Files Using PHP and MySQL?

Hi Dev,

This article will provide example of how to export csv files using php and mysql. We will use export data to csv file using php and mysql. I’m going to show you about php csv file export. if you want to see example of export mysql data as csv file in php then you are a right place.

Just follow the below steps and easily export csv file into MySQL database using PHP script (code):

Step 1: Create a Database Connection File


You will create a file name index.php and update the below code into your file.

The below code is used to create a MySQL database connection in PHP. When we insert form data into MySQL database, there we will include this file:

<?php

$servername='localhost';

$username='root';

$password='';

$dbname = "my_db";

$conn=mysqli_connect($servername,$username,$password,"$dbname");

if(!$conn){

die('Could not Connect MySql Server:' .mysql_error());

}

?>

Step 2: Export MySQL Data to CSV file PHP Code

You need to create one file name export.php and update the below code into your file.

The code below is used to get data from the MySQL database and export it to a CSV file or download it. The sample file name is users-sample.csv.

<?php

// Database Connection

require("index.php");

// get users list

$query = "SELECT * FROM users";

if (!$result = mysqli_query($con, $query)) {

exit(mysqli_error($con));

}

$users = array();

if (mysqli_num_rows($result) > 0) {

while ($row = mysqli_fetch_assoc($result)) {

$users[] = $row;

}

}

header('Content-Type: text/csv; charset=utf-8');

header('Content-Disposition: attachment; filename=users-sample.csv');

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

fputcsv($output, array('No', 'Name', 'Mobile', 'Email'));

if (count($users) > 0) {

foreach ($users as $row) {

fputcsv($output, $row);

}

}

?>

I hope it could help you...

#PHP