PHP Batch Insertion from Array Tutorial

In this tutorial, we will tackle Inserting the Data from Array in MySQL Database using PHP. Here, I will show you a technique to easily insert multiple data rows into the database. This technique or idea can be helpful for mass data insertion of a form for some feature of a PHP Projects such as POS or Cashiering System, Shopping Cart, and more.

For this tutorial, we will be creating a simple web application that consists of a feature that we want to achieve on this tutorial. The application will have a simple database table structure where our data will be inserted. Here, I will be using Bootstrap v5 for the design of the user interface and jQuery Library for the UX of the Form that we will use. The application has a single page that lists all the inserted data and has a form modal.

Getting Started

Download the following to your local machine:

Install the XAMPP into your local machine. After that, open the XAMPP's Control Panel and start the Apache and MySQL Server.

Compile the Bootstrap and jQuery files into your source code directory. Make sure to put your source code directory inside the XAMPP's htdocs directory otherwise, you will make some configuration.

Open your preferred browser and browse the XAMPP's PHPMyAdmin by browsing http://localhost/phpmyadmin.

Creating the Database

Create a new database naming dummy_db. After that, navigate the page into the SQL tab of your newly created database. Then, paste the SQL Script below into the provided text field and click the Go button below to execute the SQL Script.

  1. CREATE TABLE `member_list` (
  2. `first_name` varchar(250) NOT NULL,
  3. `middle_name` varchar(250) NOT NULL,
  4. `last_name` varchar(250) NOT NULL,
  5. `contact` varchar(100) NOT NULL,
  6. `address` text DEFAULT NULL

Creating the Database Connection File

Open your preferred text editor such as notepadd++ or sublime text. Create a new PHP File naming db-connect.php. Save the file inside your source code directory's root path. Then, copy/paste the script below.

  1.  
  2. <?php
  3. $host ="localhost";
  4. $username ="root";
  5. $pw ="";
  6. $db ="dummy_db";
  7.  
  8. $conn = new mysqli($host, $username, $pw, $db);
  9. if(!$conn){
  10. die("Database Connection Failed.");
  11. }

Creating the Page Interface

Next, create a new PHP File naming index.php and save it into your source code directory's root path. This file contains the HTML Script and PHP Scripts that displays all the inserted data into a table and a membership form inside a popup window or modal. Copy the script below and make sure to replace the external CSS and JS paths according to the location of each file on your end.

  1.  
  2. <!--
  3. This is a simple Web App. This was developed for educational purposes only.
  4. Author: oretnom23
  5. -->
  6. <?php
  7. session_start();
  8. // Require/Include DB Connection
  9. require_once('./db-connect.php');
  10. ?><!DOCTYPE html>
  11. <html lang="en">
  12.  
  13. <meta charset="UTF-8">
  14. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  15. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  16. <title>PHP Batch Insertion</title>
  17. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  18. <link rel="stylesheet" href="./css/bootstrap.min.css">
  19. <link rel="stylesheet" href="./css/styles.css">
  20. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/js/all.min.js" integrity="sha512-6PM0qYu5KExuNcKt5bURAoT6KCThUmHRewN3zUFNaoI6Di7XJPTMoT6K0nsagZKk2OB4L7E3q1uQKHNHd4stIQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  21. <script src="./js/jquery-3.6.0.min.js"></script>
  22. <script src="./js/bootstrap.min.js"></script>
  23. <script src="./js/script.js"></script>
  24.  
  25. </head>
  26.  
  27. <body class="bg-gradient bg-dark bg-opacity-50">
  28. start_loader()
  29. </script>
  30. <main>
  31. <div class="col-lg-12">
  32. <h1 class="fw-bolder text-center" id="project-title">PHP Batch Insertion</h1>
  33. </div>
  34. <div class="container w-100">
  35. <?php if(isset($_SESSION['error'])): ?>
  36. <div class="alert alert-danger rounded-0">
  37. <p><?= $_SESSION['error'] ?></p>
  38. </div>
  39. <?php unset($_SESSION['error']) ?>
  40. <?php endif; ?>
  41. <div class="text-end mb-3">
  42. <button class="btn btn-primary btn-sm bg-gradient rounded-0" type="button" data-bs-toggle="modal" data-bs-target="#MemberFormModal"><i class="fa fa-plus"></i> Add Member(s)</button>
  43. </div>
  44. <div class="row">
  45. <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
  46. <div class="card rounded-0 shadow">
  47. <div class="card-body">
  48. <div class="w-100 overflow-auto">
  49. <table class="table table-stripped table-bordered" id="item-list">
  50. <col width="10%">
  51. <col width="50%">
  52. <col width="20%">
  53. <col width="20%">
  54. <tr class="bg-primary bg-gradient text-light">
  55. <th class="text-center">#</th>
  56. <th>Name</th>
  57. <th>Contact</th>
  58. <th>Address</th>
  59. </tr>
  60. </thead>
  61. <?php
  62. $i =1;
  63. $qry = $conn->query("SELECT * FROM `member_list`");
  64. while($row = $qry->fetch_assoc()):
  65. ?>
  66. <tr>
  67. <td class="px-2 py-1 text-center"><?= ($i++) ?></td>
  68. <td class="px-2 py-1"><?= ucwords($row['last_name']. ", " . $row['first_name'] . " ". $row['middle_name']) ?></td>
  69. <td class="px-2 py-1"><?= $row['contact'] ?></td>
  70. <td class="px-2 py-1"><?= $row['address'] ?></td>
  71. </tr>
  72. <?php endwhile; ?>
  73. <?php $conn->close() ?>
  74. </tbody>
  75. </table>
  76. </div>
  77. </div>
  78. </div>
  79. </div>
  80. </div>
  81. </div>
  82. <div class="modal fade" id="MemberFormModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="MemberFormModallabel" aria-hidden="true">
  83. <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
  84. <div class="modal-content rounded-0">
  85. <div class="modal-header">
  86. <h5 class="modal-title" id="MemberFormModallabel">New Member Form</h5>
  87. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  88. </div>
  89. <div class="modal-body">
  90. <form action="batch_insert.php" method="POST" id="new_member">
  91. <div class="border-top border-bottom item py-2">
  92. <div class="row">
  93. <div class="col-md-4">
  94. <div class="form-group mb-3">
  95. <label for="first_name" class="control-label">First Name</label>
  96. <input type="text" class="form-control form-control-sm rounded-0" id="first_name" name="first_name[]" required="required">
  97. </div>
  98. </div>
  99. <div class="col-md-4">
  100. <div class="form-group mb-3">
  101. <label for="middle_name" class="control-label">Middle Name</label>
  102. <input type="text" class="form-control form-control-sm rounded-0" id="middle_name" name="middle_name[]">
  103. </div>
  104. </div>
  105. <div class="col-md-4">
  106. <div class="form-group mb-3">
  107. <label for="last_name" class="control-label">Last Name</label>
  108. <input type="text" class="form-control form-control-sm rounded-0" id="last_name" name="last_name[]" required="required">
  109. </div>
  110. </div>
  111. <div class="col-md-4">
  112. <div class="form-group mb-3">
  113. <label for="contact" class="control-label">Contact #</label>
  114. <input type="text" class="form-control form-control-sm rounded-0" id="contact" name="contact[]" required="required">
  115. </div>
  116. </div>
  117. <div class="col-md-4">
  118. <div class="form-group mb-3">
  119. <label for="address" class="control-label">Address</label>
  120. <textarea rows="2" class="form-control form-control-sm rounded-0" id="address" name="address[]" required="required"></textarea>
  121. </div>
  122. </div>
  123. <div class="col-md-4">
  124. <div class="form-group mb-3">
  125. <button tabindex="-1" class="btn btn-outline-danger btn-sm rounded-0 mt-4 rem-btn" onclick="rem_item($(this))" type="button"><i class="fa fa-times"></i> Remove</button>
  126. </div>
  127. </div>
  128. </div>
  129. </div>
  130. </form>
  131. <div class="text-center mt-3">
  132. <button class="btn btn-primary rounded-0 bg-gradient" type="button" id="add_item"><i class="fa fa-plus"></i> Add Item</button>
  133. </div>
  134. </div>
  135. <div class="modal-footer">
  136. <button type="submit" class="btn btn-primary btn-sm rounded-0" form="new_member">Save Item(s)</button>
  137. <button type="button" class="btn btn-secondary btn-sm rounded-0" data-bs-dismiss="modal">Close</button>
  138. </div>
  139. </div>
  140. </div>
  141. </div>
  142. </main>
  143. </body>
  144. </html>

Creating the Custom CSS

The below script is the custom Cascading Style Sheet script that designs or redesign some of the elements in our user interface. Save this file as styles.css and make sure to include this file into your index.html file.

  1.  
  2. html,
  3. body {
  4. height: 100%;
  5. width: 100%;
  6. }
  7.  
  8. main {
  9. padding: 1em 0;
  10. }
  11.  
  12. main * {
  13. font-family: Comic Sans MS;
  14. }
  15.  
  16. #project-title {
  17. text-shadow: 3px 3px 7px #000;
  18. padding: 2.5em 1em !important;
  19. color: white;
  20. font-size: 3em;
  21. padding-bottom: 0.5em !important;
  22. }
  23.  
  24.  
  25. /* Loader */
  26.  
  27. #pre-loader {
  28. position: absolute;
  29. width: 100%;
  30. height: 100%;
  31. top: 0;
  32. left: 0;
  33. backdrop-filter: brightness(.5);
  34. display: flex;
  35. align-items: center;
  36. justify-content: center;
  37. z-index: 99;
  38. }
  39.  
  40. .lds-hourglass {
  41. display: inline-block;
  42. position: relative;
  43. width: 80px;
  44. height: 80px;
  45. }
  46.  
  47. .lds-hourglass:after {
  48. content: " ";
  49. display: block;
  50. border-radius: 50%;
  51. width: 0;
  52. height: 0;
  53. margin: 8px;
  54. box-sizing: border-box;
  55. border: 32px solid #fff;
  56. border-color: #fff transparent #fff transparent;
  57. animation: lds-hourglass 1.2s infinite;
  58. }
  59.  
  60. @keyframes lds-hourglass {
  61. 0% {
  62. transform: rotate(0);
  63. animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
  64. }
  65. 50% {
  66. transform: rotate(900deg);
  67. animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  68. }
  69. 100% {
  70. transform: rotate(1800deg);
  71. }
  72. }

Creating the Custom JS

The below script is the custom JavaScript of out application which holds the codes or scripts the event listeners and function for our form's functionalities. The scripts will allows the user to add new item in the form and removing item from the form. Save this file as script.js and make sure to include the file into your index.php file also.

  1. // Custom Loader Element Node
  2. var loader = document.createElement('div')
  3. loader.setAttribute('id', 'pre-loader');
  4. loader.innerHTML = "<div class='lds-hourglass'></div>";
  5.  
  6. // Loader Start Function
  7. window.start_loader = function() {
  8. if (!document.getElementById('pre-loader') || (!!document.getElementById('pre-loader') && document.getElementById('pre-loader').length <= 0))
  9. document.querySelector('body').appendChild(loader)
  10. }
  11.  
  12. // Loader Stop Function
  13. window.end_loader = function() {
  14. if (!!document.getElementById('pre-loader')) {
  15. setTimeout(() => {
  16. document.getElementById('pre-loader').remove()
  17. }, 500)
  18. }
  19. }
  20.  
  21. function rem_item(_this) {
  22. if ($('form#new_member .item').length > 1) {
  23. _this.closest('.item').remove()
  24. } else {
  25. $('form#new_member')[0].reset()
  26. }
  27. }
  28. $(function() {
  29. end_loader()
  30. $('#add_item').click(function() {
  31. var item = $('form#new_member .item').first().clone()
  32. item.find('input, textarea').val('')
  33. $('form#new_member').append(item)
  34. })
  35. })

Creating the Main Script

Lastly, we will create a new PHP File naming batch_insert.php and save into your source code directory. This file contains the php script for inserting the array data from our form. The file also contains a simple script on catching the errors if any will occurred.

  1.  
  2. <?php
  3. // Require/Include DB Connection
  4. require_once('./db-connect.php');
  5.  
  6. // Data to Insert
  7. $data = "";
  8.  
  9. // Extract POST Data
  10. extract($_POST);
  11.  
  12. // Loop the Array Data
  13. foreach($first_name as $k => $v){
  14. if(!empty($data)) $data .= ", ";
  15. $data .= "('{$v}', '{$middle_name[$k]}', '{$last_name[$k]}', '{$contact[$k]}', '{$address[$k]}')";
  16. }
  17.  
  18. if(empty($data)){
  19. echo '<script> alert("New Data has been sent."); </script>';
  20. }else{
  21. $sql = "INSERT INTO `member_list` (`first_name`, `middle_name`, `last_name`, `contact`, `address`) VALUES {$data} ";
  22. $insert_batch = $conn->query($sql);
  23. if($insert_batch){
  24. echo '<script> alert("New Member(s) has been saved successfully."); </script>';
  25. }else{
  26. echo '<script> alert("Data has failed to save."); </script>';
  27. $_SESSION['error'] = "Query Error: ". $conn->error .". <br />".$sql;
  28. }
  29. }
  30. $conn->close();
  31. header("Location: ./");

That's it! You can now check the application and see if it works as we planned and if it achieves our goal of this tutorial. You can test the application by browsing http://localhost/source_code_directory_name/ in to your preferred browser.

That's the end of this tutorial. If there's an error occurred on your end, please review the changes in your codes and try to differentiate them from the source code I provided above. You can also download the working source code I created for this tutorial. The download button is located below this article.

I hope this tutorial will help you with what you are looking for and you'll find this useful for your future PHP Projects.

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

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
10 + 10 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.