Importing CSV File Data into MySQL Database using PHP Tutorial

In this tutorial, you will learn how to Import CSV File Data Into MySQL Database using PHP. The tutorial aims to provide the IT/CS Students and new programmers with a reference for reading CSV Files in PHP and Import Data into the Database. Here, the step-by-step tutorial with snippets is provided and a sample program source code zip that demonstrates the tutorial objectives is free to download.

How to Import Data From CSV to MySQL Database using PHP?

PHP has a built-in method that allows the server to read files such as CSV. In order to import the data from CSV to MySQL Database, you can simply read the data from the CSV File and create a MySQL Statement for inserting the data into the database.

Here are the following PHP methods that are useful for implementing an import data from CSV to Database:

  • fopen()
  • fgetcsv()
  • fclose()

Steps of implementing an import data from CSV to MySQL DB

  1. Create a form that contains a file input for choosing the CSV file.
  2. Upon submission, read the selected/chosen CSV file and list the row data.
  3. Create a MySQL Insert Statement w/ the values listed in the CSV file.
  4. Execute the MySQL Query for the Insertion of data into the database.

Example

Here are the snippets that result in a simple program that demonstrate the steps that I provided above.

Database Schema

Let us use the following MySQL Database Schema for this example web application. The schema creates a new database named dummy_db. It also creates one table named members that have id, name, phone, email, and created_at columns.

  1. --
  2. -- Database: `dummy_db`
  3. --
  4. CREATE DATABASE IF NOT EXISTS `dummy_db` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
  5. USE `dummy_db`;
  6.  
  7. -- --------------------------------------------------------
  8.  
  9. --
  10. -- Table structure for table `members`
  11. --
  12.  
  13. CREATE TABLE IF NOT EXISTS `members` (
  14. `name` varchar(250) NOT NULL,
  15. `phone` varchar(50) NOT NULL,
  16. `email` varchar(100) NOT NULL,
  17. PRIMARY KEY (`id`)

Database Connection

Next, create a PHP file and save it as db-connect.php. This file contains the following script which handles the connection of the application and database.

  1. <?php
  2. // DB Host
  3. $host = "localhost";
  4. // DB Username
  5. $uname = "root";
  6. // DB Password
  7. $password = "";
  8. // DB Name
  9. $dbname = "dummy_db";
  10.  
  11.  
  12. $conn = new mysqli($host, $uname, $password, $dbname);
  13. if(!$conn){
  14. die("Database Connection Failed.");
  15. }
  16. ?>

Interface

Next, let's create another PHP file and save it as index.php. The file contains the following script which is a combined PHP and HTML code. As result, the page has a form that contains a file input that only accepts a CSV file. It also contains a table that displays the inserted data from the database.

  1. <?php session_start(); ?>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Import CSV Data to MySQL in PHP</title>
  8. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  9. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  10.  
  11. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  12. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  13. </head>
  14. <body style="background:#9CB4CC">
  15. <nav class="navbar navbar-expand-lg navbar-dark" style="background:#06283D">
  16. <div class="container">
  17. <a class="navbar-brand" href="./">Import CSV Data to MySQL in PHP</a>
  18. <div>
  19. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  20. </div>
  21. </div>
  22. </nav>
  23. <div class="container-fluid px-5 pb-2 pt-5">
  24. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  25. <h3 class="text-center text-light">Importing CSV Data to MySQL Database in PHP</h3>
  26. <hr>
  27. <?php if(isset($_SESSION['status']) && $_SESSION['status']== "success"): ?>
  28. <div class="alert alert-success rounded-0 mb-3">
  29. <?= $_SESSION['message'] ?>
  30. </div>
  31. <?php unset($_SESSION['status']);unset($_SESSION['message']) ?>
  32. <?php endif; ?>
  33. <?php if(isset($_SESSION['status']) && $_SESSION['status'] == "error"): ?>
  34. <div class="alert alert-danger rounded-0 mb-3">
  35. <?= $_SESSION['message'] ?>
  36. </div>
  37. <?php unset($_SESSION['status']);unset($_SESSION['message']) ?>
  38. <?php endif; ?>
  39. <div class="card rounded-0 mb-3">
  40. <div class="card-header rounded-0">
  41. <div class="card-title"><b>Import Data From CSV</b></div>
  42. </div>
  43. <div class="card-body rounded-0">
  44. <div class="container-fluid">
  45. <form action="import_csv.php" id="import-form" method="POST" enctype="multipart/form-data">
  46. <div class="mb-3">
  47. <label for="fileData" class="form-label">Browse CSV Data</label>
  48. <input class="form-control" type="file" accept=".csv" name="fileData" id="fileData" required>
  49. </div>
  50. </form>
  51. </div>
  52. </div>
  53. <div class="card-footer py-1">
  54. <div class="text-center">
  55. <button class="btn btn-primary rounded-pill col-lg-5 col-md-6 col-sm-12 col-xs-12" form="import-form">Import</button>
  56. </div>
  57. </div>
  58. </div>
  59. <div class="card my-2 rounded-0">
  60. <div class="card-header rounded-0">
  61. <div class="card-title"><b>Member List</b></div>
  62. </div>
  63. <div class="card-body rounded-0">
  64. <div class="container-fluid">
  65. <div class="table-responsive">
  66. <table class="table table-hovered table-striped table-bordered">
  67. <tr class="bg-gradient bg-primary text-white">
  68. <th class="text-center">#</th>
  69. <th class="text-center">Name</th>
  70. <th class="text-center">Phone/Fax</th>
  71. <th class="text-center">Email</th>
  72. </tr>
  73. </thead>
  74. <?php
  75. include_once('db-connect.php');
  76. $members_sql = "SELECT * FROM `members` order by id ASC";
  77. $members_qry = $conn->query($members_sql);
  78. if($members_qry->num_rows > 0):
  79. while($row = $members_qry->fetch_assoc()):
  80. ?>
  81. <tr>
  82. <th class="text-center"><?= $row['id'] ?></th>
  83. <td><?= $row['name'] ?></td>
  84. <td><?= $row['phone'] ?></td>
  85. <td><?= $row['email'] ?></td>
  86. </tr>
  87. <?php endwhile; ?>
  88. <?php else: ?>
  89. <tr>
  90. <th class="text-center" colspan="4">No data on the database yet.</th>
  91. </tr>
  92. <?php endif; ?>
  93. <?php $conn->close() ?>
  94. </tbody>
  95. </table>
  96. </div>
  97. </div>
  98. </div>
  99. </div>
  100. </div>
  101.  
  102. </div>
  103. </body>
  104. </html>

PHP API

Next, we will create the PHP API that contains the scripts for reading the selected CSV File, listing the data to insert, and inserting the data into the database. Save the following snippet as import_csv.php. This file will be executed upon form submission.

  1. <?php
  2. include_once('db-connect.php');
  3.  
  4. /**
  5.   * Check if CSV File has been sent successfully otherwise return error
  6.   */
  7. if(isset($_FILES['fileData']) && !empty($_FILES['fileData']['tmp_name'])){
  8.  
  9. // Read CSV File
  10. $csv_file = fopen($_FILES['fileData']['tmp_name'], "r");
  11.  
  12. // Row Iteration
  13. $rowCount = 0;
  14.  
  15. //Data to insert for batch insertion
  16. $data = [];
  17.  
  18. // Read CSV Data by row
  19. while(($row = fgetcsv($csv_file, 1000, ",")) !== FALSE){
  20. if($rowCount > 0){
  21. //Sanitizing Data
  22. $name = addslashes($conn->real_escape_string($row[0]));
  23. $phone = addslashes($conn->real_escape_string($row[1]));
  24. $email = addslashes($conn->real_escape_string($row[2]));
  25.  
  26. // Add Row data to insert value
  27. $data[] = "('{$name}', '{$phone}', '{$email}')";
  28. }
  29. $rowCount++;
  30. }
  31.  
  32. // Close the CSV File
  33. fclose($csv_file);
  34.  
  35. /**
  36.   * Check if there's a data to insert otherwise return error
  37.   */
  38. if(count($data) > 0) {
  39. // Convert Data values from array to string w/ comma seperator
  40. $insert_values = implode(", ", $data);
  41.  
  42. //MySQL INSERT Statement
  43. $insert_sql = "INSERT INTO `members` (`name`, `phone`, `email`) VALUES {$insert_values}";
  44.  
  45. // Execute Insertion
  46. $insert = $conn->query($insert_sql);
  47.  
  48. if($insert){
  49. // Data Insertion is successful
  50. $_SESSION['status'] = 'success';
  51. $_SESSION['message'] = 'Data has been imported succesfully.';
  52. }else{
  53. // Data Insertion has failed
  54. $_SESSION['status'] = 'error';
  55. $_SESSION['message'] = 'Import Failed! Error: '. $conn->error;
  56. }
  57. }else{
  58. $_SESSION['status'] = 'error';
  59. $_SESSION['message'] = 'CSV File Data is empty.';
  60. }
  61.  
  62. }else{
  63. $_SESSION['status'] = 'error';
  64. $_SESSION['message'] = 'CSV File Data is missing.';
  65. }
  66. $conn->close();
  67.  
  68. header('location: ./');
  69. ?>

CSV File

Lastly, let's create a CSV file that we will use for importing. You can create your own example CSV file but make sure to follow the following format of data with the same column order. Take note that the script for importing the source code skips the first row in the reading. The CSV file only requires the name, phone, and email columns.

name,phone,email
Silas Leonard,(515) 433-7885,[email protected]
Adele Moody,1-451-357-4702,[email protected]
Colton Turner,1-172-865-3080,[email protected]
Carolyn Kramer,1-237-334-8685,[email protected]
Lionel Vazquez,1-226-236-8055,[email protected]
Naomi Workman,(320) 551-7707,[email protected]
Rhona Vega,1-683-547-2283,[email protected]
Martena Hardin,1-426-208-8881,[email protected]
Galena Collier,1-711-578-8491,[email protected]
Demetrius Nichols,1-302-469-9766,[email protected]    

There you go! You can now test the application on your end and see if it works as we planned. I also provided the source code zip file that I created for this tutorial with a sample CSV File. You can download it by clicking the Download Button located below this article's content.

Snapshot

Here is a snapshot of the application page interface.

Import MySQL Data From CSV using PHP

That's it! That's the end of this tutorial. I hope this Importing CSV File Data into MySQL Database using PHP Tutorial helps you with what you are looking for and that you'll find this useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding:)

Comments

Submitted byadamsam (not verified)on Sun, 12/11/2022 - 10:22

thanks for sharing only want to add how to skip the first line of the head of csv file $flag = true; // Read CSV Data by row while(($row = fgetcsv($csv_file, 1000, ",")) !== FALSE){ if($rowCount > 0){ //Sanitizing Data if($flag) { $flag = false; continue; } $name = addslashes($conn->real_escape_string($row[6])); $phone = addslashes($conn->real_escape_string($row[7])); $email = addslashes($conn->real_escape_string($row[8]));

Add new comment