How to export database data into excel in csv format using PHP
Already created database data export is a familiar operation inside phpMyAdmin We have to go phpMyAdmin for a database client in PHP. It provides database administration tools and also allows exporting the data. The exported data can be in various formats like SQL, CSV as selected.
When we want to export data manually then we need a PHP script, that can export database data (records) to an excel file, then this article will help you. It has detailed step by step description with example code.
We have already seen several example tutorial online for implementing database export using PHP. Here we implement simple header for doing this.
What is inside:
First, we are going to create a database named bootstrapfriendly and then create a table named tbl_animal and insert some data to its better understanding.
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
--
-- Table structure for table `tbl_animal`
--
CREATE TABLE `tbl_animal` (
`id` int(11) UNSIGNED NOT NULL,
`common_name` varchar(255) NOT NULL DEFAULT '',
`scientific_name` varchar(255) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `tbl_animal`
--
INSERT INTO `tbl_animal` (`id`, `common_name`, `scientific_name`) VALUES
(1, 'Bison', 'Bos gaurus\r\n'),
(2, 'Black buck', 'Antelope cervicapra'),
(3, 'Chinkara', 'Gazella bennettii'),
(4, 'Nilgai', 'Boselaphus tragocamelus'),
(5, 'Wolf', 'Canis lupus'),
(6, 'Lion', 'Panthera leo'),
(7, 'Elephant', 'Elephas maximus'),
(8, 'Wild Ass', 'Equus africanus asinus'),
(9, 'Panther', 'Panthera pardus'),
(10, 'Kashmir stag', 'Cervus canadensis hanglu'),
(11, 'Peacock', 'Pavo cristatus'),
(12, 'Siberian crane', 'Grus leucogeranus'),
(13, 'Fox', 'Vulpes vulpes'),
(14, 'Rhinoceros', 'Rhinoceros unicornis'),
(15, 'Tiger', 'Panthera Tigris'),
(16, 'Crocodile', 'Crocodylus palustris'),
(17, 'Gavial or Gharial', 'Gavialis gangeticus'),
(18, 'Horse', 'Equus caballus'),
(19, 'Zebra', 'Equus quagga'),
(20, 'Buffalow', 'Babalus bubalis'),
(21, 'Wild boar', 'Sus scrofa'),
(22, 'Arabian camel', 'Camelus dromedaries'),
(23, 'Giraffe', 'GiraffaÊcamelopardalis'),
(24, 'House wall Lizard', 'Hemidactylus flaviviridis'),
(25, 'Hippopotamus', 'Hippopotamus amphibius'),
(26, 'Rhesus monkey', 'Macaca mulatta'),
(27, 'Dog', 'Canis lupus familiaris'),
(28, 'Cat', 'Felis domesticus'),
(29, 'Cheetah', 'Acinonyx jubatus'),
(30, 'Black rat', 'Rattus rattus'),
(31, 'House mouse', 'Mus musculus'),
(32, 'Rabbit', 'Oryctolagus cuniculus'),
(33, 'Great horned owl', 'Bubo virginianus'),
(34, 'House sparrow', 'Passer domesticus'),
(35, 'House crow', 'Corvus splendens'),
(36, 'Common myna', 'Acridotheres tristis'),
(37, 'Indian parrot', 'Psittacula eupatria'),
(38, 'Bulbul', 'Molpastes cafer'),
(39, 'Koel', 'Eudynamis scolopaccus'),
(40, 'Pigeon', 'Columba livia'),
(41, 'Indian Cobra', 'Naja naja'),
(42, 'King cobra', 'Ophiophagus hannah'),
(43, 'Sea snake', 'Hydrophiinae'),
(44, 'Indian python', 'Python molurus'),
(45, 'Rat snake', 'Rat snake');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_animal`
--
ALTER TABLE `tbl_animal`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_animal`
--
ALTER TABLE `tbl_animal`
MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=46;
COMMIT;
Now, we need to creat a connection file for making connectivity with database
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db_name = "bootstrapfriendly";
$conn = mysqli_connect($host, $user, $pass, $db_name);
mysqli_set_charset($conn,"utf8");
if($conn)
{
// echo '<script language="javascript">';
// echo 'alert ("connected")';
// echo '';
}else{
echo '';
echo 'alert ("connection Error")';
echo '';
}
?>
Now we are going to creat a index page where we will fetch data inside a table with export to excel button
index.php
<?php include "include/connection.php"; ?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- fonts -->
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700" rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<!-- <link rel="stylesheet" href="../css/style.css"> -->
<title>Data exporting into excel in csv format</title>
</head>
<body>
<div class="container ">
<div class="row" >
<div class="col-md-8 p-4 ">
<div class="table_outer">
<?php
$query3="SELECT*FROM tbl_animal";
$res3=mysqli_query($conn,$query3);
$num=mysqli_num_rows($res3);
echo "<h3 style='color:#0aad0a'>Hurrah! Total Number of Animal is : ".$num ."</h3>";
?>
<form action="excel_action.php" method="post">
<input type="submit" name="submit" value="Export to Excel" class="btn btn-danger my-3">
</form>
<table class="table table-bordered">
<tr class="bg-primary text-white">
<td><strong> Sn. </strong> </td>
<td><strong> Common name. </strong> </td>
<td><strong> Scirntific name. </strong> </td>
</tr>
<?php
$qry = "SELECT * FROM tbl_animal ORDER BY id ASC";
$result=mysqli_query($conn, $qry); //rs.open sql,con
while ($row=mysqli_fetch_assoc($result))
{ ?>
<tr>
<td><strong> <?php echo $row['id']; ?> </strong> </td>
<td><?php echo $row['common_name']; ?> </td>
<td><?php echo $row['scientific_name']; ?> </td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script >
Now we are going to create a process action php script which will convert database data into CSV format
Here we use a simple header function to do this process
excel_action.php
<?php
if(isset($_POST["submit"])){
include "include/connection.php";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen("php://output", "w");
fputcsv($output, array('id', 'common_name', 'scientific_name'));
$query = "SELECT * FROM tbl_animal";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
}
?>