article

Tuesday, December 7, 2021

AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi

AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi

https://angularjs.org/

HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your application. 

CND : https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

AngularUI Router https://github.com/angular-ui/ui-router

Angular UI-Router is a client-side Single Page Application routing framework for AngularJS. Routing frameworks for SPAs update the browser's URL as the user navigates through the app.

CDN Minified : http://unpkg.com/@uirouter/angularjs@latest/release/angular-ui-router.min.js

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi ', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley ', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(6, 'Brielle ', 'Williamson', 'New York');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;


index.html
//index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="https://unpkg.com/@uirouter/angularjs@1.0.30/release/angular-ui-router.min.js"></script>
</head>
<body ng-app="appcrudrouter">
<nav class="navbar navbar-inverse" role="navigation">
    <div class="navbar-header">
        <a class="navbar-brand" ui-sref="#">AngularUI Router</a>
    </div>
    <ul class="nav navbar-nav">
        <li><a ui-sref="home">Home</a></li>
        <li><a ui-sref="about">About</a></li>
        <li><a ui-sref="contact">Contact</a></li>
    </ul>
</nav>
<div class="container">
    <h1 class="page-header text-center">AngularJS CRUD(Create, Read, Update and Delete) with UI-Router and PHP MySQLi</h1>
    <div ui-view></div>
</div>
<script>
var app = angular.module('appcrudrouter', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {
    
    $urlRouterProvider.otherwise('/home');
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'pages/home.html',
            controller: 'homeCtrl'
        })
        .state('add', {
            url: '/add',
            templateUrl: 'pages/add.html',
            controller: 'addCtrl'
        })
        .state('edit', {
            url: '/edit/{member:json}',
            templateUrl: 'pages/edit.html',
            controller: 'editCtrl'
        })
        .state('delete', {
            url: '/delete/{member:json}',
            templateUrl: 'pages/delete.html',
            controller: 'deleteCtrl'
        })
      
	    .state('about', {
            url: '/about',
            templateUrl: 'pages/about.html',
             controller: function($scope) {
                $scope.animals = [{id:1,name:'Dog'},
                {id:2,name:'Cat'}];
            }
        })
		
		.state('about.list', {
            url: '/list/:id',
            templateUrl: 'pages/list.html',
            controller: function($scope,$stateParams) {
                $scope.num = $stateParams.id;
            }
        })
});
</script>
<script src="js/homeController.js"></script>
<script src="js/addController.js"></script>
<script src="js/editController.js"></script>
<script src="js/deleteController.js"></script>
<script src="js/memberService.js"></script>
</body>
</html>
js/addController.js
//js/addController.js
'use strict';

app.controller('addCtrl', ['$scope', 'memberService', '$location', function($scope, memberService, $location){
	$scope.error = false;
	//add member
	$scope.add = function(){
		var addmember = memberService.create($scope.member);
		addmember.then(function(response){
			if(response.data.error){
				$scope.error = true;
				$scope.message = response.data.message;
			}
			else{
				console.log(response);
				$location.path('home');
			}
		});
	}

}]);
js/deleteController.js
//js/deleteController.js
'use strict';

app.controller('deleteCtrl', ['$scope', 'memberService', '$location', '$stateParams', function($scope, memberService, $location, $stateParams){
	$scope.error = false;
	$scope.deletemember = $stateParams.member;

	//delete member
	$scope.delete = function(){
		var dmember = memberService.delete($scope.deletemember);
		dmember.then(function(response){
			if(response.data.error){
				$scope.error = true;
				$scope.message = response.data.message;
			}
			else{
				console.log(response);
				$location.path('home');
			}
		});
	}
}]);
js/editController.js
//js/editController.js
'use strict';

app.controller('editCtrl', ['$scope', 'memberService', '$location', '$stateParams', function($scope, memberService, $location, $stateParams){
	$scope.error = false;
	$scope.updatedmember = $stateParams.member;

	//edit member
	$scope.update = function(){
		var updatemember = memberService.update($scope.updatedmember);
		updatemember.then(function(response){
			console.log(response);
			if(response.data.error){
				$scope.error = true;
				$scope.message = response.data.message;
			}
			else{
				console.log(response);
				$location.path('home');
			}
		});
	}

}]);
js/homeController.js
//js/homeController.js
'use strict';

app.controller('homeCtrl', ['$scope', 'memberService', function($scope, memberService){
	//fetch members
	$scope.fetch = function(){
		var members = memberService.read();
		members.then(function(response){
			$scope.members = response.data;
		});
	}

}]);
js/memberService.js
//js/memberService.js
'use strict';

app.factory('memberService', function($http){
	return{
		read: function(){
			var read = $http.get('api/read.php');
			return read;
		},
		create: function(member){
			var add = $http.post('api/add.php', member);
			return add;
		},
		update: function(member){
			var edit = $http.post('api/edit.php', member);
			return edit;
		},
		delete: function(member){
			var del = $http.post('api/delete.php', member);
			return del;
		}
	}
});
pages/home.html
//pages/home.html
<div class="row" ng-init="fetch()">
	<div class="col-md-12">
		<button href="" class="btn btn-primary" ui-sref="add"><i class="fa fa-plus"></i> Add New</button>	
		<table class="table table-bordered table-striped" style="margin-top:10px;">
			<thead>
                <tr>
                    <th>Firstname</th>
                   	<th>Lastname</th>
                    <th>Address</th>
                   	<th width="200">Action</th>
                </tr>
            </thead>
			<tbody>
				<tr ng-repeat="member in members">
					<td>{{ member.firstname }}</td>
					<td>{{ member.lastname }}</td>
					<td>{{ member.address }}</td>
					<td>
						<button type="button" class="btn btn-success" ui-sref="edit({member: member})"><i class="fa fa-edit"></i> Edit</button> 
						<button type="button" class="btn btn-danger" ui-sref="delete({member: member})"> <i class="fa fa-trash"></i> Delete</button>
					</td>
				</tr>
			</tbody>
		</table>
	</div>
</div>
pages/add.html
//pages/add.html
<div class="row">
	<div class="col-sm-6">
		<div class="alert alert-danger text-center" ng-show="error">
			<button type="button" class="close" ng-click="clear()"><span aria-hidden="true">×</span></button>
			<i class="fa fa-warning"></i> {{ message }}
		</div>
		<div class="panel panel-default">
			<div class="panel-body">
				<h3 class="text-center">Add Form</h3>
				<div class="form-group">
					<label>Firstname:</label>
					<input type="text" class="form-control" ng-model="member.firstname">
				</div>
				<div class="form-group">
					<label>Lastname:</label>
					<input type="text" class="form-control" ng-model="member.lastname">
				</div>
				<div class="form-group">
					<label>Address:</label>
					<input type="text" class="form-control" ng-model="member.address">
				</div>
				<button type="button" class="btn btn-primary" ng-click="add()"><i class="fa fa-save"></i> Save</button>
				<button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
			</div>
		</div>
	</div>
</div>
pages/edit.html
//pages/edit.html
<div class="row">
	<div class="col-sm-6">
		<div class="alert alert-danger text-center" ng-show="error">
			<button type="button" class="close" ng-click="clear()"><span aria-hidden="true">×</span></button>
			<i class="fa fa-warning"></i> {{ message }}
		</div>
		<div class="panel panel-default">
			<div class="panel-body">
				<h3 class="text-center">Edit Form</h3>
				<div class="form-group">
					<label>Firstname:</label>
					<input type="text" class="form-control" ng-model="updatedmember.firstname">
				</div>
				<div class="form-group">
					<label>Lastname:</label>
					<input type="text" class="form-control" ng-model="updatedmember.lastname">
				</div>
				<div class="form-group">
					<label>Address:</label>
					<input type="text" class="form-control" ng-model="updatedmember.address">
				</div>
				<button type="button" class="btn btn-success" ng-click="update()"><i class="fa fa-check-square-o"></i> Update</button>
				<button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
			</div>
		</div>
	</div>
</div>
pages/delete.html
//pages/delete.html
<div class="row">
    <div class="col-sm-6">
        <div class="alert alert-danger text-center" ng-show="error">
            <button type="button" class="close" ng-click="clear()"><span aria-hidden="true">×</span></button>
            <i class="fa fa-warning"></i> {{ message }}
        </div>
        <div class="panel panel-default">
            <div class="panel-body">
                <h4 class="text-center">Are you sure you want to delete</h4>
                <h3 class="text-center">{{ deletemember.firstname + ' ' + deletemember.lastname }}</h3><br>
                <button type="button" class="btn btn-danger" ng-click="delete()"><i class="fa fa-trash"></i> Delete</button>
                <button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
            </div>
        </div>
    </div>
</div>
pages/about.html
//pages/about.html
<div>
    <h1>About Page</h1>
    <p>This page demonstrates <span class="text-danger">multiple</span> and <span class="text-danger">named</span> views.</p>
</div>
<div class="row">
       <ul>
        <li ng-repeat="an in animals">
            <a ui-sref="about.list({id:an.id})">{{an.name}}</a>
        </li>
    </ul>
	<div ui-view></div>
</div>
pages/list.html
//pages/list.html
<div ng-if="num == 1"><strong>Dog</strong> is clicked</div>
<div ng-if="num == 2"><strong>Cat</strong> is clicked</div>
api/add.php
//api/add.php
<?php
    include('dbcon.php');
    
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false, 'firstname' => false, 'lastname' => false, 'address' => false);

    $firstname = $data->firstname;
    $lastname = $data->lastname;
    $address = $data->address;

    if(empty($firstname)){
        $out['firstname'] = true;
        $out['message'] = 'Firstname is required'; 
    } 
    elseif(empty($lastname)){
        $out['lastname'] = true;
        $out['message'] = 'Lastname is required'; 
    }
    elseif(empty($address)){
        $out['address'] = true;
        $out['message'] = 'Address is required'; 
    }
    else{
        $sql = "INSERT INTO members (firstname, lastname, address) VALUES ('$firstname', '$lastname', '$address')";
        $query = $conn->query($sql);

        if($query){
            $out['message'] = 'Member Added Successfully';
        }
        else{
            $out['error'] = true;
            $out['message'] = 'Cannot Add Member';
        }
    }
        
    echo json_encode($out);
?>
api/read.php
//api/read.php
<?php
	include('dbcon.php');
	
	$out = array();
	$sql = "SELECT * FROM members";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$out[] = $row;
	}

	echo json_encode($out);
?>
api/edit.php
//api/edit.php
<?php
    include('dbcon.php');
    
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false);

    $firstname = $data->firstname;
    $lastname = $data->lastname;
    $address = $data->address;
    $memid = $data->id;

   	$sql = "UPDATE members SET firstname = '$firstname', lastname = '$lastname', address = '$address' WHERE id = '$memid'";
   	$query = $conn->query($sql);

   	if($query){
   		$out['message'] = 'Member updated Successfully';
   	}
   	else{
   		$out['error'] = true;
   		$out['message'] = 'Cannot update Member';
   	}

    echo json_encode($out);
?>
api/delete.php
//api/delete.php
<?php
    include('dbcon.php');
    
    $data = json_decode(file_get_contents("php://input"));

    $out = array('error' => false);

    $memid = $data->id;

   	$sql = "DELETE FROM members WHERE id = '$memid'";
   	$query = $conn->query($sql);

   	if($query){
   		$out['message'] = 'Member deleted Successfully';
   	}
   	else{
   		$out['error'] = true;
   		$out['message'] = 'Cannot delete Member';
   	}

    echo json_encode($out);
?>
api/dbcon.php
//api/dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Related Post