Export MySQL data to CSV using PHP

Share

To export MySQL data to CSV using PHP, we need to follow the below process:

  1. Suppose you have a database with a table (let’s say a ‘user‘ table for an example).
  2. Create your project folder(e.g. ‘ExportCSV‘). If you are working on local not server then you can use XAMPP for windows and LAMP for Ubuntu. In XAMPP you will have a folder ‘htdocs‘, you need to place your project folder ‘ExportCSV‘ under ‘htdocs‘.
  3. Create three PHP files, one for database configurations i.e. ‘db_connection.php‘, second is ‘index.php‘ for initial page with fetched data and third is for exporting data into CSV i.e. ‘export.php‘. Put all these files under the folder ‘ExportCSV‘.
https://youtu.be/s9wa2pj3sfE

Step 1 : ‘User‘ table must have few data. Please see the example of table below:

IDFullNameEmail
1John Doe 1johndoe1@thetechnicaldiaries.com
2John Doe 2johndoe2@thetechnicaldiaries.com
‘user’ table

Step 2 : Open file ‘db_connection.php’ in code editor and write below configuration code:

<?php 

// Database configuration 

//$db_host : database host
//$db_username : database username
//$db_password : database password
//$db_name : database name

$db_host= "localhost"; 
$db_username= "root"; 
$db_password= ""; 
$db_name     = "demo"; 
 
// Create database connection 
$db = new mysqli($db_host, $db_username, $db_password, $db_name); 
 
// Check connection 
if ($db->connect_error) { 
    die("Connection failed: " . $db->connect_error); 
}

Step 3 : Open file ‘index.php‘ in code editor and first include the ‘db_connection.php‘ file at the top, to include db-connection. And then write code to fetch data from ‘user‘ table to show in tabular format.

<?php

// include the database configuration file 
include_once 'db_connection.php';

?>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<!-- Export CSV link -->
<a href="export.php">Export CSV</a>

<!-- Data list in tabular format --> 

<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>FullName</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
   <?php 
    // Fetch records from user table
    $result = $db->query("SELECT * FROM user"); 
    if($result->num_rows > 0){ 
        while($row = $result->fetch_assoc()){ 
    ?>
        <tr>
            <td><?php echo $row['ID']; ?></td>
            <td><?php echo $row['FullName']; ?></td>
            <td><?php echo $row['Email']; ?></td>
        </tr>
    <?php } }else{ ?>
        <tr><td colspan="3">No user...</td></tr>
    <?php } ?>
    </tbody>
</table>

Step 4 : Open file ‘export.php‘ and write following codes to export the data into csv:

<?php 
 
// include the database configuration file 
include_once 'db_connection.php'; 
 
// Fetch records from user table
$query = $db->query("SELECT * FROM user"); 
 
if($query->num_rows > 0){ 
    $delimiter = ","; 
    $filename = "usercsv_" . date('Y-m-d') . ".csv"; 
     
    // Create a file pointer 
    $f = fopen('php://memory', 'w'); 
     
    // Set column headers 
    $fields = array('ID', 'FullName', 'EMAIL'); 
    fputcsv($f, $fields, $delimiter); 
     
    while($row = $query->fetch_assoc()){ 

        $data = array($row['ID'], $row['FullName'], $row['email']); 
        fputcsv($f, $data, $delimiter); 
    } 
     
    fseek($f, 0); 
     
    // Set headers to download file 
    header('Content-Type: text/csv'); 
    header('Content-Disposition: attachment; filename="' . $filename . '";'); 
    fpassthru($f); 
} 
 
?>

In the above example, you will be able to export csv. You can customize it according to your logic and designing.

Download Source Code

Leave a Comment

Your email address will not be published. Required fields are marked *

 - 
Afrikaans
 - 
af
Albanian
 - 
sq
Amharic
 - 
am
Arabic
 - 
ar
Armenian
 - 
hy
Azerbaijani
 - 
az
Basque
 - 
eu
Belarusian
 - 
be
Bengali
 - 
bn
Bosnian
 - 
bs
Bulgarian
 - 
bg
Catalan
 - 
ca
Cebuano
 - 
ceb
Chichewa
 - 
ny
Chinese (Simplified)
 - 
zh-CN
Chinese (Traditional)
 - 
zh-TW
Corsican
 - 
co
Croatian
 - 
hr
Czech
 - 
cs
Danish
 - 
da
Dutch
 - 
nl
English
 - 
en
Esperanto
 - 
eo
Estonian
 - 
et
Filipino
 - 
tl
Finnish
 - 
fi
French
 - 
fr
Frisian
 - 
fy
Galician
 - 
gl
Georgian
 - 
ka
German
 - 
de
Greek
 - 
el
Gujarati
 - 
gu
Haitian Creole
 - 
ht
Hausa
 - 
ha
Hawaiian
 - 
haw
Hebrew
 - 
iw
Hindi
 - 
hi
Hmong
 - 
hmn
Hungarian
 - 
hu
Icelandic
 - 
is
Igbo
 - 
ig
Indonesian
 - 
id
Irish
 - 
ga
Italian
 - 
it
Japanese
 - 
ja
Javanese
 - 
jw
Kannada
 - 
kn
Kazakh
 - 
kk
Khmer
 - 
km
Korean
 - 
ko
Kurdish (Kurmanji)
 - 
ku
Kyrgyz
 - 
ky
Lao
 - 
lo
Latin
 - 
la
Latvian
 - 
lv
Lithuanian
 - 
lt
Luxembourgish
 - 
lb
Macedonian
 - 
mk
Malagasy
 - 
mg
Malay
 - 
ms
Malayalam
 - 
ml
Maltese
 - 
mt
Maori
 - 
mi
Marathi
 - 
mr
Mongolian
 - 
mn
Myanmar (Burmese)
 - 
my
Nepali
 - 
ne
Norwegian
 - 
no
Pashto
 - 
ps
Persian
 - 
fa
Polish
 - 
pl
Portuguese
 - 
pt
Punjabi
 - 
pa
Romanian
 - 
ro
Russian
 - 
ru
Samoan
 - 
sm
Scots Gaelic
 - 
gd
Serbian
 - 
sr
Sesotho
 - 
st
Shona
 - 
sn
Sindhi
 - 
sd
Sinhala
 - 
si
Slovak
 - 
sk
Slovenian
 - 
sl
Somali
 - 
so
Spanish
 - 
es
Sundanese
 - 
su
Swahili
 - 
sw
Swedish
 - 
sv
Tajik
 - 
tg
Tamil
 - 
ta
Telugu
 - 
te
Thai
 - 
th
Turkish
 - 
tr
Ukrainian
 - 
uk
Urdu
 - 
ur
Uzbek
 - 
uz
Vietnamese
 - 
vi
Welsh
 - 
cy
Xhosa
 - 
xh
Yiddish
 - 
yi
Yoruba
 - 
yo
Zulu
 - 
zu