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

Dynamically Add and Remove Element using AngularJS and PHP Tutorial

luckyboy2112

Banana Technician
L Rep
0
0
0
Rep
0
L Vouches
0
0
0
Vouches
0
Posts
52
Likes
134
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
Introduction

In this tutorial, you will learn how to Dynamically Add and Remove an Element using AngularJS and Data Batch Insertion using PHP and MySQL Database. The tutorial aims to provide a reference or guide to students or new programmers on manipulating DOM using AngularJS and inserting multiple data in the database at once. Here are snippets and a simple web application source code zip file.

What is Dynamic Adding and Removing Element?

Dynamically Adding and Removing an Element is a form of manipulating DOM (Document Object Model). Implementing this kind of feature to your web project allows your end-users to add and remove HTML Elements without leaving the current page.

What is Batch Insertion?

Batch Insertion is the process of inserting multiple data into the database at once. This kind of feature is usually used when processing the insertion of data from a Form with Iterated input data.

For this tutorial, we will create a simple web application with a form that allows the users to dynamically add and remove input items and insert all the data on the database at once.

Methods and Functions

Here are the methods and functions that we will use to achieve the application that we want to create.

AngularJS

  • module
  • module.controller
  • $scope service
  • $http service
  • ng-If
  • ng-repeat
  • ng-module
  • ng-click
  • ng-model
  • ng-controller
  • ng-app
  • ng-show

Getting Started

Since we will use PHP Script and MySQL Database, Download and Install XAMPP or any equivalent software to allow your local machine to run the scripts.

Creating the Database

The below MySQL Script is a MySQL Schema of our sample application to develop.

  1. CREATE

    TABLE

    `people`

    (
  2. `id`

    int

    (

    30

    )

    NOT

    NULL

    PRIMARY KEY

    AUTO_INCREMENT

    ,
  3. `name`

    varchar

    (

    250

    )

    NOT

    NULL


  4. )

    ENGINE

    =

    InnoDB

    DEFAULT

    CHARSET

    =

    utf8mb4;

Database Connection

Next, we will create a PHP script that handles the connection of our app to the database. Create a PHP File named db-connect.php.

  1. <?php
  2. $host

    =

    "localhost"

    ;
  3. $username

    =

    "root"

    ;
  4. $pw

    =

    ""

    ;
  5. $db_name

    =

    "dummy_db"

    ;

  6. $conn

    =

    new

    mysqli(

    $host

    ,

    $username

    ,

    $pw

    ,

    $db_name

    )

    ;

  7. if

    (

    !

    $conn

    )

    {
  8. die

    (

    "Database Connection Failed"

    )

    ;
  9. }

Creating the Interface

The snippet below is an HTML Scripts that also contains the AngularJS attributes that are needed for the app. This page contains the form panel and the table for displaying the inserted data. Save the snippet below as index.php

  1. <!DOCTYPE html>
  2. <html

    lang

    =

    "en"

    >
  3. <head

    >
  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

    >

    Angular JS Dynamic Add & Delete Element</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. <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>
  11. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.js" integrity="sha512-klc+qN5PPscoGxSzFpetVsCr9sryi2e2vHwZKq43FdFyhSAa7vAqog/Ifl8tzg/8mBZiG2MAKhyjH5oPJp65EA==" 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. <style>
  14. html, body{
  15. min-height:100%;
  16. width:100%;
  17. }
  18. tbody:empty:after{
  19. content:'No records found'
  20. }
  21. </

    style

    >
  22. </

    head

    >
  23. <body

    >
  24. <nav class

    =

    "navbar navbar-expand-lg navbar-dark bg-primary bg-gradient"

    >
  25. <div

    class

    =

    "container"

    >
  26. <a

    class

    =

    "navbar-brand"

    href

    =

    "./"

    >

    Angular JS Dynamic Add & Delete Element</a>
  27. <div>
  28. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  29. </div>
  30. </div>
  31. </nav>
  32. <div class="container-fluid px-5 my-3" ng-app="SampleApp" ng-controller="FormController">
  33. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  34. <div class="card rounded-0 shadow mb-3">
  35. <div class="card-header">
  36. <div class="card-title"><b>Dynamic Form</b></div>
  37. </div>
  38. <div class="card-body">
  39. <div class="container-fluid">
  40. <form ng-submit="formSubmit()">
  41. <div class="alert alert-success mb-3" ng-show="success_msg">{{success_msg}}</div>
  42. <div class="alert alert-danger mb-3" ng-show="error_msg">{{error_msg}}</div>
  43. <div id="item-list">
  44. <div class="d-flex w-100 mb-3 justify-content-between align-items-end input-item" ng-repeat="item in items">
  45. <div class="col-auto flex-shrink-1 flex-grow-1 pe-4">
  46. <label class="form-label">Full Name</label>
  47. <input type="text" class="form-control form-control-sm rounded-0" ng-model="fData.name[item.id]" name="name[]" required>
  48. </div>
  49. <div class="col-auto">
  50. <button class="btn btn-sm btn-danger rounded-0" type="button" ng-click="item_remove($index)" tabindex = '-1'><i class="fa-solid fa-trash"></i></button>
  51. </div>
  52. </div>
  53. </div>
  54. <div class="mb-3 d-grid gap-2">
  55. <button class="btn btn-sm btn-light border btn-block rounded-pill" type="button" ng-click="item_add()" ><i class="fa-solid fa-plus"></i> Add Item</button>
  56. <button type="submit" class="btn btn-primary btn-block rounded-pill"><i class="fa-solid fa-save"></i> Save</button>
  57. </div>
  58. </form>
  59. </div>
  60. </div>
  61. </div>
  62. <div class="card rounded-0 shadow">
  63. <div class="card-header">
  64. <div class="card-title"><b>Name Lists</b></div>
  65. </div>
  66. <div class="card-body">
  67. <div class="container-fluid">
  68. <div class="alert alert-danger mb-3" ng-show="tbl_error_msg">{{tbl_error_msg}}</div>
  69. <table class="table table-striped table-bordered">
  70. <colgroup>
  71. <col width="10%">
  72. <col width="90%">
  73. </colgroup>
  74. <thead>
  75. <tr>
  76. <th class="text-center">#</th>
  77. <th class="text-center">Name</th>
  78. </tr>
  79. </thead>
  80. <tbody>
  81. <tr ng-repeat="nameobj in dataNames">
  82. <td class="text-center">{{$index + 1}}</td>
  83. <td class="">{{nameobj.name}}</td>
  84. </tr>
  85. <tr ng-if="dataNames.length <= 0">
  86. <th class="text-center" colspan="2">No records found</th>
  87. </tr>
  88. </tbody>
  89. </table>
  90. </div>
  91. </div>
  92. </div>
  93. </div>
  94. </div>
  95. <script src="app.js"></script>
  96. </body>
  97. </html>

Creating the AngularJS Script

The below snippet is a JavaScript file containing the AngularJS script. The script initiates the functionalities we need for the app. Save the file as the app. This file must be loaded on the main page after the AngularJS Library.

  1. var

    mymodule =

    angular.module

    (

    "SampleApp"

    ,

    [

    ]

    )

    ;


  2. /**
  3. * Angular Controller
  4. */

  5. mymodule.controller

    (

    "FormController"

    ,

    function

    (

    $scope,

    $http)

    {
  6. $scope.items

    =

    [

    {

    id:

    1

    ,

    name:

    ''

    }

    ]

    ;
  7. $scope.fData

    =

    {

    }
  8. $scope.success_msg

    =

    ""

    ;
  9. $scope.error_msg

    =

    ""

    ;
  10. $scope.tbl_error_msg

    =

    ""

    ;

  11. /**
  12. * Add Button Function
  13. */
  14. $scope.item_add

    =

    function

    (

    )

    {
  15. var

    key =

    $scope.items

    .length

    +

    1

    ;
  16. $scope.items

    .push

    (

    {

    id:

    key,

    name:

    ''

    }

    )
  17. console.log

    (

    $scope.items

    )
  18. }

  19. /**
  20. *
  21. * Remove Item Function
  22. */
  23. $scope.item_remove

    =

    function

    (

    itemIndex)

    {
  24. $scope.items

    .splice

    (

    itemIndex,

    1

    )
  25. console.log

    (

    $scope.items

    )
  26. }

  27. /**
  28. * Form Submit
  29. */

  30. $scope.formSubmit

    =

    function

    (

    )

    {
  31. $http.post

    (

    'insertData.php'

    ,

    $scope.fData

    ,

    {

    }

    )
  32. .then

    (
  33. function

    (

    response)

    {
  34. if

    (

    response.status

    ==

    200

    )

    {
  35. var

    data =

    response.data
  36. if

    (

    data.status

    ==

    'success'

    )

    {
  37. $scope.success_msg

    =

    "Data has been added successfully."
  38. $scope.items

    =

    [

    {

    id:

    1

    ,

    name:

    ''

    }

    ]

    ;
  39. $scope.fData

    =

    {

    }
  40. $scope.getAllData

    (

    )
  41. }

    else

    if

    (

    !!

    data.error

    )

    {
  42. $scope.error_msg

    =

    data.error
  43. }

    else

    {
  44. console.error

    (

    response)
  45. $scope.error_msg

    =

    "Data has failed to insert due to some reasons."
  46. }
  47. }

    else

    {
  48. $scope.error_msg

    =

    "Data has failed to insert due to some reasons."
  49. console.error

    (

    response)
  50. }
  51. }

    ,
  52. function

    (

    error)

    {
  53. $scope.error_msg

    =

    "Data has failed to insert due to some reasons."
  54. console.error

    (

    error)
  55. }
  56. )
  57. }

  58. /**
  59. * Retrieve Data
  60. */
  61. $scope.getAllData

    =

    function

    (

    )

    {
  62. $http.get

    (

    'retrieve.php'

    ,

    {

    }

    )
  63. .then

    (
  64. function

    (

    response)

    {
  65. if

    (

    response.status

    ==

    200

    )

    {
  66. var

    data =

    response.data
  67. $scope.dataNames

    =

    data
  68. }

    else

    {
  69. $scope.tbl_error_msg

    =

    "Retrieving Data Failed."
  70. console.error

    (

    response)
  71. }
  72. }

    ,
  73. function

    (

    error)

    {
  74. $scope.tbl_error_msg

    =

    "Retrieving Data Failed."
  75. console.error

    (

    error)
  76. }
  77. )
  78. }
  79. $scope.getAllData

    (

    )
  80. }

    )

Inserting Data

The snippet below is a PHP Script. The code itself executes the batch insertion of the data submitted from the form. Save the file as insertData.php.

  1. <?php
  2. require_once

    (

    "db-connect.php"

    )

    ;
  3. // Data
  4. $data

    =

    (

    array

    )

    json_decode

    (

    file_get_contents

    (

    "php://input"

    )

    )

    ;

  5. $dataToInsert

    =

    [

    ]

    ;
  6. if

    (

    isset

    (

    $data

    [

    'name'

    ]

    )

    )

    {
  7. foreach

    (

    $data

    [

    'name'

    ]

    as

    $name

    )

    {
  8. if

    (

    !

    empty

    (

    trim

    (

    $name

    )

    )

    )
  9. $dataToInsert

    [

    ]

    =

    "('"

    .

    (

    addslashes

    (

    $conn

    ->

    real_escape_string

    (

    $name

    )

    )

    )

    .

    "')"

    ;
  10. }
  11. }

    else

    {
  12. $resp

    [

    'status'

    ]

    =

    'failed'

    ;
  13. $resp

    [

    'error'

    ]

    =

    "There's no array of names given."

    ;
  14. }

  15. if

    (

    count

    (

    $dataToInsert

    )

    >

    0

    )

    {
  16. $sql

    =

    "INSERT INTO `people` (`name`) VALUES "

    ;
  17. $sql

    .=

    implode

    (

    ", "

    ,

    $dataToInsert

    )

    ;
  18. $insert

    =

    $conn

    ->

    query

    (

    $sql

    )

    ;
  19. if

    (

    $insert

    )

    {
  20. $resp

    [

    'status'

    ]

    =

    'success'

    ;
  21. }

    else

    {
  22. $resp

    [

    'status'

    ]

    =

    'failed'

    ;
  23. $resp

    [

    'error'

    ]

    =

    $conn

    ->

    error

    ;
  24. }
  25. }

    else

    {
  26. $resp

    [

    'status'

    ]

    =

    'failed'

    ;
  27. $resp

    [

    'error'

    ]

    =

    "There's no data to be inserted/save."

    ;
  28. }
  29. // Return Response
  30. echo

    json_encode

    (

    $resp

    )

    ;
  31. $conn

    ->

    close

    (

    )

    ;

Retrieving Data

The snippet below is also a PHP Script. The script fetches all the data from the database and returns it to AngularJS's HTTP Service Request as an object. Save the file as retrieve.php.

  1. <?php
  2. require_once

    (

    'db-connect.php'

    )

    ;
  3. $sql

    =

    "SELECT * FROM `people` order by `name` asc"

    ;
  4. $query

    =

    $conn

    ->

    query

    (

    $sql

    )

    ;
  5. $result

    =

    $query

    ->

    fetch_all

    (

    MYSQLI_ASSOC)

    ;

  6. echo

    json_encode

    (

    $result

    )

    ;
  7. $conn

    ->

    close

    (

    )

    ;

That's it! You can now test the application source code on your end by browsing the main page using your preferred browser such as Chrome browser. I have also provided the complete source code file I created for this tutorial. The zip file is free to download on this site. The download button is located below this article.

Snapshots

Here are some Snapshots of the output of the source code I have provided.

Form Panel

Data Table Panel

Main Page

DEMO VIDEO

That's the end of this tutorial. I hope this Dynamically Add and Remove Element using AngularJS and PHP/MySQL Batch Insertion Tutorial will help you with what you are looking for and that you'll find this useful for your current and future projects.

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

Happy Coding :)


Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,341

323,350

Top