PHP - Generate CSV File Using MySQLi

In this tutorial we will create a Generate CSV File Using MySQLi. PHP is a server-side scripting language designed primarily for web development. It is a lean and consistent way to access databases. This means developers can write portable code much easier. It is mostly used by a newly coders for its user friendly environment. So Let's do the coding...

Before we get started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html. And this is the link for the jquery that i used in this tutorial https://jquery.com/. Lastly, this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

Creating Database

Open your database web server then create a database name in it db_csv, after that click Import then locate the database file inside the folder of the application then click ok. tut1

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.
  1. <?php
  2. $conn = new mysqli('localhost', 'root', '', 'db_csv');
  3.  
  4. if(!$conn){
  5. die("Error: Failed to connect to database!");
  6. }
  7. ?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into your text editor, then save it as index.php.
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  5. <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  6. </head>
  7. <body>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  11. </div>
  12. </nav>
  13. <div class="col-md-3"></div>
  14. <div class="col-md-6 well">
  15. <h3 class="text-primary">PHP - Generate CSV File Using MySQLi</h3>
  16. <hr style="border-top:1px dotted #ccc;"/>
  17. <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#form_modal"><span class="glyphicon glyphicon-plus"></span> Add Employee</button>
  18. <a href="export.php" class="btn btn-success pull-right"><span class="glyphicon glyphicon-export"></span> Export as CSV</a>
  19. <br /><br />
  20. <table class="table table-bordered">
  21. <thead class="alert-success">
  22. <tr>
  23. <th>Firstname</th>
  24. <th>Lastname</th>
  25. <th>Address</th>
  26. <th>Age</th>
  27. <th>Job</th>
  28. </tr>
  29. </thead>
  30. <tbody style="background-color:#fff;">
  31. <?php
  32. require 'conn.php';
  33.  
  34. $query = $conn->query("SELECT * FROM `employee` ORDER BY `lastname` ASC");
  35. while($fetch = $query->fetch_array()){
  36. ?>
  37. <tr>
  38. <td><?php echo $fetch['firstname']?></td>
  39. <td><?php echo $fetch['lastname']?></td>
  40. <td><?php echo $fetch['address']?></td>
  41. <td><?php echo $fetch['age']?></td>
  42. <td><?php echo $fetch['job']?></td>
  43. </tr>
  44. <?php
  45. }
  46. ?>
  47. </tbody>
  48. </table>
  49. </div>
  50.  
  51.  
  52. <div class="modal fade" id="form_modal" aria-hidden="true">
  53. <div class="modal-dialog" role="document">
  54. <form method="POST" action="save_query.php">
  55. <div class="modal-content">
  56. <div class="modal-body">
  57. <div class="col-md-2"></div>
  58. <div class="col-md-8">
  59. <div class="form-group">
  60. <label>Firstname</label>
  61. <input class="form-control" type="text" name="firstname"/>
  62. </div>
  63. <div class="form-group">
  64. <label>Lastname</label>
  65. <input class="form-control" type="text" name="lastname"/>
  66. </div>
  67. <div class="form-group">
  68. <label>Address</label>
  69. <input class="form-control" type="text" name="address"/>
  70. </div>
  71. <div class="form-group">
  72. <label>Age</label>
  73. <input class="form-control" type="number" name="age"/>
  74. </div>
  75. <div class="form-group">
  76. <label>Job</label>
  77. <input class="form-control" type="text" name="job"/>
  78. </div>
  79. </div>
  80. </div>
  81. <div style="clear:both;"></div>
  82. <div class="modal-footer">
  83. <button type="button" class="btn btn-danger" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
  84. <button name="save" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span> Save</button>
  85. </div>
  86. </div>
  87. </form>
  88. </div>
  89. </div>
  90. </body>
  91. <script src="js/jquery-3.2.1.min.js"></script>
  92. <script src="js/bootstrap.js"></script>
  93. </html>

Creating PHP Query

This code contains the php query of the application. This code will store the data inputs to the database server when the user fill up and submit the form. To do that just copy and write this block of codes inside the text editor, then save it as save_query.php.
  1. <?php
  2. require_once 'conn.php';
  3.  
  4. if(ISSET($_POST['save'])){
  5. if(!empty($_POST['firstname']) || !empty($_POST['lastname']) || !empty($_POST['address']) || !empty($_POST['age']) || !empty($_POST['job'])){
  6. $firstname = $_POST['firstname'];
  7. $lastname = $_POST['lastname'];
  8. $address = $_POST['address'];
  9. $age = $_POST['age'];
  10. $job = $_POST['job'];
  11.  
  12. $conn->query("INSERT INTO `employee` VALUES('', '$firstname', '$lastname', '$address', '$age', '$job')") or die(mysqli_errno());
  13. echo "<script>alert('Data Inserted!')</script>";
  14. echo "<script>window.location = 'index.php'</script>";
  15. }else{
  16. echo "<script>alert('Please complete the require field!')</script>";
  17. echo "<script>window.location = 'index.php'</script>";
  18. }
  19.  
  20. }
  21. ?>

Creating Main Function

This is where the main function of the application. This code will forcefully compress and download the MySQLi data when the button is clicked. To do this just copy and write these block of codes inside the text editor, then save it as export.php.
  1. <?php
  2. require_once 'conn.php';
  3.  
  4. header('Content-Type: text/csv; charset=UTF-8');
  5. header('Content-Disposition: attachment; filename=data.csv');
  6.  
  7. $output = fopen("php://output", "w");
  8. fputcsv($output, array('emp_id', 'firstname', 'lastname', 'address', 'age', 'job'));
  9. $query = $conn->query("SELECT * FROM `employee` ORDER BY `lastname` ASC");
  10. while($fetch = $query->fetch_assoc()){
  11. fputcsv($output, $fetch);
  12. }
  13.  
  14. fclose($output);
  15. ?>
There you have it we successfully created Generate CSV File Using MySQLi. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Add new comment