Dynamically Add and Remove Element using AngularJS and PHP Tutorial

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.

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.  
  7. $conn = new mysqli($host, $username, $pw, $db_name);
  8.  
  9. if(!$conn){
  10. die("Database Connection Failed");
  11. }

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. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Angular JS Dynamic Add & Delete Element</title>
  7. <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" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <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>
  10. <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>
  11. <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>
  12. <style>
  13. html, body{
  14. min-height:100%;
  15. width:100%;
  16. }
  17. tbody:empty:after{
  18. content:'No records found'
  19. }
  20. </style>
  21. </head>
  22. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  23. <div class="container">
  24. <a class="navbar-brand" href="./">Angular JS Dynamic Add & Delete Element</a>
  25. <div>
  26. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  27. </div>
  28. </div>
  29. </nav>
  30. <div class="container-fluid px-5 my-3" ng-app="SampleApp" ng-controller="FormController">
  31. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  32. <div class="card rounded-0 shadow mb-3">
  33. <div class="card-header">
  34. <div class="card-title"><b>Dynamic Form</b></div>
  35. </div>
  36. <div class="card-body">
  37. <div class="container-fluid">
  38. <form ng-submit="formSubmit()">
  39. <div class="alert alert-success mb-3" ng-show="success_msg">{{success_msg}}</div>
  40. <div class="alert alert-danger mb-3" ng-show="error_msg">{{error_msg}}</div>
  41. <div id="item-list">
  42. <div class="d-flex w-100 mb-3 justify-content-between align-items-end input-item" ng-repeat="item in items">
  43. <div class="col-auto flex-shrink-1 flex-grow-1 pe-4">
  44. <label class="form-label">Full Name</label>
  45. <input type="text" class="form-control form-control-sm rounded-0" ng-model="fData.name[item.id]" name="name[]" required>
  46. </div>
  47. <div class="col-auto">
  48. <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>
  49. </div>
  50. </div>
  51. </div>
  52. <div class="mb-3 d-grid gap-2">
  53. <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>
  54. <button type="submit" class="btn btn-primary btn-block rounded-pill"><i class="fa-solid fa-save"></i> Save</button>
  55. </div>
  56. </form>
  57. </div>
  58. </div>
  59. </div>
  60. <div class="card rounded-0 shadow">
  61. <div class="card-header">
  62. <div class="card-title"><b>Name Lists</b></div>
  63. </div>
  64. <div class="card-body">
  65. <div class="container-fluid">
  66. <div class="alert alert-danger mb-3" ng-show="tbl_error_msg">{{tbl_error_msg}}</div>
  67. <table class="table table-striped table-bordered">
  68. <colgroup>
  69. <col width="10%">
  70. <col width="90%">
  71. </colgroup>
  72. <thead>
  73. <tr>
  74. <th class="text-center">#</th>
  75. <th class="text-center">Name</th>
  76. </tr>
  77. </thead>
  78. <tbody>
  79. <tr ng-repeat="nameobj in dataNames">
  80. <td class="text-center">{{$index + 1}}</td>
  81. <td class="">{{nameobj.name}}</td>
  82. </tr>
  83. <tr ng-if="dataNames.length <= 0">
  84. <th class="text-center" colspan="2">No records found</th>
  85. </tr>
  86. </tbody>
  87. </table>
  88. </div>
  89. </div>
  90. </div>
  91. </div>
  92. </div>
  93. <script src="app.js"></script>
  94. </body>
  95. </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.  
  4. /**
  5.   * Angular Controller
  6.   */
  7.  
  8. mymodule.controller("FormController", function ($scope, $http){
  9. $scope.items = [{id:1, name:''}];
  10. $scope.fData={}
  11. $scope.success_msg = "";
  12. $scope.error_msg = "";
  13. $scope.tbl_error_msg = "";
  14.  
  15. /**
  16.   * Add Button Function
  17.   */
  18. $scope.item_add = function(){
  19. var key = $scope.items.length + 1;
  20. $scope.items.push({id:key, name:''})
  21. console.log($scope.items)
  22. }
  23.  
  24. /**
  25.   *
  26.   * Remove Item Function
  27.   */
  28. $scope.item_remove = function(itemIndex){
  29. $scope.items.splice(itemIndex, 1)
  30. console.log($scope.items)
  31. }
  32.  
  33. /**
  34.   * Form Submit
  35.   */
  36.  
  37. $scope.formSubmit = function(){
  38. $http.post('insertData.php',$scope.fData,{})
  39. .then(
  40. function (response){
  41. if(response.status == 200){
  42. var data = response.data
  43. if(data.status == 'success'){
  44. $scope.success_msg = "Data has been added successfully."
  45. $scope.items = [{id:1, name:''}];
  46. $scope.fData={}
  47. $scope.getAllData()
  48. }else if(!!data.error){
  49. $scope.error_msg = data.error
  50. }else{
  51. console.error(response)
  52. $scope.error_msg = "Data has failed to insert due to some reasons."
  53. }
  54. }else{
  55. $scope.error_msg = "Data has failed to insert due to some reasons."
  56. console.error(response)
  57. }
  58. },
  59. function (error){
  60. $scope.error_msg = "Data has failed to insert due to some reasons."
  61. console.error(error)
  62. }
  63. )
  64. }
  65.  
  66. /**
  67.   * Retrieve Data
  68.   */
  69. $scope.getAllData = function(){
  70. $http.get('retrieve.php', {})
  71. .then(
  72. function (response){
  73. if(response.status == 200){
  74. var data = response.data
  75. $scope.dataNames = data
  76. }else{
  77. $scope.tbl_error_msg = "Retrieving Data Failed."
  78. console.error(response)
  79. }
  80. },
  81. function (error){
  82. $scope.tbl_error_msg = "Retrieving Data Failed."
  83. console.error(error)
  84. }
  85. )
  86. }
  87. $scope.getAllData()
  88. })

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.  
  6. $dataToInsert = [];
  7. if(isset($data['name'])){
  8. foreach($data['name'] as $name){
  9. if(!empty(trim($name)))
  10. $dataToInsert[] = "('". ( addslashes( $conn->real_escape_string( $name ) ) ) . "')";
  11. }
  12. }else{
  13. $resp['status'] = 'failed';
  14. $resp['error'] = "There's no array of names given.";
  15. }
  16.  
  17. if(count($dataToInsert) > 0){
  18. $sql = "INSERT INTO `people` (`name`) VALUES ";
  19. $sql .= implode(", ", $dataToInsert);
  20. $insert = $conn->query($sql);
  21. if($insert){
  22. $resp['status'] = 'success';
  23. }else{
  24. $resp['status'] = 'failed';
  25. $resp['error'] = $conn->error;
  26. }
  27. }else{
  28. $resp['status'] = 'failed';
  29. $resp['error'] = "There's no data to be inserted/save.";
  30. }
  31. // Return Response
  32. echo json_encode($resp);
  33. $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.  
  7. echo json_encode($result);
  8. $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

AngularJS Dynamic Add and Remove Element - Form Panel

Data Table Panel

AngularJS Dynamic Add and Remove Element - Data Table Panel

Main Page

AngularJS Dynamic Add and Remove Element - 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 :)

Add new comment