• We just launched and are currently in beta. Join us as we build and grow the community.

PHP Batch Insertion from Array Tutorial

iwasnthere

Otaku
Divine
I Rep
0
0
0
Rep
0
I Vouches
0
0
0
Vouches
0
Posts
100
Likes
156
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
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. `id`

    int

    (

    30

    )

    NOT

    NULL

    AUTO_INCREMENT

    PRIMARY KEY

    ,
  3. `first_

    name`

    varchar

    (

    250

    )

    NOT

    NULL

    ,
  4. `middle_

    name`

    varchar

    (

    250

    )

    NOT

    NULL

    ,
  5. `last_

    name`

    varchar

    (

    250

    )

    NOT

    NULL

    ,
  6. `contact`

    varchar

    (

    100

    )

    NOT

    NULL

    ,
  7. `address`

    text

    DEFAULT

    NULL


  8. )

    ENGINE

    =

    InnoDB

    DEFAULT

    CHARSET

    =

    utf8mb4;

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. <?php
  2. $host

    =

    "localhost"

    ;
  3. $username

    =

    "root"

    ;
  4. $pw

    =

    ""

    ;
  5. $db

    =

    "dummy_db"

    ;

  6. $conn

    =

    new

    mysqli(

    $host

    ,

    $username

    ,

    $pw

    ,

    $db

    )

    ;
  7. if

    (

    !

    $conn

    )

    {
  8. die

    (

    "Database Connection Failed."

    )

    ;
  9. }

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. This is a simple Web App. This was developed for educational purposes only.
  3. Author: oretnom23
  4. Email: [email protected]
  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. <head

    >
  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. </

    head

    >

  25. <body

    class

    =

    "bg-gradient bg-dark bg-opacity-50"

    >
  26. <script

    >
  27. start_loader()
  28. </

    script

    >
  29. <main>
  30. <div

    class

    =

    "col-lg-12"

    >
  31. <h1

    class

    =

    "fw-bolder text-center"

    id

    =

    "project-title"

    >

    PHP Batch Insertion</

    h1

    >
  32. </

    div

    >
  33. <div

    class

    =

    "container w-100"

    >
  34. <?php if(

    isset(

    $_SESSION[

    'error'

    ]

    )

    )

    : ?>
  35. <div

    class

    =

    "alert alert-danger rounded-0"

    >
  36. <p

    ><?=

    $_SESSION[

    'error'

    ]

    ?></

    p

    >
  37. </

    div

    >
  38. <?php unset(

    $_SESSION[

    'error'

    ]

    )

    ?>
  39. <?php endif; ?>
  40. <div

    class

    =

    "text-end mb-3"

    >
  41. <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

    >
  42. </

    div

    >
  43. <div

    class

    =

    "row"

    >
  44. <div

    class

    =

    "col-lg-12 col-md-12 col-sm-12 col-xs-12"

    >
  45. <div

    class

    =

    "card rounded-0 shadow"

    >
  46. <div

    class

    =

    "card-body"

    >
  47. <div

    class

    =

    "w-100 overflow-auto"

    >
  48. <table

    class

    =

    "table table-stripped table-bordered"

    id

    =

    "item-list"

    >
  49. <colgroup

    >
  50. <col

    width

    =

    "10%"

    >
  51. <col

    width

    =

    "50%"

    >
  52. <col

    width

    =

    "20%"

    >
  53. <col

    width

    =

    "20%"

    >
  54. </

    colgroup

    >
  55. <thead

    >
  56. <tr

    class

    =

    "bg-primary bg-gradient text-light"

    >
  57. <th

    class

    =

    "text-center"

    >

    #</

    th

    >
  58. <th

    >

    Name</

    th

    >
  59. <th

    >

    Contact</

    th

    >
  60. <th

    >

    Address</

    th

    >
  61. </

    tr

    >
  62. </

    thead

    >
  63. <tbody

    >
  64. <?php
  65. $i =

    1

    ;
  66. $qry =

    $conn->

    query("SELECT * FROM `member_list`");
  67. while($row = $qry->fetch_assoc()):
  68. ?>
  69. <tr

    >
  70. <td

    class

    =

    "px-2 py-1 text-center"

    ><?=

    (

    $i++)

    ?></

    td

    >
  71. <td

    class

    =

    "px-2 py-1"

    ><?=

    ucwords(

    $row[

    'last_name'

    ]

    . ", "

    . $row[

    'first_name'

    ]

    . " "

    . $row[

    'middle_name'

    ]

    )

    ?></

    td

    >
  72. <td

    class

    =

    "px-2 py-1"

    ><?=

    $row[

    'contact'

    ]

    ?></

    td

    >
  73. <td

    class

    =

    "px-2 py-1"

    ><?=

    $row[

    'address'

    ]

    ?></

    td

    >
  74. </

    tr

    >
  75. <?php endwhile; ?>
  76. <?php $conn->

    close() ?>
  77. </

    tbody

    >
  78. </

    table

    >
  79. </

    div

    >
  80. </

    div

    >
  81. </

    div

    >
  82. </

    div

    >
  83. </

    div

    >
  84. </

    div

    >
  85. <div

    class

    =

    "modal fade"

    id

    =

    "MemberFormModal"

    data-bs-backdrop=

    "static"

    data-bs-keyboard=

    "false"

    tabindex

    =

    "-1"

    aria-labelledby=

    "MemberFormModallabel"

    aria-hidden=

    "true"

    >
  86. <div

    class

    =

    "modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg"

    >
  87. <div

    class

    =

    "modal-content rounded-0"

    >
  88. <div

    class

    =

    "modal-header"

    >
  89. <h5

    class

    =

    "modal-title"

    id

    =

    "MemberFormModallabel"

    >

    New Member Form</

    h5

    >
  90. <button

    type

    =

    "button"

    class

    =

    "btn-close"

    data-bs-dismiss=

    "modal"

    aria-label

    =

    "Close"

    ></

    button

    >
  91. </

    div

    >
  92. <div

    class

    =

    "modal-body"

    >
  93. <form

    action

    =

    "batch_insert.php"

    method

    =

    "POST"

    id

    =

    "new_member"

    >
  94. <div

    class

    =

    "border-top border-bottom item py-2"

    >
  95. <div

    class

    =

    "row"

    >
  96. <div

    class

    =

    "col-md-4"

    >
  97. <div

    class

    =

    "form-group mb-3"

    >
  98. <label

    for

    =

    "first_name"

    class

    =

    "control-label"

    >

    First Name</

    label

    >
  99. <input

    type

    =

    "text"

    class

    =

    "form-control form-control-sm rounded-0"

    id

    =

    "first_name"

    name

    =

    "first_name[]"

    required=

    "required"

    >
  100. </

    div

    >
  101. </

    div

    >
  102. <div

    class

    =

    "col-md-4"

    >
  103. <div

    class

    =

    "form-group mb-3"

    >
  104. <label

    for

    =

    "middle_name"

    class

    =

    "control-label"

    >

    Middle Name</

    label

    >
  105. <input

    type

    =

    "text"

    class

    =

    "form-control form-control-sm rounded-0"

    id

    =

    "middle_name"

    name

    =

    "middle_name[]"

    >
  106. </

    div

    >
  107. </

    div

    >
  108. <div

    class

    =

    "col-md-4"

    >
  109. <div

    class

    =

    "form-group mb-3"

    >
  110. <label

    for

    =

    "last_name"

    class

    =

    "control-label"

    >

    Last Name</

    label

    >
  111. <input

    type

    =

    "text"

    class

    =

    "form-control form-control-sm rounded-0"

    id

    =

    "last_name"

    name

    =

    "last_name[]"

    required=

    "required"

    >
  112. </

    div

    >
  113. </

    div

    >
  114. <div

    class

    =

    "col-md-4"

    >
  115. <div

    class

    =

    "form-group mb-3"

    >
  116. <label

    for

    =

    "contact"

    class

    =

    "control-label"

    >

    Contact #</

    label

    >
  117. <input

    type

    =

    "text"

    class

    =

    "form-control form-control-sm rounded-0"

    id

    =

    "contact"

    name

    =

    "contact[]"

    required=

    "required"

    >
  118. </

    div

    >
  119. </

    div

    >
  120. <div

    class

    =

    "col-md-4"

    >
  121. <div

    class

    =

    "form-group mb-3"

    >
  122. <label

    for

    =

    "address"

    class

    =

    "control-label"

    >

    Address</

    label

    >
  123. <textarea

    rows

    =

    "2"

    class

    =

    "form-control form-control-sm rounded-0"

    id

    =

    "address"

    name

    =

    "address[]"

    required=

    "required"

    ></

    textarea

    >
  124. </

    div

    >
  125. </

    div

    >
  126. <div

    class

    =

    "col-md-4"

    >
  127. <div

    class

    =

    "form-group mb-3"

    >
  128. <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

    >
  129. </

    div

    >
  130. </

    div

    >
  131. </

    div

    >
  132. </

    div

    >
  133. </

    form

    >
  134. <div

    class

    =

    "text-center mt-3"

    >
  135. <button

    class

    =

    "btn btn-primary rounded-0 bg-gradient"

    type

    =

    "button"

    id

    =

    "add_item"

    ><i

    class

    =

    "fa fa-plus"

    ></

    i

    >

    Add Item</

    button

    >
  136. </

    div

    >
  137. </

    div

    >
  138. <div

    class

    =

    "modal-footer"

    >
  139. <button

    type

    =

    "submit"

    class

    =

    "btn btn-primary btn-sm rounded-0"

    form=

    "new_member"

    >

    Save Item(s)</

    button

    >
  140. <button

    type

    =

    "button"

    class

    =

    "btn btn-secondary btn-sm rounded-0"

    data-bs-dismiss=

    "modal"

    >

    Close</

    button

    >
  141. </

    div

    >
  142. </

    div

    >
  143. </

    div

    >
  144. </

    div

    >
  145. </

    main>
  146. </

    body

    >
  147. </

    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. html,
  2. body {
  3. height

    :

    100%

    ;
  4. width

    :

    100%

    ;
  5. }

  6. main {
  7. padding

    :

    1em

    0

    ;
  8. }

  9. main *

    {
  10. font-family

    :

    Comic Sans MS;
  11. }

  12. #project-title

    {
  13. text-shadow

    :

    3px

    3px

    7px

    #000

    ;
  14. padding

    :

    2.5em

    1em

    !important;
  15. color

    :

    white

    ;
  16. font-size

    :

    3em

    ;
  17. padding-bottom

    :

    0.5em

    !important;
  18. }


  19. /* Loader */

  20. #pre-loader

    {
  21. position

    :

    absolute

    ;
  22. width

    :

    100%

    ;
  23. height

    :

    100%

    ;
  24. top

    :

    0

    ;
  25. left

    :

    0

    ;
  26. backdrop-filter:

    brightness(

    .5)

    ;
  27. display

    :

    flex;
  28. align-items

    :

    center

    ;
  29. justify-content

    :

    center

    ;
  30. z-index

    :

    99

    ;
  31. }

  32. .lds-hourglass

    {
  33. display

    :

    inline-block

    ;
  34. position

    :

    relative

    ;
  35. width

    :

    80px

    ;
  36. height

    :

    80px

    ;
  37. }

  38. .lds-hourglass

    :

    after

    {
  39. content

    :

    " "

    ;
  40. display

    :

    block

    ;
  41. border-radius

    :

    50%

    ;
  42. width

    :

    0

    ;
  43. height

    :

    0

    ;
  44. margin

    :

    8px

    ;
  45. box-sizing

    :

    border-box

    ;
  46. border

    :

    32px

    solid

    #fff

    ;
  47. border-color

    :

    #fff

    transparent

    #fff

    transparent

    ;
  48. animation

    :

    lds-hourglass 1.2s

    infinite

    ;
  49. }

  50. @keyframes

    lds-hourglass {
  51. 0%

    {
  52. transform

    :

    rotate

    (

    0

    )

    ;
  53. animation-timing-function

    :

    cubic-bezier

    (

    0.55

    ,

    0.055

    ,

    0.675

    ,

    0.19

    )

    ;
  54. }
  55. 50%

    {
  56. transform

    :

    rotate

    (

    900deg

    )

    ;
  57. animation-timing-function

    :

    cubic-bezier

    (

    0.215

    ,

    0.61

    ,

    0.355

    ,

    1

    )

    ;
  58. }
  59. 100%

    {
  60. transform

    :

    rotate

    (

    1800deg

    )

    ;
  61. }
  62. }

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. // Loader Start Function
  6. window.start_loader

    =

    function

    (

    )

    {
  7. if

    (

    !

    document.getElementById

    (

    'pre-loader'

    )

    ||

    (

    !!

    document.getElementById

    (

    'pre-loader'

    )

    &&

    document.getElementById

    (

    'pre-loader'

    )

    .length

    <=

    0

    )

    )
  8. document.querySelector

    (

    'body'

    )

    .appendChild

    (

    loader)
  9. }

  10. // Loader Stop Function
  11. window.end_loader

    =

    function

    (

    )

    {
  12. if

    (

    !!

    document.getElementById

    (

    'pre-loader'

    )

    )

    {
  13. setTimeout(

    (

    )

    =>

    {
  14. document.getElementById

    (

    'pre-loader'

    )

    .remove

    (

    )
  15. }

    ,

    500

    )
  16. }
  17. }

  18. function

    rem_item(

    _this)

    {
  19. if

    (

    $(

    'form#new_member .item'

    )

    .length

    >

    1

    )

    {
  20. _this.closest

    (

    '.item'

    )

    .remove

    (

    )
  21. }

    else

    {
  22. $(

    'form#new_member'

    )

    [

    0

    ]

    .reset

    (

    )
  23. }
  24. }
  25. $(

    function

    (

    )

    {
  26. end_loader(

    )
  27. $(

    '#add_item'

    )

    .click

    (

    function

    (

    )

    {
  28. var

    item =

    $(

    'form#new_member .item'

    )

    .first

    (

    )

    .clone

    (

    )
  29. item.find

    (

    'input, textarea'

    )

    .val

    (

    ''

    )
  30. $(

    'form#new_member'

    )

    .append

    (

    item)
  31. }

    )
  32. }

    )

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. <?php
  2. session_start

    (

    )

    ;
  3. // Require/Include DB Connection
  4. require_once

    (

    './db-connect.php'

    )

    ;

  5. // Data to Insert
  6. $data

    =

    ""

    ;

  7. // Extract POST Data
  8. extract

    (

    $_POST

    )

    ;

  9. // Loop the Array Data
  10. foreach

    (

    $first_name

    as

    $k

    =>

    $v

    )

    {
  11. if

    (

    !

    empty

    (

    $data

    )

    )

    $data

    .=

    ", "

    ;
  12. $data

    .=

    "('{$v}

    ', '{$middle_name

    [$k

    ]}', '{$last_name

    [$k

    ]}', '{$contact

    [$k

    ]}', '{$address

    [$k

    ]}')"

    ;
  13. }

  14. if

    (

    empty

    (

    $data

    )

    )

    {
  15. echo

    '<script> alert("New Data has been sent."); </script>'

    ;
  16. }

    else

    {
  17. $sql

    =

    "INSERT INTO `member_list` (`first_name`, `middle_name`, `last_name`, `contact`, `address`) VALUES {$data}

    "

    ;
  18. $insert_batch

    =

    $conn

    ->

    query

    (

    $sql

    )

    ;
  19. if

    (

    $insert_batch

    )

    {
  20. echo

    '<script> alert("New Member(s) has been saved successfully."); </script>'

    ;
  21. }

    else

    {
  22. echo

    '<script> alert("Data has failed to save."); </script>'

    ;
  23. $_SESSION

    [

    'error'

    ]

    =

    "Query Error: "

    .

    $conn

    ->

    error

    .

    ". <br />"

    .

    $sql

    ;
  24. }
  25. }
  26. $conn

    ->

    close

    (

    )

    ;
  27. 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.

 

449,193

322,229

322,238

Top