Add Form Fields Dynamically using AngularJS with PHP/MySQLi

January 25, 2021
PHP
add form fields using angularjs

Tutorial: Add Form Fields Dynamically using AngularJS with PHP/MySQLi with Source Code

About How to Add Form Fields Dynamically using AngularJS

This is a tutorial on how to Add Form Fields Dynamically using AngularJS with PHP/MySQLi. I’ve used CDN for Bootstrap and Angular JS in this tutorial, so you need an internet connection for them to work.

Related Tutorials: Signup and Register using AngularJS, How to Fetch MySQL Data Using AngularJS

Creating a 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.

CREATE TABLE `members` (
  `memid` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` text NOT NULL,
PRIMARY KEY(`memid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
add forms fields dynamically using angularjs

add forms fields dynamically using angularjs

index.html

Next, this is a index that contains an add form.

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <meta charset="utf-8">
    <title>AngularJS Adding Form Fields Dynamically with PHP/MySQLi</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="memberdata" ng-init="fetch()">
<div class="container">
    <h1 class="page-header text-center">AngularJS Adding Form Fields Dynamically with PHP/MySQLi</h1>
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="alert alert-success text-center" ng-show="success">
                <button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">&times;</span></button>
                <i class="fa fa-check"></i> {{ successMessage }}
            </div>
            <div class="alert alert-danger text-center" ng-show="error">
                <button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">&times;</span></button>
                <i class="fa fa-warning"></i> {{ errorMessage }}
            </div>
            <form name="addForm" novalidate>
                <fieldset ng-repeat="memberfield in memberfields">
                    <div class="panel panel-default">
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <input type="text" placeholder="Firstname" class="form-control" ng-model="memberfield.firstname" required>
                                </div>
                                <div class="col-md-3">
                                    <input type="text" placeholder="Lastname" class="form-control" ng-model="memberfield.lastname" required>
                                </div>
                                <div class="col-md-5">
                                    <input type="text" placeholder="Address" class="form-control" ng-model="memberfield.address" required>
                                </div>
                                <button class="btn btn-danger btn-sm" ng-show="$last" ng-click="removeField()"><span class="glyphicon glyphicon-remove"></span></button>
                            </div>
                        </div>
                    </div>
                </fieldset>
                <button type="button" class="btn btn-primary" ng-click="newfield()"><span class="glyphicon glyphicon-plus"></span> Add</button>
                <button type="button" class="btn btn-primary" ng-disabled="addForm.$invalid" ng-click="submitForm()"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
            </form>
            <table class="table table-bordered table-striped" style="margin-top:10px;">
                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Address</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="member in members">
                        <td>{{ member.firstname }}</td>
                        <td>{{ member.lastname }}</td>
                        <td>{{ member.address }}</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<script src="angular.js"></script>
</body>
</html>

angular.js

This contains an angular js scripts.

var app = angular.module('app', []);
app.controller('memberdata', function($scope, $http){
    $scope.success = false;
    $scope.error = false;
 
    $scope.fetch = function(){
    	$http.get("fetch.php").success(function(data){ 
            $scope.members = data; 
        });
    }
 
    $scope.memberfields = [{id: 'field1'}];
 
    $scope.newfield = function(){
        var newItem = $scope.memberfields.length+1;
        $scope.memberfields.push({'id':'field'+newItem});
    }
 
    $scope.submitForm = function(){
        $http.post('add.php', $scope.memberfields)
        .success(function(data){
            if(data.error){
                $scope.error = true;
                $scope.success = false;
                $scope.errorMessage = data.message;
            }
            else{
                $scope.error = false;
                $scope.success = true;
                $scope.successMessage = data.message;
                $scope.fetch();
                $scope.memberfields = [{id: 'field1'}];
            }
        });
    }
 
    $scope.removeField = function() {
        var lastItem = $scope.memberfields.length-1;
        $scope.memberfields.splice(lastItem);
    };
 
    $scope.clearMessage = function(){
    	$scope.success = false;
    	$scope.error = false;
    }
});

fetch.php

This is a PHP api/code that fetches data from a MySQL database.

<?php
    $conn = new mysqli('localhost', 'root', '', 'angular');
 
    $output = array();
    $sql = "SELECT * FROM members";
    $query=$conn->query($sql);
    while($row=$query->fetch_array()){
        $output[] = $row;
    }
 
    echo json_encode($output);
?>

add.php

Lastly, this is a PHP api/code in adding one or multiple rows into a database on how to Add Form Fields Dynamically using AngularJS with PHP/MySQLi.

<?php
    $conn = new mysqli('localhost', 'root', '', 'angular');
 
    $data = json_decode(file_get_contents("php://input"));
 
    $count = count($data);
 
    $out = array('error' => false);
 
    foreach($data as $key => $value){
        $firstname = $value->firstname;
        $lastname = $value->lastname;
        $address = $value->address;
 
        $sql = "INSERT INTO members (firstname, lastname, address) VALUES ('$firstname', '$lastname', '$address')";
        $query = $conn->query($sql);
    }
 
    if($query){
        $out['message'] = "($count) Member/s added successfully";
    }
    else{
        $out['error'] = true;
        $out['message'] = "Cannot add Member(s)";
    }
 
    echo json_encode($out);
?>

Leave a Reply

Your email address will not be published. Required fields are marked *