article

Wednesday, January 26, 2022

AngularJS Delete Multiple Rows with PHP MySQLi

AngularJS Delete Multiple Rows with PHP MySQLi

Bootstrap 5.1 Version
https://getbootstrap.com/docs/5.1/getting-started/introduction/

angularjs CDN
https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js


CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) 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'),
(40, 'Brielle', 'Williamson', 'New York'),
(54, 'Bruno', 'Nash', 'London'),
(55, 'Caesar', 'Vance', 'New York'),
(56, 'Cara', 'Stevens', 'New York'),
(57, 'Cedric', 'Kelly', 'Edinburgh'),
(58, 'Zorita Serran', 'Satou', 'Tokyo'),
(59, 'Angelica ', 'Ramos', 'London'),
(60, 'Ashton ', 'Cox', 'San Francisco'),
(61, 'Bradley ', 'Greer', 'London'),
(62, 'Brenden ', 'Wagner', 'San Francisco'),
(63, 'Brielle', 'Williamson', 'New York'),
(64, 'Bruno', 'Nash', 'London'),
(65, 'Caesar', 'Vance', 'New York'),
(66, 'Cara', 'Stevens', 'New York'),
(67, 'Brenden ', 'Wagner', 'San Francisco'),
(68, 'Brielle', 'Williamson', 'New York'),
(69, 'Bruno', 'Nash', 'London'),
(70, 'Caesar', 'Vance', 'New York'),
(71, 'Cara', 'Stevens', 'New York'),
(72, 'Cedric', 'Kelly', 'Edinburgh');

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

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

index.html
//index.html
<!DOCTYPE html>
<html lang="en" ng-app="deletemultiplerow">
<head>
<meta charset="utf-8">
<title>AngularJS Delete Multiple Rows with PHP MySQLi</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="MemberCtr" ng-init="fetch()">
<div class="container">
    <h1 class="page-header text-center">AngularJS Delete Multiple Rows with PHP MySQLi</h1>
    <div class="row">
		<div class="col-10 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">×</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">×</span></button>
				<i class="fa fa-warning"></i> {{ errorMessage }}
			</div>
			
			<button class="btn btn-danger" ng-click="deleteAll()">Delete</button>
			
			<table class="table table-bordered table-striped" style="margin-top:10px;">
				<thead>
                    <tr>
                    	<th><input type="checkbox" ng-model="checkAll" ng-change="toggleAll()"></th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Address</th>
                   </tr>
                </thead>
				<tbody>
					<tr ng-repeat="member in members">
						<td><input type="checkbox" ng-model="member.Selected" ng-change="toggleOne()"></td>
						<td>{{ member.firstname }}</td>
						<td>{{ member.lastname }}</td>
						<td>{{ member.address }}</td>
					</tr>
				</tbody>
			</table>
			</div>
		</div>
	</div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
//script.js
var app = angular.module('deletemultiplerow', []);
app.controller('MemberCtr',function($scope, $http){
    $scope.success = false;
    $scope.error = false;

    $scope.fetch = function(){
		$http({
            method: 'GET',
            url: 'fetch.php',
        }).then(function (data){
            console.log(data)
            $scope.members = data.data;      
        },function (error){
            console.log(error, 'can not get data.');
        });
    }

    $scope.toggleAll = function(){
        for (var i = 0; i < $scope.members.length; i++) {
            $scope.members[i].Selected = $scope.checkAll;
        }
    };

    $scope.toggleOne = function(){
        $scope.checkAll = true;
        for (var i = 0; i < $scope.members.length; i++) {
            if (!$scope.members[i].Selected) {
                $scope.checkAll = false;
                break;
            }
        };
    };
        
    $scope.deleteAll = function(){
        checkedId = [];
        for (var i = 0; i < $scope.members.length; i++) {
            if ($scope.members[i].Selected) {
                checkedId.push($scope.members[i].id);
            }
        }
		$http({
            method: 'POST',
            url: 'delete.php',
			data:checkedId,
        }).then(function (data){
            console.log(data);
            if(data.data.error){
                $scope.error = true;
                $scope.success = false;
                $scope.errorMessage = data.data.message;
                $scope.checkAll = false;
            }
            else{
                $scope.success = true;
                $scope.error = false;
                $scope.successMessage = data.data.message;
                $scope.fetch();
                $scope.checkAll = false;
            }     
        },function (error){
            console.log(error, 'can not get data.');
        });
		
    }

    $scope.clearMessage = function(){
    	$scope.success = false;
    	$scope.error = false;
    }

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

	echo json_encode($output);
?>
delete.php
//delete.php
<?php
  $conn = new mysqli('localhost', 'root', '', 'testingdb');

  $data = json_decode(file_get_contents("php://input"));

  $out = array('error' => false);
  
  foreach ($data as $key => $value) {
    $sql = "DELETE FROM members WHERE id = '".$value."'";
    $query = $conn->query($sql);
  }

  if($query){
    $out['message'] = "Member(s) deleted Successfully";
  }
  else{
    $out['error'] = true;
    $out['message'] = "Something went wrong. Cannot delete Member(s)";
  }

  echo json_encode($out);
?>

Related Post