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.     <script>
  29.         start_loader()
  30.     </script>
  31.     <main>
  32.         <div class="col-lg-12">
  33.             <h1 class="fw-bolder text-center" id="project-title">PHP Batch Insertion</h1>
  34.         </div>
  35.         <div class="container w-100">
  36.             <?php if(isset($_SESSION['error'])): ?>
  37.                 <div class="alert alert-danger rounded-0">
  38.                     <p><?= $_SESSION['error'] ?></p>
  39.                 </div>
  40.             <?php unset($_SESSION['error']) ?>
  41.             <?php endif; ?>
  42.             <div class="text-end mb-3">
  43.                 <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>
  44.             </div>
  45.             <div class="row">
  46.                 <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
  47.                     <div class="card rounded-0 shadow">
  48.                         <div class="card-body">
  49.                             <div class="w-100 overflow-auto">
  50.                                 <table class="table table-stripped table-bordered" id="item-list">
  51.                                     <colgroup>
  52.                                         <col width="10%">
  53.                                         <col width="50%">
  54.                                         <col width="20%">
  55.                                         <col width="20%">
  56.                                     </colgroup>
  57.                                     <thead>
  58.                                         <tr class="bg-primary bg-gradient text-light">
  59.                                             <th class="text-center">#</th>
  60.                                             <th>Name</th>
  61.                                             <th>Contact</th>
  62.                                             <th>Address</th>
  63.                                         </tr>
  64.                                     </thead>
  65.                                     <tbody>
  66.                                         <?php
  67.                                        $i =1;
  68.                                        $qry = $conn->query("SELECT * FROM `member_list`");
  69.                                         while($row = $qry->fetch_assoc()):
  70.                                         ?>
  71.                                         <tr>
  72.                                             <td class="px-2 py-1 text-center"><?= ($i++)  ?></td>
  73.                                             <td class="px-2 py-1"><?= ucwords($row['last_name']. ", " . $row['first_name'] . " ". $row['middle_name']) ?></td>
  74.                                             <td class="px-2 py-1"><?= $row['contact'] ?></td>
  75.                                             <td class="px-2 py-1"><?= $row['address'] ?></td>
  76.                                         </tr>
  77.                                         <?php endwhile; ?>
  78.                                         <?php $conn->close() ?>
  79.                                     </tbody>
  80.                                 </table>
  81.                             </div>
  82.                         </div>
  83.                     </div>
  84.                 </div>
  85.             </div>
  86.         </div>
  87.         <div class="modal fade" id="MemberFormModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="MemberFormModallabel" aria-hidden="true">
  88.             <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg">
  89.                 <div class="modal-content rounded-0">
  90.                     <div class="modal-header">
  91.                         <h5 class="modal-title" id="MemberFormModallabel">New Member Form</h5>
  92.                         <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  93.                     </div>
  94.                     <div class="modal-body">
  95.                         <form action="batch_insert.php" method="POST" id="new_member">
  96.                             <div class="border-top border-bottom item py-2">
  97.                                 <div class="row">
  98.                                     <div class="col-md-4">
  99.                                         <div class="form-group mb-3">
  100.                                             <label for="first_name" class="control-label">First Name</label>
  101.                                             <input type="text" class="form-control form-control-sm rounded-0" id="first_name" name="first_name[]" required="required">
  102.                                         </div>
  103.                                     </div>
  104.                                     <div class="col-md-4">
  105.                                         <div class="form-group mb-3">
  106.                                             <label for="middle_name" class="control-label">Middle Name</label>
  107.                                             <input type="text" class="form-control form-control-sm rounded-0" id="middle_name" name="middle_name[]">
  108.                                         </div>
  109.                                     </div>
  110.                                     <div class="col-md-4">
  111.                                         <div class="form-group mb-3">
  112.                                             <label for="last_name" class="control-label">Last Name</label>
  113.                                             <input type="text" class="form-control form-control-sm rounded-0" id="last_name" name="last_name[]" required="required">
  114.                                         </div>
  115.                                     </div>
  116.                                     <div class="col-md-4">
  117.                                         <div class="form-group mb-3">
  118.                                             <label for="contact" class="control-label">Contact #</label>
  119.                                             <input type="text" class="form-control form-control-sm rounded-0" id="contact" name="contact[]" required="required">
  120.                                         </div>
  121.                                     </div>
  122.                                     <div class="col-md-4">
  123.                                         <div class="form-group mb-3">
  124.                                             <label for="address" class="control-label">Address</label>
  125.                                             <textarea rows="2" class="form-control form-control-sm rounded-0" id="address" name="address[]" required="required"></textarea>
  126.                                         </div>
  127.                                     </div>
  128.                                     <div class="col-md-4">
  129.                                         <div class="form-group mb-3">
  130.                                             <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>
  131.                                         </div>
  132.                                     </div>
  133.                                 </div>
  134.                             </div>
  135.                         </form>
  136.                         <div class="text-center mt-3">
  137.                             <button class="btn btn-primary rounded-0 bg-gradient" type="button" id="add_item"><i class="fa fa-plus"></i> Add Item</button>
  138.                         </div>
  139.                     </div>
  140.                     <div class="modal-footer">
  141.                         <button type="submit" class="btn btn-primary btn-sm rounded-0" form="new_member">Save Item(s)</button>
  142.                         <button type="button" class="btn btn-secondary btn-sm rounded-0" data-bs-dismiss="modal">Close</button>
  143.                     </div>
  144.                 </div>
  145.             </div>
  146.         </div>
  147.     </main>
  148. </body>
  149. </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