AngularJS Adding Form Fields Dynamically with PHP/MySQLi

Getting Started

I've used CDN for Bootstrap and Angular JS in this tutorial so you need internet connection for them to work.

Creating our Database

First, we are going to create our database. 1. Open phpMyAdmin. 2. Click databases, create a database and name it as angular. 3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.
  1. CREATE TABLE `members` (
  2.   `memid` int(11) NOT NULL AUTO_INCREMENT,
  3.   `firstname` varchar(30) NOT NULL,
  4.   `lastname` varchar(30) NOT NULL,
  5.   `address` text NOT NULL,
  6. PRIMARY KEY(`memid`)
database sql

index.html

Next, this is our index that contains out add form.
  1. <!DOCTYPE html>
  2. <html lang="en" ng-app="app">
  3.     <meta charset="utf-8">
  4.     <title>AngularJS Adding Form Fields Dynamically with PHP/MySQLi</title>
  5.     <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  6.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  7. </head>
  8. <body ng-controller="memberdata" ng-init="fetch()">
  9. <div class="container">
  10.     <h1 class="page-header text-center">AngularJS Adding Form Fields Dynamically with PHP/MySQLi</h1>
  11.     <div class="row">
  12.                 <div class="col-md-8 col-md-offset-2">
  13.                         <div class="alert alert-success text-center" ng-show="success">
  14.                                 <button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">&times;</span></button>
  15.                                 <i class="fa fa-check"></i> {{ successMessage }}
  16.                         </div>
  17.                         <div class="alert alert-danger text-center" ng-show="error">
  18.                                 <button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">&times;</span></button>
  19.                                 <i class="fa fa-warning"></i> {{ errorMessage }}
  20.                         </div>
  21.                         <form name="addForm" novalidate>
  22.                                 <fieldset ng-repeat="memberfield in memberfields">
  23.                                         <div class="panel panel-default">
  24.                                                 <div class="panel-body">
  25.                                                         <div class="row">
  26.                                                                 <div class="col-md-3">
  27.                                                                         <input type="text" placeholder="Firstname" class="form-control" ng-model="memberfield.firstname" required>
  28.                                                                 </div>
  29.                                                                 <div class="col-md-3">
  30.                                                                         <input type="text" placeholder="Lastname" class="form-control" ng-model="memberfield.lastname" required>
  31.                                                                 </div>
  32.                                                                 <div class="col-md-5">
  33.                                                                         <input type="text" placeholder="Address" class="form-control" ng-model="memberfield.address" required>
  34.                                                                 </div>
  35.                                                                 <button class="btn btn-danger btn-sm" ng-show="$last" ng-click="removeField()"><span class="glyphicon glyphicon-remove"></span></button>
  36.                                                         </div>
  37.                                                 </div>
  38.                                         </div>
  39.                                 </fieldset>
  40.                                 <button type="button" class="btn btn-primary" ng-click="newfield()"><span class="glyphicon glyphicon-plus"></span> Add</button>
  41.                                 <button type="button" class="btn btn-primary" ng-disabled="addForm.$invalid" ng-click="submitForm()"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
  42.                         </form>
  43.                         <table class="table table-bordered table-striped" style="margin-top:10px;">
  44.                                 <thead>
  45.                     <tr>
  46.                         <th>First Name</th>
  47.                         <th>Last Name</th>
  48.                         <th>Address</th>
  49.                     </tr>
  50.                 </thead>
  51.                                 <tbody>
  52.                                         <tr ng-repeat="member in members">
  53.                                                 <td>{{ member.firstname }}</td>
  54.                                                 <td>{{ member.lastname }}</td>
  55.                                                 <td>{{ member.address }}</td>
  56.                                         </tr>
  57.                                 </tbody>
  58.                         </table>
  59.                 </div>
  60.         </div>
  61. </div>
  62. <script src="angular.js"></script>
  63. </body>
  64. </html>

angular.js

This contains our angular js scripts.
  1. var app = angular.module('app', []);
  2. app.controller('memberdata', function($scope, $http){
  3.         $scope.success = false;
  4.     $scope.error = false;
  5.  
  6.     $scope.fetch = function(){
  7.         $http.get("fetch.php").success(function(data){
  8.                 $scope.members = data;
  9.             });
  10.     }
  11.  
  12.     $scope.memberfields = [{id: 'field1'}];
  13.  
  14.     $scope.newfield = function(){
  15.         var newItem = $scope.memberfields.length+1;
  16.         $scope.memberfields.push({'id':'field'+newItem});
  17.     }
  18.  
  19.     $scope.submitForm = function(){
  20.         $http.post('add.php', $scope.memberfields)
  21.         .success(function(data){
  22.             if(data.error){
  23.                 $scope.error = true;
  24.                 $scope.success = false;
  25.                 $scope.errorMessage = data.message;
  26.             }
  27.             else{
  28.                 $scope.error = false;
  29.                 $scope.success = true;
  30.                 $scope.successMessage = data.message;
  31.                 $scope.fetch();
  32.                 $scope.memberfields = [{id: 'field1'}];
  33.             }
  34.         });
  35.     }
  36.  
  37.     $scope.removeField = function() {
  38.         var lastItem = $scope.memberfields.length-1;
  39.         $scope.memberfields.splice(lastItem);
  40.     };
  41.  
  42.     $scope.clearMessage = function(){
  43.         $scope.success = false;
  44.         $scope.error = false;
  45.     }
  46. });

fetch.php

This is our PHP api/code that fetches data from our MySQL database.
  1. <?php
  2.         $conn = new mysqli('localhost', 'root', '', 'angular');
  3.        
  4.         $output = array();
  5.         $sql = "SELECT * FROM members";
  6.         $query=$conn->query($sql);
  7.         while($row=$query->fetch_array()){
  8.                 $output[] = $row;
  9.         }
  10.  
  11.         echo json_encode($output);
  12. ?>

add.php

Lastly, this is our PHP api/code in adding one or multiple rows into our database.
  1. <?php
  2.     $conn = new mysqli('localhost', 'root', '', 'angular');
  3.  
  4.     $data = json_decode(file_get_contents("php://input"));
  5.  
  6.     $count = count($data);
  7.  
  8.     $out = array('error' => false);
  9.  
  10.     foreach($data as $key => $value){
  11.         $firstname = $value->firstname;
  12.         $lastname = $value->lastname;
  13.         $address = $value->address;
  14.  
  15.         $sql = "INSERT INTO members (firstname, lastname, address) VALUES ('$firstname', '$lastname', '$address')";
  16.         $query = $conn->query($sql);
  17.     }
  18.  
  19.     if($query){
  20.         $out['message'] = "($count) Member/s added successfully";
  21.     }
  22.     else{
  23.         $out['error'] = true;
  24.         $out['message'] = "Cannot add Member(s)";
  25.     }
  26.  
  27.     echo json_encode($out);
  28. ?>
That ends this tutorial. Happy Coding :)

Comments

Hello very good tutorial, but I have a question how to do if I want an input that does not add with 3 that adds, I tried but I encounter problems in the registration, thank you

Add new comment