Export Data to CSV with Date Filter using PHP & MySQL

CSV (comma separated value) is well known file format to store tabular data. In our previous tutorial, we have published tutorial to Export Data to CSV with PHP and MySQL and get huge response from our readers. Many of them requested for tutorial to export data to CSV with date range filter.

So in this tutorial you will learn how to export data to csv file with date range filter using PHP and MySQL.

We will cover this tutorial step by step with live example to all display records with start and end date to select date range to filter data to export into CSV file.

Also, read:


As we will cover this tutorial with live example to to export data to csv file with date range filter using PHP and MySQL, so the major files for this example is following.

  • index.php
  • datepickers.js
  • export.php

Step1: Create MySQL Database Table and Insert Records
First we will create MySQL database table orders to store order records to export into CSV.

CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `cname` varchar(255) NOT NULL,
  `item` varchar(255) NOT NULL,
  `value` double(12,2) NOT NULL,
  `date` date NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

We will insert some records to orders using following insert statement.

INSERT INTO `orders` (`id`, `cname`, `item`, `value`, `date`) VALUES
(1, 'Aston', 'Footbal', 1200.00, '2019-08-14'),
(2, 'Steve', 'Cricket Bat', 800.00, '2019-07-08'),
(3, 'Stephen', 'Java Book', 750.00, '2019-06-29'),
(4, 'Anthony', 'Washing Machine', 11250.00, '2019-05-20'),
(5, 'Victory', 'Shopping Trolley', 200.00, '2019-06-10'),
(6, 'Jessica', 'Sony Camera', 1200.00, '2019-06-06'),
(7, 'White', 'Bike Tires', 2000.00, '2019-05-28'),
(8, 'Richardson', 'Bike', 1600.00, '2019-04-18'),
(9, 'Marco', 'Computer', 1500.00, '2019-05-22'),
(10, 'Illiana', 'Laptop', 2800.00, '2019-06-30'),
(11, 'Smith', 'Sony TV', 1880.00, '2019-05-03'),
(12, 'David', 'iPhone ', 2225.00, '2019-06-01'),
(13, 'McGraw', 'iphone 7', 15620.00, '2019-05-30'),
(14, 'Gary', '3D Printer', 600.00, '2019-06-02'),
(15, 'Sarah', 'Kitchen Appliances', 35.00, '2019-07-29'),
(16, 'Thomas', 'SanDisk 32GB microSDHC', 85.00, '2019-04-05'),
(17, 'Helena', 'Tube Light', 12.00, '2019-05-04'),
(18, 'Nathan', 'Bluetooth', 20.00, '2019-06-07'),
(19, 'Ronald', 'shampoo', 10.00, '2019-06-13'),
(20, 'kristen', 'Mobile charger', 10.00, '2019-06-18');

Step2: Include Boostrap, jQuery, DatePicker Files
We will include Boostrap, jQuery and Boostrap Datepicker library files in index.php file.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<script src="js/datepickers.js"></script>

Step3: Display Records with Date Range Input
In index.php file, we will design to display date range input to pick dates with export button. We will also display records to export from that with date range.


<div class="container">
<h2>Example: Export Data to CSV with Date Filter using PHP</h2>
<br>
<div class="row">
 <form method="post">
  <div class="input-daterange">
   <div class="col-md-4">
	From<input type="text" name="fromDate" class="form-control"
 value="<?php echo date("Y-m-d"); ?>" readonly />
	<?php echo $startDateMessage; ?>
   </div>
   <div class="col-md-3">
	To<input type="text" name="toDate" class="form-control" 
value="<?php echo date("Y-m-d"); ?>" readonly />
	<?php echo $endDate; ?>
   </div>
  </div>
  <div class="col-md-2"><div> </div>
   <input type="submit" name="export" value="Export to CSV" class="btn btn-info" />
  </div>
 </form>
</div>
<div class="row">
	<div class="col-md-8">
		<?php echo $noResult;?>
	</div>
</div>
<br />
<table class="table table-bordered table-striped">
 <thead>
  <tr>
   <th>ID</th>
   <th>Name</th>
   <th>Item</th>
   <th>Price</th>
   <th>Date</th>
  </tr>
 </thead>
 <tbody>
  <?php
  foreach($allOrders as $order) {
   echo '
   <tr>
	<td>'.$order["id"].'</td>
	<td>'.$order["cname"].'</td>
	<td>'.$order["item"].'</td>
	<td>$'.$order["value"].'</td>
	<td>'.$order["date"].'</td>
   </tr>
   ';
  }
  ?>
 </tbody>
</table>
</div>

Step4: Add Bootstrap Date Picker with Range Input
We will implement data picker to input date range using bootstrap-datepicker.js library.

$(document).ready(function(){
 $('.input-daterange').datepicker({
  todayBtn:'linked',
  format: "yyyy-mm-dd",
  autoclose: true
 });
});

Step5: Implement Data Export to CSV with Date Range Filter
In export.php file, we will implement functionality to get date from MySQL database table according to selected date range and export to CSV file.

if(isset($_POST["export"])){
 if(empty($_POST["fromDate"])){
  $startDateMessage = '>label class="text-danger"<Select start date.>/label<';
 }else if(empty($_POST["toDate"])){
  $endDate = '>label class="text-danger"<Select end date.>/label<';
 } else {  
  $orderQuery = "
	SELECT * FROM orders 
	WHERE date <= '".$_POST["fromDate"]."' AND date >= '".$_POST["toDate"]."' ORDER BY date DESC";
  $orderResult = mysqli_query($conn, $orderQuery) or die("database error:". mysqli_error($conn));
  $filterOrders = array();
  while( $order = mysqli_fetch_assoc($orderResult) ) {
	$filterOrders[] = $order;
  }
  if(count($filterOrders)) {
	  $fileName = "phpzag_export_".date('Ymd') . ".csv";
	  header("Content-Description: File Transfer");
	  header("Content-Disposition: attachment; filename=$fileName");
	  header("Content-Type: application/csv;");
	  $file = fopen('php://output', 'w');
	  $header = array("Id", "Name", "Item", "Value", "Date");
	  fputcsv($file, $header);  
	  foreach($filterOrders as $order) {
	   $orderData = array();
	   $orderData[] = $order["id"];
	   $orderData[] = $order["cname"];
	   $orderData[] = $order["item"];
	   $orderData[] = $order["value"];
	   $orderData[] = $order["date"];
	   fputcsv($file, $orderData);
	  }
	  fclose($file);
	  exit;
  }
 }
}

You may also like:

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download


One thought on “Export Data to CSV with Date Filter using PHP & MySQL

  1. Dear Sir,
    Please help me, i’ done the php code (Date Range mysql data export in xls) but i face error in my program.
    This is my code.
    <?php
    require('includes\dbconnection.php');

    // Select query
    $query = "SELECT * FROM tblvisitor where date(EnterDate)
    between 'fromdate' and 'todate' ORDER BY ID asc";

    $res=mysqli_query($con,$query);
    $html='S.NoNameID TypeID NoMobile
    No
    AddressFrom AddressWhom to meet
    DepartmentPurposeIn TimeOut TimeRemarks‘;
    while($row=mysqli_fetch_assoc($res)){
    $html.=”.$row[‘ID’].”.$row[‘FullName’].”.$row[‘IDType’].”.$row[‘IDProof’].”.$row[‘MobileNumber’].’
    ‘.$row[‘Address’].”.$row[‘FrmAddress’].”.$row[‘WhomtoMeet’].’
    ‘.$row[‘Deptartment’].”.$row[‘ReasontoMeet’].”.$row[‘EnterDate’].”.$row[‘outtime’].”.$row[‘remark’].”;
    }
    $html.=”;
    header(‘Content-Type:application/xls’);
    header(‘Content-Disposition:attachment;filename=report.xls’);
    echo $html;
    ?>
    Note: Error is when is click my “Export” button in php form the excel
    file is downloaded successfully but only the header rows only as
    shown no data is pick from my MySql database please help me out.

    Thanks & Regards,
    Ameen MSD.

Comments are closed.