Import export csv using php and mysql

July 14, 2021 . 6 MIN READ

https://www.cloudways.com/blog/import-export-csv-using-php-and-mysql/

Import CSV to MySQL in PHP

After the database has been created, I next need an HTML file  that could upload CSV file. For this HTML file, I will use HTML File uploader in a simple bootstrap form.

Create a file and name it `index.php` . This is a simple form for uploading CSV file. This file will also show the results in a simple table on the same page. When the user submits the form,  all records will be saved in the database.

First, I will add Bootstrap CDN to index.php.

  1. <link rel=“stylesheet” href=“https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css” crossorigin=“anonymous”>
  2. <link rel=“stylesheet” href=“https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css” crossorigin=“anonymous”>
  3. <script src=“https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js” crossorigin=“anonymous”></script>

Next, in the `body` tag,  add the following HTML code for the Bootstrap form.

  1. <!DOCTYPE html>
  2. <html lang=“en”>
  3. <head>
  4. <link rel=“stylesheet” href=“https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css” crossorigin=“anonymous”>
  5. <link rel=“stylesheet” href=“https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css” crossorigin=“anonymous”>
  6. <script src=“https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js” crossorigin=“anonymous”></script>
  7. </head>
  8. <body>
  9. <div id=“wrap”>
  10. <div class=“container”>
  11. <div class=“row”>
  12. <form class=“form-horizontal” action=“functions.php” method=“post” name=“upload_excel” enctype=“multipart/form-data”>
  13. <fieldset>
  14. <! Form Name >
  15. <legend>Form Name</legend>
  16. <! File Button >
  17. <div class=“form-group”>
  18. <label class=“col-md-4 control-label” for=“filebutton”>Select File</label>
  19. <div class=“col-md-4”>
  20. <input type=“file” name=“file” id=“file” class=“input-large”>
  21. </div>
  22. </div>
  23. <! Button >
  24. <div class=“form-group”>
  25. <label class=“col-md-4 control-label” for=“singlebutton”>Import data</label>
  26. <div class=“col-md-4”>
  27. <button type=“submit” id=“submit” name=“Import” class=“btn btn-primary button-loading” dataloadingtext=“Loading…”>Import</button>
  28. </div>
  29. </div>
  30. </fieldset>
  31. </form>
  32. </div>
  33. <?php
  34. get_all_records();
  35. ?>
  36. </div>
  37. </div>
  38. </body>
  39. </html>

 

You might notice that I have set an action to `functions.php` file. In the next step, I will create this file and add code to it. I have also include a method `get_all_records()` near the end of the file. This method fetches all the records from the database and display the records in the table on the index page.

Next up, I will create `functions.php` file and add the following code in it.

  1. <?php
  2. if(isset($_POST[“Import”])){
  3. $filename=$_FILES[“file”][“tmp_name”];
  4. if($_FILES[“file”][“size”] > 0)
  5. {
  6. $file = fopen($filename, “r”);
  7. while (($getData = fgetcsv($file, 10000, “,”)) !== FALSE)
  8. {
  9. $sql = “INSERT into employeeinfo (emp_id,firstname,lastname,email,reg_date)
  10. values (‘”.$getData[0].”‘,‘”.$getData[1].”‘,‘”.$getData[2].”‘,‘”.$getData[3].”‘,‘”.$getData[4].”‘)“;
  11. $result = mysqli_query($con, $sql);
  12. if(!isset($result))
  13. {
  14. echo “<script type=\”text/javascript\”>
  15. alert(\”Invalid File:Please Upload CSV File.\”);
  16. window.location = \”index.php\”
  17. </script>”;
  18. }
  19. else {
  20. echo “<script type=\”text/javascript\”>
  21. alert(\”CSV File has been successfully Imported.\”);
  22. window.location = \”index.php\”
  23. </script>”;
  24. }
  25. }
  26. fclose($file);
  27. }
  28. }
  29. ?>

When the upload button is clicked, the temporary file name will be stored in memory and using the `while` loop the data is saved in $getData variable. Once the process has been completed, the data is sorted column wise and then finally inserted in the `employeeinfo` table.

Note that `fgetcsv()` parses lines from the open file, checking for CSV fields and `fopen()` opens a file or a URL. This code could be tested by importing a CSV file with test data.

Display the Saved Records

Once the CSV file has been imported, I will display the data through a simple function, `get_all_records()`, initialized in `index.php`. Copy this function to `function.php`.

  1. function get_all_records(){
  2. $con = getdb();
  3. $Sql = “SELECT * FROM employeeinfo”;
  4. $result = mysqli_query($con, $Sql);
  5. if (mysqli_num_rows($result) > 0) {
  6. echo “<div class=‘table-responsive’><table id=‘myTable’ class=‘table table-striped table-bordered’>
  7. <thead><tr><th>EMP ID</th>
  8. <th>First Name</th>
  9. <th>Last Name</th>
  10. <th>Email</th>
  11. <th>Registration Date</th>
  12. </tr></thead><tbody>”;
  13. while($row = mysqli_fetch_assoc($result)) {
  14. echo “<tr><td>” . $row[’emp_id’].”</td>
  15. <td>” . $row[‘firstname’].”</td>
  16. <td>” . $row[‘lastname’].”</td>
  17. <td>” . $row[’email’].”</td>
  18. <td>” . $row[‘reg_date’].”</td></tr>”;
  19. }
  20. echo “</tbody></table></div>”;
  21. } else {
  22. echo “you have no records”;
  23. }
  24. }

In this really simple method, I simply selected all the records and displayed these records on the index page through the method. Whenever the user uploads a CSV file, the records will get saved in the table and then displayed on the index page.

Export MySQL to CSV With PHP

Exporting data from  MySQL database to a CSV file is similarly very easy. To demonstrate this, I will use the index.php that I created earlier.

Add the following code to the file.

  1. <div>
  2. <form class=“form-horizontal” action=“functions.php” method=“post” name=“upload_excel”
  3. enctype=“multipart/form-data”>
  4. <div class=“form-group”>
  5. <div class=“col-md-4 col-md-offset-4”>
  6. <input type=“submit” name=“Export” class=“btn btn-success” value=“export to excel”/>
  7. </div>
  8. </div>
  9. </form>
  10. </div>

After adding this HTML markup, the Export button will appear below the table. Now add the following condition in functions.php.

  1. if(isset($_POST[“Export”])){
  2. header(‘Content-Type: text/csv; charset=utf-8’);
  3. header(‘Content-Disposition: attachment; filename=data.csv’);
  4. $output = fopen(“php://output”, “w”);
  5. fputcsv($output, array(‘ID’, ‘First Name’, ‘Last Name’, ‘Email’, ‘Joining Date’));
  6. $query = “SELECT * from employeeinfo ORDER BY emp_id DESC”;
  7. $result = mysqli_query($con, $query);
  8. while($row = mysqli_fetch_assoc($result))
  9. {
  10. fputcsv($output, $row);
  11. }
  12. fclose($output);
  13. }

When the `Export` button is clicked, the headers `Content-Type: text/csv` with an attachement `data.csv` is sent.

Since `php://output` is a write-only stream that allows write access to the output buffer mechanism, I selected all data from table in the next line, and passed it to `fputcsv()` method. This method formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file. Finally, the file with all the desired data is downloaded.

Finally, after integrating all the code, you will see the following final shape of application.

 

You might also like: Simple CRUD in PHP and MySQL

Conclusion

In this article, I discussed how you could export data from and to CSV files using PHP and MySQL. This is a simple example you can Add more complex logic and validations as per your requirements. You can also create test cases to verify the code and Integerate with GitHub using PHP Continuous Integeration Tools. If you wish to add to the discussion or would like to ask a question, leave a comment below.

Leave a Reply

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