OOP CRUD Operation using Angularjs in PHP

July 6, 2020
PHP
oop crud operation using php source code

How to Have OOP CRUD Operation using Angularjs in PHP 

Getting Started

Please take note that CSS and angular.js used in this tutorial are hosted, so you need an internet connection for them to work. This tutorial is on how to have an OOP CRUD Operation using Angularjs in PHP with MySQL Database.

Creating a Database

1. Open phpMyAdmin.

2. Click databases, create a database and name it as crud_angular.

3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.

CREATE TABLE `member` (
  `memberid` INT(11) NOT NULL AUTO_INCREMENT,
  `firstname` VARCHAR(50) NOT NULL,
  `lastname` VARCHAR(50) NOT NULL,
PRIMARY KEY(`memberid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

OOP CRUD Operation using Angularjs in PHP

Creating a Connection

Next, we create our connection to our database. This will serve as the bridge between our forms and database. We name this as conn.php.

<?php
 
$conn = new mysqli("localhost", "root", "", "crud_angular");
 
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
 
?>

index.php

This is our index which contains our form and our table.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"> 
    <title>PHP - OOP CRUD Operation using angular.js</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.4.8/angular.min.js"></script>  
</head>
<body>
<div class="container">
    <h1 class="page-header">PHP - OOP CRUD Operation using angular.js</h1>
    <div class="row">
        <div ng-app="mem_app" ng-controller="controller" ng-init="showdata()">
            <div class="col-md-4">
                <form ng-submit="myFunc()">
                    <h3>Member Form</h3>
                    <hr>
                    <div class="form-group">
                    	<label for="firstname">Firstname</label>
                    	<input type="text" class="form-control" id="firstname" name="firstname" ng-model="firstname" placeholder="Enter Firstname">
                  	</div>
                  	<div class="form-group">
                    	<label for="lastname">Lastname</label>
                    	<input type="text" class="form-control" id="lastname" name="lastname" ng-model="lastname" placeholder="Enter Lastname">
                  	</div>
                  	<hr>
                  	<button type="submit" class="{{btnClass}}" ng-click="insert()"><span class="{{icon}}"></span> {{btnName}}</button>
                </form>
            </div>
            <div class="col-md-8">
                <h3>Member List</h3>
                <table class="table table-bordered table-striped">
                    <thead>
                        <th>Firstname</th>
                        <th>Lastname</th>
                        <th>Action</th>
                    </thead>
                    <tbody>
                        <tr ng-repeat="mem in member">
                            <input type="hidden" value="{{mem.memberid}}">
                            <td>{{mem.firstname}}</td>
                            <td>{{mem.lastname}}</td>
                            <td>
                                <button class="btn btn-success" ng-click="update(mem.memberid, mem.firstname, mem.lastname)"><span class="glyphicon glyphicon-pencil"></span> Edit</button> || <button class="btn btn-danger" ng-click="delete(mem.memberid)"><span class="glyphicon glyphicon-trash"></span> Delete</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<script src="myangular.js"></script>
</body>
</html>

myangular.js

This contains our angular js codes.

var app = angular.module("mem_app", []);
app.controller("controller", function($scope, $http) {
    $scope.btnName = "Save";
    $scope.icon = "glyphicon glyphicon-floppy-disk";
    $scope.btnClass = "btn btn-primary";
    $scope.insert = function() {
        if ($scope.firstname == null) {
            alert("Please input Firstname");
        } 
        else if ($scope.lastname == null) {
            alert("Please input Lastname");
        }  
        else {
            $http.post(
                "action.php", {
                    'firstname': $scope.firstname,
                    'lastname': $scope.lastname,
                    'btnName': $scope.btnName,
                    'memberid': $scope.memberid,
                }
            ).success(function(data) {
                alert(data);
                $scope.firstname = null;
                $scope.lastname = null;
                $scope.btnName = "Save";
                $scope.icon = "glyphicon glyphicon-floppy-disk";
                $scope.btnClass = "btn btn-primary";
                $scope.showdata();
            });
        }
    }
    $scope.showdata = function() {
        $http.get("fetch.php")
            .success(function(data) {
                $scope.member = data;
            });
    }
    $scope.update = function(memberid, firstname, lastname) {
        $scope.memberid = memberid;
        $scope.firstname = firstname;
        $scope.lastname = lastname;
        $scope.icon = "glyphicon glyphicon-check";
        $scope.btnClass = "btn btn-success";
        $scope.btnName = "Update";
    }
    $scope.delete= function(memberid) {
        if (confirm("Are you sure you want to delete member?")) {
            $http.post("delete.php", {
                    'memberid': memberid
                })
                .success(function(data) {
                    alert(data);
                    $scope.showdata();
                });
        } else {
            return false;
        }
    }
});

fetch.php

This is our PHP code in fetching data from our database to show in our table.

<?php
    include('conn.php');
    $output = array();
    $query = $conn->query("select * from member"); 
    if ($query->num_rows > 0) {
        while ($row = $query->fetch_array()) {
            $output[] = $row;
        }
        echo json_encode($output);
    }
?>

action.php

This contains our insert and update PHP code.

<?php
    include('conn.php');
    $info = json_decode(file_get_contents("php://input"));
    if (count($info) > 0) {
        $firstname = mysqli_real_escape_string($conn, $info->firstname);
        $lastname = mysqli_real_escape_string($conn, $info->lastname);
        $btn_name = $info->btnName;
        if ($btn_name == "Save") {
            if ($conn->query("insert into member (firstname, lastname) values ('$firstname', '$lastname')")) {
                echo "Member Added Successfully";
            } else {
                echo 'Failed';
            }
        }
        if ($btn_name == "Update") {
            $id    = $info->memberid;
            if ($conn->query("update member set firstname='$firstname', lastname='$lastname' where memberid='$id'")) {
                echo 'Member Updated Successfully';
            } else {
                echo 'Failed';
            }
        }
    }
?>

delete.php

Lastly, this is our PHP delete code.

<?php
    include('conn.php');
    $data = json_decode(file_get_contents("php://input"));
    if (count($data) > 0) {
        $id = $data->memberid;
        if ($conn->query("delete from member where memberid='$id'")) {
            echo 'Member Deleted Successfully';
        } else {
            echo 'Failed';
        }
    }
?>

That ends this tutorial. If you have any question, comment or suggestion, feel free to write it below or message me. Happy Coding!

Download Here

Leave a Reply

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