article

Thursday, December 23, 2021

AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)

AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)

https://angularjs.org/ version 1.8.2

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

Database Table

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'),
(6, 'Brielle', 'Williamson', 'New York'),
(7, 'Bruno', 'Nash', 'London'),
(8, 'Caesar', 'Vance', 'New York'),
(9, 'Cara', 'Stevens', 'New York'),
(10, 'Cedric', 'Kelly', 'Edinburgh');

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

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
index.html
//index.html
<html>  
<head>  
<title>AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)</title>  
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>  
<body>  
<div class="container"><br />
    <h3 align="center">AngularJS PHP Mysql PDO Inline Table CRUD (Create, Read, Update and Delete)</h3><br />
    <div class="table-responsive" ng-app="angularinlinetablecrud" ng-controller="liveController" ng-init="fetchData()">
                <div class="alert alert-success alert-dismissible" ng-show="success" >
                    <a href="#" class="close" data-dismiss="alert" ng-click="closeMsg()" aria-label="close">×</a>
                    {{successMessage}}
                </div>
                <form name="testform" ng-submit="insertData()">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Address</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" ng-model="addData.firstname" class="form-control" placeholder="Enter First Name" ng-required="true" /></td>
                                <td><input type="text" ng-model="addData.lastname" class="form-control" placeholder="Enter Last Name" ng-required="true" /></td>
                                <td><input type="text" ng-model="addData.address" class="form-control" placeholder="Enter Address" ng-required="true" /></td>
                                <td><button type="submit" class="btn btn-success btn-sm" ng-disabled="testform.$invalid">Add</button></td>
                            </tr>
                            <tr ng-repeat="data in namesData" ng-include="getTemplate(data)">
                            </tr>
                            
                        </tbody>
                    </table>
                </form>
                <script type="text/ng-template" id="display">
                    <td>{{data.firstname}}</td>
                    <td>{{data.lastname}}</td>
                    <td>{{data.address}}</td>
                    <td>
                        <button type="button" class="btn btn-primary btn-sm" ng-click="showEdit(data)">Edit</button>
                        <button type="button" class="btn btn-danger btn-sm" ng-click="deleteData(data.id)">Delete</button>
                    </td>
                </script>
                <script type="text/ng-template" id="edit">
                    <td><input type="text" ng-model="formData.firstname" class="form-control"  /></td>
                    <td><input type="text" ng-model="formData.lastname" class="form-control" /></td>
                    <td><input type="text" ng-model="formData.address" class="form-control" /></td>
                    <td>
                        <input type="hidden" ng-model="formData.data.id" />
                        <button type="button" class="btn btn-info btn-sm" ng-click="editData()">Save</button>
                        <button type="button" class="btn btn-default btn-sm" ng-click="reset()">Cancel</button>
                    </td>
                </script>   

				<!--<div id="output">{{ foo }}</div> -->
   </div>  
  </div>
<script>
var app = angular.module('angularinlinetablecrud', []);

app.controller('liveController', function($scope, $http){

    $scope.formData = {};
    $scope.addData = {};
    $scope.success = false;

    $scope.getTemplate = function(data){ //alert(data.id);
        if (data.id === $scope.formData.id)
        {
            return 'edit';
        }
        else
        {
            return 'display';
        }
    };

    $scope.fetchData = function(){
		   $http({
			  method: 'GET',
			  url: 'select.php'
		   }).then(function (data){
				console.log(data)
				$scope.namesData = data.data;
				//$scope.foo = data.data;
		   },function (error){
				console.log(error, 'can not get data.');
		   });
    };

    $scope.insertData = function(){
        $http({
            method:"POST",
            url:"insert.php",
            data:$scope.addData,
        }).then(function(data){ alert(data.data.message);
            $scope.success = true;
            $scope.successMessage = data.data.message;
            $scope.fetchData();
            $scope.addData = {};
        });
    };

    $scope.showEdit = function(data) {
        $scope.formData = angular.copy(data);
    };

    $scope.editData = function(){
        $http({
            method:"POST",
            url:"edit.php",
            data:$scope.formData,
        }).then(function(data){
            $scope.success = true;
            $scope.successMessage = data.data.message;
            $scope.fetchData();
            $scope.formData = {};
        });
    };

    $scope.reset = function(){
        $scope.formData = {};
    };

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

    $scope.deleteData = function(id){
        if(confirm("Are you sure you want to remove it?"))
        {
            $http({
                method:"POST",
                url:"delete.php",
                data:{'id':id}
            }).then(function(data){
                $scope.success = true;
                $scope.successMessage = data.data.message;
                $scope.fetchData();
            }); 
        }
    };

});
</script>
</body>  
</html>  
db.php
//db.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=testingdb", "root", "");
?>
select.php
//select.php
<?php  
include('db.php');

$query = "SELECT * FROM members ORDER BY id DESC";
$statement = $connect->prepare($query);
if($statement->execute())
{
  while($row = $statement->fetch(PDO::FETCH_ASSOC))
  {
    $data[] = $row;
  }
  echo json_encode($data);
}
?>
insert.php
//insert.php
<?php  
include('db.php');

$message = '';

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

$data = array(
 ':firstname'  => $form_data->firstname,
 ':lastname'  => $form_data->lastname,
 ':address'  => $form_data->address
);

$query = "
 INSERT INTO members 
 (firstname, lastname, address) VALUES 
 (:firstname, :lastname, :address)
";

$statement = $connect->prepare($query);

if($statement->execute($data))
{
 $message = 'Data Inserted';
}

$output = array(
 'message' => $message
);

echo json_encode($output);
?>
edit.php
//edit.php
<?php  
include('db.php');

$message = '';

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

$data = array(
 ':firstname'  => $form_data->firstname,
 ':lastname'  => $form_data->lastname,
 ':address'  => $form_data->address,
 ':id'    => $form_data->id
);

$query = "
 UPDATE members 
 SET firstname = :firstname, lastname = :lastname , address = :address 
 WHERE id = :id
";

$statement = $connect->prepare($query);
if($statement->execute($data))
{
 $message = 'Data Edited';
}

$output = array(
 'message' => $message
);

echo json_encode($output);
?>
delete.php
//delete.php
<?php
include('db.php');

$message = '';

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

$query = "DELETE FROM members WHERE id = '".$form_data->id."'";

$statement = $connect->prepare($query);
if($statement->execute())
{
 $message = 'Data Deleted';
}

$output = array(
 'message' => $message
);

echo json_encode($output);
?>

Related Post