Showing posts with label CSV. Show all posts
Showing posts with label CSV. Show all posts

Thursday, 7 July 2022

Export MySQL Data to CSV File using Node.js Express


This tutorial on Export Data to CSV file using Node js Express Application and in this tutorial, you will learn how to export data in CSV file from MySQL Database table in Node.js Application.

In our Node Web Application, sometimes we have to export data from MySQL database. So at that time CSV file format is the best option for exporting data from MySQL Database, so for this here in our Node.js Express Application, we will export MySQL data to CSV file using Node.js Application.

So if you have follow this tutorial, then this tutorial will helps you in easy way to exporting mysql database table data in CSV file using Node JS Express framework.

In this Node.js tutorial on export data to CSV file, we will use body-parser and json2csv node module under this node application, and by using this both module we will first export data to CSV file.

  • Fetch data from MySQL and display on Web page in HTML table format using Node.js & MySQL
  • Fetch Data from MySQL table and convert into JSON format
  • Convert JSON data to CSV format using json2csv node module
  • Export MySQL data to CSV file and download CSV file using Node.js

Export MySQL Data to CSV File using Node.js Express

For Export MySQL data to CSV file in Node.js, so you have follow below steps.

  1. MySQL Table Structure
  2. Download and Install Node.js Express framework
  3. Create MySQL Database Connection
  4. Install body-parser & json2csv Module
  5. Create Routes
  6. Create Views File
  7. Check Output in the browser




Step 1 - MySQL Table Structure


For start this tutorial, first we have to create table in MySQL table for export data to CSV file format in Node.js, so for create table in MySQL database, we have to run following script in your phpmyadmin area and it will create sample_data table with pre inserting of sample data and we will export that data to CSV file using Node js.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `sample_data`
--

CREATE TABLE `sample_data` (
  `id` int(10) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL,
  `age` varchar(30) NOT NULL,
  `gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `sample_data`
--

INSERT INTO `sample_data` (`id`, `first_name`, `last_name`, `age`, `gender`) VALUES
(1, 'John', 'Smith', '26', 'Male'),
(2, 'Donna', 'Hubber', '24', 'Female'),
(3, 'Peter', 'Parker', '28', 'Male'),
(4, 'Tom ', 'Muddy', '28', 'Male'),
(5, 'Desmond', 'Taylor', '36', 'Male'),
(6, 'Willie', 'Hudson', '24', 'Male'),
(7, 'Harold', 'Avila', '29', 'Male'),
(8, 'Kathryn', 'Moon', '22', 'Female'),
(9, 'Maria', 'Brewer', '26', 'Female'),
(10, 'Carma', 'Holland', '25', 'Female'),
(11, 'Patrick', 'Michel', '32', 'Male');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `sample_data`
--
ALTER TABLE `sample_data`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_data`
--
ALTER TABLE `sample_data`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;





Step 2 - Download and Install Node.js Express framework


In this Node.js tutorial, we have use Express.js Framework, So first we need to download and install Node.js Express framework. So for this, first we have to go into directory in which we have run our node code and under that directory, we have to create csv_export directory and then after we have goes into that directory, so for this, we have to run following command.


mkdir csv_export
cd csv_export


Once we have goes into csv_export directory, now first we wan to download and install node express genderator, so for this, in the command prompt we have to run following command, which will download and install node.js express generator.


npm install -g express-generator


Next we want to download and install node.js express framework, so for this in the command prompt we have to run following command which will download and install node.js express framework under autocomplete directory.


npx express --view=ejs


In this downloaded Node.js Express framework, we have use ejs template engine for display HTML output in the browser and once we have run this command then it will display following node.js express directory structure which you can seen below.


create : public\
   create : public\javascripts\
   create : public\images\
   create : public\stylesheets\
   create : public\stylesheets\style.css
   create : routes\
   create : routes\index.js
   create : routes\users.js
   create : views\
   create : views\error.ejs
   create : views\index.ejs
   create : app.js
   create : package.json
   create : bin\
   create : bin\www

   install dependencies:
     > npm install

   run the app:
     > SET DEBUG=crud:* & npm start


And lastly under node.js express download and install process we have to run following command for install required node.js default module for express framework.


npm install


After run above command, so here our Node.js Express download and install process is completed.

Step 3 - Create MySQL Database Connection


After download and install Node.js Express framework, now we want to connect this applicatioin with MySQL Database, so for make MySQL database connection, first we have to download node mysql module. So for this, we have to run following command in command prompt.


npm install mysql


Once Node Mysql module has been install in our node express application, next we need to create one database.js file for create mysql database connection, and under this file, we have to define MySQL database configuration for connection node express application with MySQL database.

database.js

const mysql = require('mysql');

var connection = mysql.createConnection({
	host : 'localhost',
	database : 'testing',
	user : 'root',
	password : ''
});

connection.connect(function(error){
	if(error)
	{
		throw error;
	}
	else
	{
		console.log('MySQL Database is connected Successfully');
	}
});

module.exports = connection;


Step 4 - Install body-parser & json2csv Module


In this Node tutorial for Export data to CSV, here we need to download some extra node module like body-parser and json2csv module. So for download this module, we have goes to command prompt and run following command.


npm install body-parser json2csv --save


In this above command json2csv module has been used for convert a JSON data to CSV data and convert CSV data to JSON format.

And body-parser module is a npm library which has been process data and send that data to HTTP request body.

So by isntalling this both module under this Node Express framework, we can able to export MySQL database to CSV file format.

Step 5 - Create Routes


In the Node Express framework, routes file has been used for handle HTTP request. Here when we have download express framework, then you will get index.js default files under routes directory.

Here we have to open routes/index.js file and under this file, we have to include database connection file and json2csv node module also.

After this, in the main route which has been load views/index.ejs file for display output in the browser. So when file has been load then it will fetch data from MySQL table and display data on the web page in HTML table format.

And for handle request for export data to csv file, we have to create another route and under that route first it will fetch data from mysql table, and convert that data into JSON format and lasly by using json2csv module it will convert json data to csv format and downlaod csv file in local computer.

routes/index.js

var express = require('express');
var router = express.Router();

var database = require('../database');

var data_exporter = require('json2csv').Parser;

/* GET home page. */
router.get('/', function(req, res, next) {

    database.query('SELECT * FROM sample_data', function(error, data){

        res.render('index', { title: 'Express', sample_data:data });

    });
    
});

router.get('/export', function(request, response, next){

    database.query('SELECT * FROM sample_data', function(error, data){

        var mysql_data = JSON.parse(JSON.stringify(data));

        //convert JSON to CSV Data

        var file_header = ['First Name', 'Last Name', 'Age', 'Gender'];

        var json_data = new data_exporter({file_header});

        var csv_data = json_data.parse(mysql_data);

        response.setHeader("Content-Type", "text/csv");

        response.setHeader("Content-Disposition", "attachment; filename=sample_data.csv");

        response.status(200).end(csv_data);

    });

});

module.exports = router;


Step 6 - Create Views File


In the Node.js Express framework, views directory file has been used for display html output in the browser. In this tutorial, we have use EJS template engine for display HTML output in the browser. Here we will use views/index.ejs default file, and under this file, first we will display mysql data in html table format and then after, we have to create on link for export data to csv file which will send http get request to routes for export data to csv file in Node.js Express application.

views/index.ejs

<!doctype html>
<html lang="en">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

        <title>How to Export MySQL Data to CSV in Node.js</title>
    </head>
    <body>
        <div class="container">
            <h1 class="text-center text-primary mt-3 mb-3">How to Export MySQL Data to CSV in Node.js</h1>

            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col-md-10">Sample Data</div>
                        <div class="col-md-2">
                            <a href="/export" class="btn btn-success btn-sm float-end">Export to CSV</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                        
                    <table class="table table-bordered">
                        <tr>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Age</th>
                            <th>Gender</th>
                        </tr>
                        <% sample_data.forEach(function(data){ %>
                        <tr>
                            <td><%= data.first_name %></td>
                            <td><%= data.last_name %></td>
                            <td><%= data.age %></td>
                            <td><%= data.gender %></td>
                        </tr>
                        <% }); %>
                    </table>

                </div>
            </div>
        </div>
  </body>
</html>


Step 7 - Check Output in the browser


Once we have follow all above step, so we are able to check output in the browser. So for check output in the browser, first we have goes to command prompt and run following command.


npm start


This command will start Node.js server and then after we can goes to browser and following URL.


http://localhost:3000/


So once we have hit above url then it will display MySQL table data on web page in HTML table format and above this data, we can see on export button. So when we have click on export button then it will export mysql data into CSV file format using Node js express application.





Friday, 16 October 2020

How to Convert CSV to JSON in PHP


This is simple and short tutorial on How do we convert CSV file data into JSON format in PHP. In this world of web programming, sometimes we have to make feature like fetch data from CSV file and insert that CSV file data into Mysql database then at that time we have need to convert CSV to JSON. The main purpose of this tutorial is to learn how can we easy way to convert CSV data or file to JSON object using PHP script.

Advantages of CSV


  1. CSV files can be opened or edited by text editors like notepad.
  2. In data-warehouse, CSV follows a reasonably flat, simple schema.
  3. Any programing language to parse CSV data is trivial, generating it's extremely easy.
  4. CSV is safe and may clearly differentiate between the numeric values and text. CSV doesn't manipulate data and stores it as-is.
  5. In CSV, you write column headers just one occasion where as in Excel, you've got to possess a start tag and end tag for every column in each row.
  6. Importing CSV files are often much faster, and it also consumes less memory.
  7. It's easy to programmatically manipulate CSV since, after all, they're simple text files.
  8. CSV are often opened with any text editor in Windows like notepad, MS Excel, Microsoft Works 9, etc.

Advantages of JSON


  1. JSON is a portable that means it can be parse and write are available in many programming languages like JavaScript.
  2. By using JSON we can online transfer large data from source to destination in the form of array or objects.
  3. IN JSON we can transfer data in plain text or unformatted data like comma speratted or delimited data.
  4. JSON is better that XML, this is because it has more sufficient space than XML data structure.
  5. JSON has no tag name and it has structure which is nested braces instead of verbose tags.
  6. In exchange of data JSON is faster than XML.


So here we have seen benefits of CSV and JSON data and both are mainly used for data exchange. But if you have work on any web services than JSON data is mostly used for transmit or exchange of data on the web. So if you have data in CSV file and you have to exchange that data then you must convert that data into JSON format and you can easily exchange data online.

In PHP language there many functions are available for parse or read data from CSV file and then convert that data into PHP array and lastly for convert data into JSON then we can use json_encode() function.



Sample Input CSV Data



Company Name,Address,City,State,ZIP/PIN CODE,Country,Website,Industry,First Name,Last Name,Phone Number,Designation,Email
Cougar Investment,3570 Thunder Road,Mountain View,CA,94041,USA,dealtechs.com,Animal care and service worker,Devin,Taylor,650-564-1816,Animal care and service worker,DevinRTaylor@armyspy.com
Robert Hall,1729 Lyndon Street,Slatington,PA,18080,USA,toksalgida.com,Media,Ruby,Gibson,610-767-5251,News anchor,RubyBGibson@armyspy.com



index.php



<?php

$error = '';

if(isset($_POST["upload_file"]))
{
  if($_FILES['file']['name'])
  {
    $file_array = explode(".", $_FILES['file']['name']);

    $file_name = $file_array[0];

    $extension = end($file_array);

    if($extension == 'csv')
    {
      $column_name = array();

      $final_data = array();

      $file_data = file_get_contents($_FILES['file']['tmp_name']);

      $data_array = array_map("str_getcsv", explode("\n", $file_data));

      $labels = array_shift($data_array);

      foreach($labels as $label)
      {
        $column_name[] = $label;
      }

      $count = count($data_array) - 1;

      for($j = 0; $j < $count; $j++)
      {
        $data = array_combine($column_name, $data_array[$j]);

        $final_data[$j] = $data;
      }

      header('Content-disposition: attachment; filename='.$file_name.'.json');

      header('Content-type: application/json');

      echo json_encode($final_data);

      exit;
    }
    else
    {
      $error = 'Only <b>.csv</b> file allowed';
    }
  }
  else
  {
    $error = 'Please Select CSV File';
  }
}

?>

<!DOCTYPE html>
<html>
  	<head>
    	<title>Convert CSV to JSON using PHP</title>
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
    	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  	</head>
  	<body>
  		<div class="container">
  			<br />
  			<br />
    		<h1 align="center">Convert CSV to JSON using PHP</h1>
    		<br />
    		<div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <?php
            if($error != '')
            {
              echo '<div class="alert alert-danger">'.$error.'</div>';
            }
            ?>
            <form method="post" enctype="multipart/form-data">
              <div class="col-md-6" align="right">Select File</div>
              <div class="col-md-6">
                <input type="file" name="file" />
              </div>
              <br /><br /><br />
              <div class="col-md-12" align="center">
                <input type="submit" name="upload_file" class="btn btn-primary" value="Upload" />
              </div>
            </form>
          </div>
        </div>
    	</div>
    	
  	</body>
</html>



Output JSON Data



[
  {
    "Company Name": "Cougar Investment",
    "Address": "3570 Thunder Road",
    "City": "Mountain View",
    "State": "CA",
    "ZIP/PIN CODE": "94041",
    "Country": "USA",
    "Website": "dealtechs.com",
    "Industry": "Animal care and service worker",
    "First Name": "Devin",
    "Last Name": "Taylor",
    "Phone Number": "650-564-1816",
    "Designation": "Animal care and service worker",
    "Email": "DevinRTaylor@armyspy.com"
  },
  {
    "Company Name": "Robert Hall",
    "Address": "1729 Lyndon Street",
    "City": "Slatington",
    "State": "PA",
    "ZIP/PIN CODE": "18080",
    "Country": "USA",
    "Website": "toksalgida.com",
    "Industry": "Media",
    "First Name": "Ruby",
    "Last Name": "Gibson",
    "Phone Number": "610-767-5251",
    "Designation": "News anchor",
    "Email": "RubyBGibson@armyspy.com"
  }
]



Friday, 19 June 2020

Import Selected CSV File Column in PHP using Ajax jQuery



On the web, we have seen lots of articles or tutorial on How to import CSV file data into Mysql Database by using PHP script. But there are none of the tutorials has define how can we define particular CSV file column data at the time of importing file, and that selected column data has been imported into Mysql table by using PHP script with Ajax jQuery. For solve the problem of CSV file Column Mapping here we have make this tutorial in which we have step by step describe the process of CSV file column mapping in PHP using Ajax jQuery.

This tutorial has divided in following different part.
  • Make Upload Form for Select CSV File
  • Convert CSV File into HTML Table
  • Write jQuery Code for Column Selection
  • Import Select Column Data



Before we have going to step, first we must have to see our database structure. So below you can find this tutorial Mysql table definition.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `csv_file`
--

CREATE TABLE `csv_file` (
  `id` int(11) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `csv_file`
--
ALTER TABLE `csv_file`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `csv_file`
--
ALTER TABLE `csv_file`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;


Here in this Mysql table there is only three column in which we want to import CSV file data. Now below we have to CSV file structure.


Company Name,First Name,Last Name,Address,City,State,ZIP/PIN CODE,Country,Phone Number,Email
Prestiga-Biz,Barbara,Motes,3029 Harrison Street,Oakland,CA,94612,USA,415-481-0998,barbarapmotes@armyspy.com
McDade's,Paul,Minter,1376 Orphan Road,Long Lake,WI,54542,USA,715-967-2332,paulcminter@rhyta.com
Penn Fruit,Robin,Morton,4609 Eastland Avenue,Jackson,MS,39211,USA,601-348-3248,robinamorton@armyspy.com
Frank's Nursery & Crafts,Alvin,Sarvis,83 Star Trek Drive,Pensacola,FL,32501,USA,850-356-1961,AlvinMSarvis@armyspy.com
Media Play,Daniel,Retana,1114 Bel Meadow Drive,Arrowhead,CA ,92352,USA,909-336-8296,DanielSRetana@teleworm.us
Cut Rite,Eva,Tallent,4138 Shadowmar Drive,Metairie,LA,70006,USA,504-779-1200,EvaTTallent@dayrep.com
Matrix Design,Charles,Astorga,410 Westwood Avenue,Garden City,NY ,11530,USA,516-805-0092,CharlesAAstorga@armyspy.com
Century House,Jane,Lim,2305 Reppert Coal Road,Southfield,MI,48075,USA,586-970-6260,JanePLim@armyspy.com
Life's Gold,Tom,Garcia,518 Seth Street,Gustine,TX,76455,USA,325-667-9370,TomKGarcia@armyspy.com
Two Pesos,Aaron,Lovejoy,2448 Settlers Lane,New York,NY,10007,USA,917-826-2371,AaronRLovejoy@armyspy.com
Smitty's Marketplace,Susan,Reyes,4402 Stuart Street,Sewickley,PA,15143,USA,724-417-4584,SusanDReyes@armyspy.com
Waves Music,Susan,Jackson,1196 Archwood Avenue,Cheyenne,WY,82003,USA,307-871-1265,SusanRJackson@rhyta.com
Realty Depot,Mary,Shepard,2632 Scott Street,Poughkeepsie,NY,12601,USA,845-471-7357,MaryEShepard@armyspy.com
Martin's,Sadie,Hill,148 Peaceful Lane,Warrensville Heights,OH,44128,USA,216-390-5580,SadieAHill@dayrep.com
Wickes Furniture,Stephen,Flynn,4378 Jenna Lane,Ames,IA,50010,USA,515-233-9027,StephenJFlynn@teleworm.us
Larry's Markets,Beth,Holloway,3915 Essex Court,South Burlington,VT,5403,USA,802-272-7414,BethHHolloway@rhyta.com
Handy Dan,Mildred,Hoyt,2626 Johnstown Road,Cary,IL,60013,USA,847-462-6919,MildredAHoyt@armyspy.com
Laura Ashley Mother & Child,Karen,Walker,3659 Shingleton Road,Portage,MI,49002,USA,269-327-9698,KarenBWalker@rhyta.com
Harmony House,Lucille,Wilson,644 Villa Drive,South Bend,IN,46601,USA,574-303-6598,LucilleZWilson@jourrapide.com
Suadela Investment,Jimmie,Cornwell,2533 Melody Lane,Lively,VA,22503,USA,804-462-5048,JimmieMCornwell@jourrapide.com
American Appliance,Marion,Davis,2905 Denver Avenue,City Of Commerce,CA,90040,USA,951-314-7204,MarionVDavis@armyspy.com
The Warner Brothers Store,Sonia,Johnson,1510 Bel Meadow Drive,Los Angeles,CA,90017,USA,909-269-6784,SoniaCJohnson@jourrapide.com
Gart Sports,Brandy,Voyles,2538 Broadcast Drive,Washington,VA,20011,USA,703-956-0582,BrandyRVoyles@rhyta.com
Irving's Sporting Goods,Deborah,Gossard,2655 Ashton Lane,Austin,TX,78756,USA,512-465-9149,DeborahGGossard@rhyta.com
Yardbirds Home Center,Dawn,Guerrero,753 Saints Alley,Tampa,FL,33614,USA,813-787-0466,DawnAGuerrero@teleworm.us
Multicerv,Priscilla,Holloway,4957 Custer Street,Smethport,PA,16749,USA,814-887-3339,PriscillaRHolloway@armyspy.com
Colonial Stores,Jay,Crowder,4281 Ryder Avenue,Bellevue,WA,98004,USA,425-384-6261,JayECrowder@dayrep.com
Balanced Fortune,Ashley,Hemphill,2042 Olen Thomas Drive,Rosston,TX,76263,USA,940-768-7053,AshleyJHemphill@jourrapide.com
Lee Wards,Debra,Harrington,532 Seltice Way,Kellogg,ID,83837,USA,208-783-0049,DebraFHarrington@armyspy.com
Garden Guru,Anna,Brooks,1332 Brown Street,San Francisco,CA,94124,USA,925-999-9078,AnnaEBrooks@rhyta.com



So, Above we can see that there is 10 column in CSV file. Now we have to make feature like when we have upload CSV file file then we can define three column and only three column data must be import into above Mysql table. So below you can find the solution of CSV file column mapping in PHP script using Ajax jQuery.



1 - Make Upload Form for Select CSV File


For make CSV file column mapping script. So first we have to make One upload form for select CSV file from our local computer. After creating HTML form for upload csv file. Then after we have to write jquery code and in that code we have make Ajax call which will send CSV file to server script. Below you can find the source code of this steps.

index.php



<!DOCTYPE html>
<html>
   <head>
     <title>CSV Column Mapping in PHP</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <style>
      .table tbody tr th
      {
        min-width: 200px;
      }

      .table tbody tr td
      {
        min-width: 200px;
      }

      </style>
   </head>
   <body>
    <div class="container">
     <br />
     <br />
      <h1 align="center">CSV Column Mapping in PHP</h1>
      <br />
        <div id="message"></div>
      <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <div class="row" id="upload_area">
              <form method="post" id="upload_form" enctype="multipart/form-data">
                <div class="col-md-6" align="right">Select File</div>
                <div class="col-md-6">
                  <input type="file" name="file" id="csv_file" />
                </div>
                <br /><br /><br />
                <div class="col-md-12" align="center">
                  <input type="submit" name="upload_file" id="upload_file" class="btn btn-primary" value="Upload" />
                </div>
              </form>
              
            </div>
            <div class="table-responsive" id="process_area">

            </div>
          </div>
        </div>
     </div>
     
   </body>
</html>

<script>
$(document).ready(function(){

  $('#upload_form').on('submit', function(event){

    event.preventDefault();
    $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      dataType:'json',
      contentType:false,
      cache:false,
      processData:false,
      success:function(data)
      {
        if(data.error != '')
        {
          $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
          $('#process_area').html(data.output);
          $('#upload_area').css('display', 'none');
        }
      }
    });

  });

});
</script>






2 - Convert CSV File into HTML Table


In second steps, First we have to check user has select file or not. If User has select file then we have to check selected file is .csv file or not if selected file is CSV file then we have to fetch data from CSV file. From this first line of csv file, we have to count total number of column of CSV file and based on that column we have to make select box for column selection for all column in html table format. After this all csv file data has been store in SESSION variable for future use of import data and top five row of CSV file has been convert into HTML table. After this we have to make import button and append that button code in HTML table code and send whole data to Ajax request in json string format.




upload.php



<?php

//upload.php

session_start();

$error = '';

$html = '';

if($_FILES['file']['name'] != '')
{
 $file_array = explode(".", $_FILES['file']['name']);

 $extension = end($file_array);

 if($extension == 'csv')
 {
  $file_data = fopen($_FILES['file']['tmp_name'], 'r');

  $file_header = fgetcsv($file_data);

  $html .= '<table class="table table-bordered"><tr>';

  for($count = 0; $count < count($file_header); $count++)
  {
   $html .= '
   <th>
    <select name="set_column_data" class="form-control set_column_data" data-column_number="'.$count.'">
     <option value="">Set Count Data</option>
     <option value="first_name">First Name</option>
     <option value="last_name">Last Name</option>
     <option value="email">Email</option>
    </select>
   </th>
   ';
  }

  $html .= '</tr>';

  $limit = 0;

  while(($row = fgetcsv($file_data)) !== FALSE)
  {
   $limit++;

   if($limit < 6)
   {
    $html .= '<tr>';

    for($count = 0; $count < count($row); $count++)
    {
     $html .= '<td>'.$row[$count].'</td>';
    }

    $html .= '</tr>';
   }

   $temp_data[] = $row;
  }

  $_SESSION['file_data'] = $temp_data;

  $html .= '
  </table>
  <br />
  <div align="right">
   <button type="button" name="import" id="import" class="btn btn-success" disabled>Import</button>
  </div>
  <br />
  ';
 }
 else
 {
  $error = 'Only <b>.csv</b> file allowed';
 }
}
else
{
 $error = 'Please Select CSV File';
}

$output = array(
 'error'  => $error,
 'output' => $html
);

echo json_encode($output);


?>



3 - Write jQuery Code for Column Selection


Once selected CSV file data has been uploaded and after this convert that file data into html table format and display on web page. Now in third step we have to write jquery code for validate column selection or mapping. So, we have to write jquery script, firts it will check user must have to select at least three column this is because in database there is three column in which we want to import data. If user select less than or greater than three column then import button will be disabled, but if user select three different column then import button will enable. jQuery will also check user must define define unique column as per Mysql table, if user select two column from html table with same Mysql table then also import button will disable. All unique column select box option we have to store in variable, and this variable value we will be used for define column number at the time of importing of data. So this validation will check in this part of jQuery script.



index.php



<!DOCTYPE html>
<html>
   <head>
     <title>CSV Column Mapping in PHP</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <style>
      .table tbody tr th
      {
        min-width: 200px;
      }

      .table tbody tr td
      {
        min-width: 200px;
      }

      </style>
   </head>
   <body>
    <div class="container">
     <br />
     <br />
      <h1 align="center">CSV Column Mapping in PHP</h1>
      <br />
        <div id="message"></div>
      <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <div class="row" id="upload_area">
              <form method="post" id="upload_form" enctype="multipart/form-data">
                <div class="col-md-6" align="right">Select File</div>
                <div class="col-md-6">
                  <input type="file" name="file" id="csv_file" />
                </div>
                <br /><br /><br />
                <div class="col-md-12" align="center">
                  <input type="submit" name="upload_file" id="upload_file" class="btn btn-primary" value="Upload" />
                </div>
              </form>
              
            </div>
            <div class="table-responsive" id="process_area">

            </div>
          </div>
        </div>
     </div>
     
   </body>
</html>

<script>
$(document).ready(function(){

  $('#upload_form').on('submit', function(event){

    event.preventDefault();
    $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      dataType:'json',
      contentType:false,
      cache:false,
      processData:false,
      success:function(data)
      {
        if(data.error != '')
        {
          $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
          $('#process_area').html(data.output);
          $('#upload_area').css('display', 'none');
        }
      }
    });

  });

  var total_selection = 0;

  var first_name = 0;

  var last_name = 0;

  var email = 0;

  var column_data = [];

  $(document).on('change', '.set_column_data', function(){

    var column_name = $(this).val();

    var column_number = $(this).data('column_number');

    if(column_name in column_data)
    {
      alert('You have already define '+column_name+ ' column');

      $(this).val('');

      return false;
    }

    if(column_name != '')
    {
      column_data[column_name] = column_number;
    }
    else
    {
      const entries = Object.entries(column_data);

      for(const [key, value] of entries)
      {
        if(value == column_number)
        {
          delete column_data[key];
        }
      }
    }

    total_selection = Object.keys(column_data).length;

    if(total_selection == 3)
    {
      $('#import').attr('disabled', false);

      first_name = column_data.first_name;

      last_name = column_data.last_name;

      email = column_data.email;
    }
    else
    {
      $('#import').attr('disabled', 'disabled');
    }

  });
  
});
</script>



4 - Import Select Column Data


This is last part of CSV file column mapping tutorial and in this part we have to import selected CSV file column data into Mysql table. In third part, we have write jQuery script and define three column with unique option. Now in this part, we have to write jQuery script in which we have to make Ajax call which will send local variable in which we have store column number which has been get in third part. Based on this variable column number at PHP script will import only that column data into Mysql table. At PHP script CSV file data will be get from SESSION variable in which we have store CSV file data in second steps.




index.php



<!DOCTYPE html>
<html>
   <head>
     <title>CSV Column Mapping in PHP</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <style>
      .table tbody tr th
      {
        min-width: 200px;
      }

      .table tbody tr td
      {
        min-width: 200px;
      }

      </style>
   </head>
   <body>
    <div class="container">
     <br />
     <br />
      <h1 align="center">CSV Column Mapping in PHP</h1>
      <br />
        <div id="message"></div>
      <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <div class="row" id="upload_area">
              <form method="post" id="upload_form" enctype="multipart/form-data">
                <div class="col-md-6" align="right">Select File</div>
                <div class="col-md-6">
                  <input type="file" name="file" id="csv_file" />
                </div>
                <br /><br /><br />
                <div class="col-md-12" align="center">
                  <input type="submit" name="upload_file" id="upload_file" class="btn btn-primary" value="Upload" />
                </div>
              </form>
              
            </div>
            <div class="table-responsive" id="process_area">

            </div>
          </div>
        </div>
     </div>
     
   </body>
</html>

<script>
$(document).ready(function(){

  $('#upload_form').on('submit', function(event){

    event.preventDefault();
    $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      dataType:'json',
      contentType:false,
      cache:false,
      processData:false,
      success:function(data)
      {
        if(data.error != '')
        {
          $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
          $('#process_area').html(data.output);
          $('#upload_area').css('display', 'none');
        }
      }
    });

  });

  var total_selection = 0;

  var first_name = 0;

  var last_name = 0;

  var email = 0;

  var column_data = [];

  $(document).on('change', '.set_column_data', function(){

    var column_name = $(this).val();

    var column_number = $(this).data('column_number');

    if(column_name in column_data)
    {
      alert('You have already define '+column_name+ ' column');

      $(this).val('');

      return false;
    }

    if(column_name != '')
    {
      column_data[column_name] = column_number;
    }
    else
    {
      const entries = Object.entries(column_data);

      for(const [key, value] of entries)
      {
        if(value == column_number)
        {
          delete column_data[key];
        }
      }
    }

    total_selection = Object.keys(column_data).length;

    if(total_selection == 3)
    {
      $('#import').attr('disabled', false);

      first_name = column_data.first_name;

      last_name = column_data.last_name;

      email = column_data.email;
    }
    else
    {
      $('#import').attr('disabled', 'disabled');
    }

  });

  $(document).on('click', '#import', function(event){

    event.preventDefault();

    $.ajax({
      url:"import.php",
      method:"POST",
      data:{first_name:first_name, last_name:last_name, email:email},
      beforeSend:function(){
        $('#import').attr('disabled', 'disabled');
        $('#import').text('Importing...');
      },
      success:function(data)
      {
        $('#import').attr('disabled', false);
        $('#import').text('Import');
        $('#process_area').css('display', 'none');
        $('#upload_area').css('display', 'block');
        $('#upload_form')[0].reset();
        $('#message').html("<div class='alert alert-success'>"+data+"</div>");
      }
    })

  });
  
});
</script>


import.php



<?php

//import.php

if(isset($_POST["first_name"]))
{
 $connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

 session_start();

 $file_data = $_SESSION['file_data'];

 unset($_SESSION['file_data']);

 foreach($file_data as $row)
 {
  $data[] = '("'.$row[$_POST["first_name"]].'", "'.$row[$_POST["last_name"]].'", "'.$row[$_POST["email"]].'")';
 }

 if(isset($data))
 {
  $query = "
  INSERT INTO csv_file 
  (first_name, last_name, email) 
  VALUES ".implode(",", $data)."
  ";

  $statement = $connect->prepare($query);

  if($statement->execute())
  {
   echo 'Data Imported Successfully';
  }
 }
}



?>


So, In this tutorial, we have step by step sees how can we map CSV file column or define CSV file column and then after we have import or insert that define or selected column data into Mysql table by using PHP with Ajax jQuery. IF you have find any simple way for map csv file column in PHP then you are welcome and Let us know in the comments section.

Friday, 29 May 2020

Add CSV Excel Export Button in Laravel Yajra Datatable



This is one more post on Yajra Laravel Datatables package and in this post, we will learn How to add export buttons to Yajra Laravel Datatables package. If you are using Laravel framework as your web application development task. So, in Laravel framework if you want to use jQuery Datatable plugin for display data on web page in tabular format with searching of data, pagination and data sorting feature. For all those things you have to use Yajra Datatables package in Laravel framework. By using this package you can perform server-side processing of searching, sorting and pagination of data without writing any line of code.

So, If you want to export Yajra DataTable data in excel or csv file format, then you have to add csv and excel export button in your DataTable. In Laravel framework, Yajra Datatables package has provide DataTable Buttons plugin for add export button in your Laravel Datatable. After adding of export button, you can easily export your Laravel DataTable data to CSV file or Excel sheet file format without writing any line of code. So, If want to learn How to add export button in Yajra Laravel Datatable, then you have to follow below step. After following below steps you can easily integrate csv excel export button with your Yajra Laravel Datatable and you can simply export your datatable data in csv or excel file format.

  1. Download Latest Version of Laravel Framework
  2. Make MySql Database Connection
  3. Generate Fake Data
  4. Install Yajra DataTables Package
  5. Create DataTable Class
  6. Create Controller Class
  7. Create View Blade File
  8. Set Route
  9. Run Laravel Application



1 - Download Latest Version of Laravel Framework


First we have to download latest version of Laravel framework, So If you have use window OS then you have to go command prompt in which Composer application must be installed and then after write following command.


composer create-project --prefer-dist laravel/laravel export


This command will make export folder in define directory, download and install latest version of Laravel framework.

2 - Make MySql Database Connection


After downloading of Laravel framework, first want to make database connection. For this we have to open Laravel framework .env file and in that file we have to define Mysql database configuration.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


3 - Generate Fake Data


After making of Mysql Database connection, now we want to make table in mysql databaes connection and then after we want to fill that table with fake data. For this we have to follow following steps.

  • Create Model Class
  • Migrate Table Defination to Database
  • Create Factory Class
  • Create Seed Class

Create Model Class


Here we will use Model class for perform database related operation. For this, we have to create model class file. For this we have to go command prompt and write following command.


php artisan make:model Export -m


This command will make Export.php model class file in app folder. In this file we have to define table column name which you can find below.

app/Export.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Export extends Model
{
    protected $fillable = ['firstName', 'lastName'];
}



Migrate Table Defination to Database


When we have create model class, then at that time that model class migration table file has been created in database/migrations folder. In that file, we have to define table column defination which you can seen below.


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateExportsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('exports', function (Blueprint $table) {
            $table->id();
            $table->string('firstName');
            $table->string('lastName');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('exports');
    }
}



After define table defination, now we want to migrate this table defination to mysql database and create exports table. For this we have go to command prompt and write following command.


php artisan migrate


Above command will make exports table in Mysql database. So, this way we can create table in mysql database from Laravel our laravel application.

Create Factory Class


For generate fake data and fill mysql exports table with fill data, we have to create one factory class. This class will allowed you to build fake data for your modelds. For create model factories, we have to go command prompt and write following command.


php artisan make:factory ExportFactory


This command will create model factories with name ExportFactory.php in database/factories folder. In this file, first we have import our model class and then after we have to define in which mysql table column we have to define fake data column name which can find below.

database/factories/ExportFactory.php

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Model;
use Faker\Generator as Faker;
use App\Export;

$factory->define(App\Export::class, function (Faker $faker) {
    return [
        'firstName'  => $faker->firstName,
        'lastName'  => $faker->lastName
    ];
});



Create Seed Class


In Laravel Seed classes is used for seeding your database with test data. In Laravel framework all seed classes has been store in database/seeds folder. For create seed class, we have to command prompt and write following command.


php artisan make:seeder ExportTableSeeder


This command will create ExportTableSeeder.php seed class in database/seeds directory. In this class first we want to import our model class then after in this class you can find run() and under this method we can define how many number of fake data has been genrated by using model factory class. You can find source below it.

database/seeds/ExportTableSeeder.php

<?php

use Illuminate\Database\Seeder;
use App\Export;

class ExportTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $count = 500;
        factory(Export::class, $count)->create();

    }
}



After this we have to open database/seeds/DatabaseSeeder.php file which is already created under this database/seeds directory. So we have to open this file and under this file we can find run() method and under that method we have to called ExportTableSeeder class.

database/seeds/DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UserSeeder::class);
        $this->call(ExportTableSeeder::class);
    }
}



After this for generate fake data, we have to go command prompt and write following command.


composer dump-autoload


This command will regenerates the list of all classed which we have included in this Laravel project. Running of this command is required for generate fake data. And lastly for generate fake data we have to run following command.


php artisan db:seed


This command will seed your test data and it will fill exports mysql table with fake data. So, this is complete step by step process for creating fake data in Laravel framework.




4 - Install Yajra DataTables Package & DataTables Buttons plugin


Here we have use Yajra Datatables package has been used for load data in jQuery Datatable plugin in Laravel framework. For use Yajra Datatable package, we have to install in Laravel framework. For this we have go to command prompt and write following command.


composer require yajra/laravel-datatables-oracle


This command will download and install in latest version of Yajra DataTable package in Laravel framework. Here we want to add export button in Yajra Laravel Datatable, for this we have to download and intall Datatable Button plugin. For this we have to go command prompt and write followng command.


composer require yajra/laravel-datatables-buttons


This command will download and install DataTables Button plugin of Yajra Datatable package. By using this plugin we can add export button Yajra DataTables for export data for Datatable. Now we want to yajra datatable package service in Laravel framework. For this we have to open config/app.php file and under this file in provider array we have to define this two package service, which you can see below.

config/app.php

<?php

return [

    'providers' => [
      
     ---------------
        
        Yajra\DataTables\DataTablesServiceProvider::class,
        Yajra\DataTables\ButtonsServiceProvider::class,

      ---------------

    ],
];



After defining of service, now we want to publish DataTable Button service, for this we have go to command prompt and write following command.


php artisan vendor:publish --tag=datatables-buttons


This command will publish datatables buttons plugin service in Laravel. Now we can use datatables buttons in Laravel framework for add export button Datatable.

5 - Create DataTable Class


In this tutorial, we will use DataTable class for load data in jQuery Datatable plugin and add export button in DataTable for export data in CSV or Excel file. For this we have to create DataTable class, for this we have go to command prompt and write following command.


php artisan datatables:make ExportDataTable


This command will make DataTables/ExportDataTable.php class file in app directory. So, we have to open this file, and in this class file we have to import model class. In this class file, we can see following method.

dataTable($query) - This method will build DataTable class.
query(ExportDataTable $model) - This method is used for get the query source of DataTable. In this method we have define data fetch query.
html() - This method will build your html code and Ajax jQuery script for initialize jQuery Datatable plugin. In this method we can define which export button you want to add in Datatable.
getColumns() - In this method we have to define Mysql table column name.
filename() - This method is used for get the file name for export.

app/DataTables/ExportDataTable.php

<?php

namespace App\DataTables;

use App\Export;
use App\DataTables\ExportDataTable;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;

class ExportDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query);
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\ExportDataTable $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(ExportDataTable $model)
    {
        //return $model->newQuery();
        $data = Export::select();
        return $this->applyScopes($data);
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->dom('Bfrtip')
                    ->orderBy(1)
                    ->buttons(
                        Button::make('csv'),
                        Button::make('excel')
                    );
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            Column::make('id'),
            Column::make('firstName'),
            Column::make('lastName'),
            Column::make('created_at'),
            Column::make('updated_at'),
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'Export_' . date('YmdHis');
    }
}



6 - Create Controller Class


In Laravel framework for handle http request, we have to ceate Controller class. In Laravel framework controller class file has been store in app/Http/Controllers follder. For create controller class file, we have to go command prompt and write following command.


php artisan make:controller ExportController


This command will create ExportController.php controller class file. In this file, first we want to import ExportDataTable.php class and then after we have to make index method which will render ExportDataTable class data and load in export.blade.php view file.

app/Http/Controllers/ExportController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\DataTables\ExportDataTable;

class ExportController extends Controller
{
    public function index(ExportDataTable $dataTable)
    {
     return $dataTable->render('export');
    }
}



7 - Create View Blade File


For display output in Laravel framework, it has been used blade templating engine for display HTML output in browser. In Laravel framework view files has been store in resources/views folder. In this directory we have already create export.blade.php file. This file will display Mysql table data in DataTable by using Yajra Datatable package. And with data you can also find export csv or excel button also.

resources/views/export.blade.php

<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Add CSV Excel Export Button in Yajra Laravel Datatable</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.0.3/css/buttons.dataTables.min.css">
    <script src="https://cdn.datatables.net/buttons/1.0.3/js/dataTables.buttons.min.js"></script>
    <script src="{{ asset('vendor/datatables/buttons.server-side.js') }}"></script>
  </head>
  <body>
    <div class="container">    
      <br />
      <h3 align="center">Add CSV Excel Export Button in Yajra Laravel Datatable</h3>
      <br />
      <div class="table-responsive">
        <div class="panel panel-default">
          <div class="panel-heading">Sample Data</div>
          <div class="panel-body">
            
            {!! $dataTable->table() !!}

            {!! $dataTable->scripts() !!}
          </div>
        </div>        
      </div>
      <br />
      <br />
    </div>
  </body>
</html>



8 - Set Route


In next we want to set the route of controller class method. For set route we have to open routes/web.php file and in this file we have to define route which you can find below.

routes/web.php


Route::resource('export', 'ExportController');



9 - Run Laravel Application


Now all set and we are ready to check output in browser. But before check output in browser, we have to first start Laravel application server. For this we have go to command prompt and write following command.


php artisan serve


This command will start Laravel server and provide base url of Laravel application. For test above code we have to write following url.


http://127.0.0.1:8000/export


So this is step by step processing of How to add export button in Laravel Yajra DataTable package. In this tutorial, we have first learn How to generate fake data in Laravel and then after we have seen how to load data in Datatable in Laravel framework by using Yajra Datatable package and then after we have seen how can we export Yajra DataTable data in CSV or Excel file format by using Yajra DataTable buttons plugin. So If you have found this tutorial helpful to you then do not forget to share it.

Tuesday, 18 June 2019

How to use Date Range Filter For Export Data to CSV File in PHP



This is one more post on Exporting of Mysql data. In this post we will learn How to export Mysql data to CSV file by using PHP script. But here we add on feature like date range, that means here we will discuss how to export only those mysql data which has come between two define date to CSV file format by using PHP script. So, here you can learn How to export mysql data for specific date into Excel sheet or CSV file format via PHP.

If you have already learn How to Export Data to CSV file or Excel Sheet using PHP script. But suppose we do not want to export whole Mysql data into CSV file or Excel spread sheet but we want to Export those Data to CSV file with PHP which has come between select date range. So, at that time this turial will help you to learn How to export mysql data to CSV file or Excel sheet by using date range filter with PHP script. This is feature will add usability of your web application and use can freely to export those data which he want to export and he do not export whole unwanted data. This feature will reduce your website bandwidth and reduce load on your mysql database because only required or filtered data only has been exported into CSV file or Excel sheet.

In this post we want to Export date range filter data in CSV file using PHP then in PHP there are many PHP build in file system function is available for export data to CSV file. Here we have use some PHP function like fopen(), fputcsv(), fclose() for Export data to CSV file. Here fopen() function will open file in PHP stream. After this fputcsv() function will write data in open file and fclose() function will close open file. So, this basic PHP function has been used for export data to CSV file in PHP. But here we have not only export mysql data to csv file but also here we have export filtered data exported into csv file. So for filter data here we have use date range that means define two date and only export only those data which has come between this two define data. This we can done in mysql query which you can find below. For date range selection here we have use bootstrap date picker plugin. So, this simple tutorial on How to use Date Range Filter with Export Data to CSV File in PHP. Below you can find complete source code also.







Source Code


Database (tbl_order)



DROP TABLE IF EXISTS `tbl_order`;

CREATE TABLE `tbl_order` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `order_customer_name` varchar(255) NOT NULL,
  `order_item` varchar(255) NOT NULL,
  `order_value` double(12,2) NOT NULL,
  `order_date` date NOT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=MyISAM AUTO_INCREMENT=21 DEFAULT CHARSET=latin1;

/*Data for the table `tbl_order` */

insert  into `tbl_order`(`order_id`,`order_customer_name`,`order_item`,`order_value`,`order_date`) values 
(1,'David E. Gary','Shuttering Plywood',1500.00,'2019-06-14'),
(2,'Eddie M. Douglas','Aluminium Heavy Windows',2000.00,'2019-06-08'),
(3,'Oscar D. Scoggins','Plaster Of Paris',150.00,'2019-05-29'),
(4,'Clara C. Kulik','Spin Driller Machine',350.00,'2019-05-30'),
(5,'Christopher M. Victory','Shopping Trolley',100.00,'2019-06-01'),
(6,'Jessica G. Fischer','CCTV Camera',800.00,'2019-06-02'),
(7,'Roger R. White','Truck Tires',2000.00,'2019-05-28'),
(8,'Susan C. Richardson','Glass Block',200.00,'2019-06-04'),
(9,'David C. Jury','Casing Pipes',500.00,'2019-05-27'),
(10,'Lori C. Skinner','Glass PVC Rubber',1800.00,'2019-05-30'),
(11,'Shawn S. Derosa','Sony HTXT1 2.1-Channel TV',180.00,'2019-06-03'),
(12,'Karen A. McGee','Over-the-Ear Stereo Headphones ',25.00,'2019-06-01'),
(13,'Kristine B. McGraw','Tristar 10\" Round Copper Chef Pan with Glass Lid',20.00,'2019-05-30'),
(14,'Gary M. Porter','ROBO 3D R1 Plus 3D Printer',600.00,'2019-06-02'),
(15,'Sarah D. Hunter','Westinghouse Select Kitchen Appliances',35.00,'2019-05-29'),
(16,'Diane J. Thomas','SanDisk Ultra 32GB microSDHC',12.00,'2019-06-05'),
(17,'Helena J. Quillen','TaoTronics Dimmable Outdoor String Lights',16.00,'2019-06-04'),
(18,'Arlette G. Nathan','TaoTronics Bluetooth in-Ear Headphones',25.00,'2019-06-03'),
(19,'Ronald S. Vallejo','Scotchgard Fabric Protector, 10-Ounce, 2-Pack',20.00,'2019-06-03'),
(20,'Felicia L. Sorensen','Anker 24W Dual USB Wall Charger with Foldable Plug',12.00,'2019-06-04');


index.php



<?php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$start_date_error = '';
$end_date_error = '';

if(isset($_POST["export"]))
{
 if(empty($_POST["start_date"]))
 {
  $start_date_error = '<label class="text-danger">Start Date is required</label>';
 }
 else if(empty($_POST["end_date"]))
 {
  $end_date_error = '<label class="text-danger">End Date is required</label>';
 }
 else
 {
  $file_name = 'Order Data.csv';
  header("Content-Description: File Transfer");
  header("Content-Disposition: attachment; filename=$file_name");
  header("Content-Type: application/csv;");

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

  $header = array("Order ID", "Customer Name", "Item Name", "Order Value", "Order Date");

  fputcsv($file, $header);

  $query = "
  SELECT * FROM tbl_order 
  WHERE order_date >= '".$_POST["start_date"]."' 
  AND order_date <= '".$_POST["end_date"]."' 
  ORDER BY order_date DESC
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $data = array();
   $data[] = $row["order_id"];
   $data[] = $row["order_customer_name"];
   $data[] = $row["order_item"];
   $data[] = $row["order_value"];
   $data[] = $row["order_date"];
   fputcsv($file, $data);
  }
  fclose($file);
  exit;
 }
}

$query = "
SELECT * FROM tbl_order 
ORDER BY order_date DESC;
";

$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();

?>

<html>
 <head>
  <title>Daterange Mysql Data Export to CSV in PHP</title>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  <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>
 </head>
 <body>
  <div class="container box">
   <h1 align="center">Daterange Mysql Data Export to CSV in PHP</h1>
   <br />
   <div class="table-responsive">
    <br />
    <div class="row">
     <form method="post">
      <div class="input-daterange">
       <div class="col-md-4">
        <input type="text" name="start_date" class="form-control" readonly />
        <?php echo $start_date_error; ?>
       </div>
       <div class="col-md-4">
        <input type="text" name="end_date" class="form-control" readonly />
        <?php echo $end_date_error; ?>
       </div>
      </div>
      <div class="col-md-2">
       <input type="submit" name="export" value="Export" class="btn btn-info" />
      </div>
     </form>
    </div>
    <br />
    <table class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>Order ID</th>
       <th>Customer Name</th>
       <th>Item</th>
       <th>Value</th>
       <th>Order Date</th>
      </tr>
     </thead>
     <tbody>
      <?php
      foreach($result as $row)
      {
       echo '
       <tr>
        <td>'.$row["order_id"].'</td>
        <td>'.$row["order_customer_name"].'</td>
        <td>'.$row["order_item"].'</td>
        <td>$'.$row["order_value"].'</td>
        <td>'.$row["order_date"].'</td>
       </tr>
       ';
      }
      ?>
     </tbody>
    </table>
    <br />
    <br />
   </div>
  </div>
 </body>
</html>

<script>

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

</script>