Skip to main content

simple CRUD based Web API using Angular JS as middleware and PHP Core for backend service

In this, tutorial, we are going to create a simple CRUD based Web API using Angular JS as middleware and PHP Core for backend service. This tutorial here aims at explaining how to create AngularJS application utilizing PHP Web Services and MySQL Database. We may skip the basic concept of AngularJS which is not part of this tutorial but you can get those concepts from the official documentation of Angular JS. We may skip the basic concept of AngularJS which is not part of this tutorial but you can get those concepts from the official documentation of AngularJS.


Database:

After starting Apache and MySQL ports from XAMPP or any other local server deployment application, first of all we need to create a database called “api” in phpmyadmin and create a table named “tbl_users” under the database with four attributes, ‘u_id‘, ‘u_name‘, ‘u_age‘, ‘u_phone‘, you can do that by using the Graphical User Interface (GUI) or running the following script:

-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 10, 2020 at 09:46 PM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.2.33

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `api`
--

DELIMITER $$
--
-- Procedures
--
CREATE DEFINER=`root`@`localhost` PROCEDURE `st_deleteUser` (`id` INT) BEGIN
     DELETE FROM tbl_users WHERE u_id = id;
    END$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `st_getUser` () BEGIN
     SELECT u.u_id as "ID",
            u.u_name as "Name",
               u.u_age as "Age",
               u.u_phone as "Phone"
               
               FROM tbl_users u
               ORDER BY u.u_id ASC;
    END$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `st_insertUser` (IN `name` VARCHAR(30), IN `age` TINYINT, IN `phone` VARCHAR(15)) BEGIN
     INSERT INTO tbl_users (u_name, u_age, u_phone) VALUES (name, age, phone);
    END$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `st_updateUser` (`name` VARCHAR(30), `age` TINYINT, `phone` VARCHAR(15), `id` INT) BEGIN
     UPDATE tbl_users SET 
         u_name = name,
            u_age = age,
            u_phone = phone
             WHERE 
            u_id = id;
    END$$

DELIMITER ;

-- --------------------------------------------------------

--
-- Table structure for table `tbl_users`
--

CREATE TABLE `tbl_users` (
  `u_id` int(11) NOT NULL,
  `u_name` varchar(30) NOT NULL,
  `u_age` tinyint(4) NOT NULL,
  `u_phone` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_users`
--
ALTER TABLE `tbl_users`
  ADD PRIMARY KEY (`u_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_users`
--
ALTER TABLE `tbl_users`
  MODIFY `u_id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
view rawapi.sql hosted with ❤ by GitHub
Backend API:

Once the database is done, let’s move towards setting up your back end. We will create the Web API project in Visual Studio Code or any Text Editor of your choice and steps are pretty simple:

Step 1:

Open the location where your local server application like XAMPP/WAP is installed and go to directory called “C/xampp/htdocs“, this is the default server configuration of mine, you might have your own so you can navigate to your respective folder and create a directory named “api“. Boo yeah, you have created the folder. Time to connect the database in your app. A small reminder, your link will be like C/xampp/htdocs/api.

Step 2:

Now, start VS Code and open the folder you just created. Create a file including a connection to the database. Create a file named “connection.php”.

<?php
    $con = mysqli_connect("localhost", "root", "", "api");
    if($con) {
        // echo "Connection Established";
    } else {
        die();
    }
?>
view rawconnection.php hosted with ❤ by GitHub
Step 3:

Try running the connection.php file in the browser by typing “localhost/api/connection.php” as the URL, if it returns “Connection Established“ you are good to continue.

Step 4:

Now create “insert.php” file and write the following code mentioned below. This file will be responsible for carrying out and handling the Request and Response system in the API whenever we insert data.

<?php
    require "connection.php";
    $data = json_decode(file_get_contents("php://input"));
        $name = $data->name;
        $age = $data->age;
        $phone = $data->phone;

    $query = "CALL st_insertUser('$name', $age, '$phone')";

    if(mysqli_query($con, $query)) {
        $response["msg"] = "User added successfully";
    } else {
        $response["msg"] = "Add user response from server failed";
    }

    echo json_encode($response);
?>
view rawinsert.php hosted with ❤ by GitHub
Step 5:

Now create the “update.php” file and write the following code mentioned below. This file will be responsible for carrying out and handling the Request and Response system in the API whenever we update data.

<?php
    require "connection.php";
    $data = json_decode(file_get_contents("php://input"));
        $id = $data->id;
        $name = $data->name;
        $age = $data->age;
        $phone = $data->phone;

    $query = "CALL st_updateUser('$name', $age, '$phone', $id)";

    if(mysqli_query($con, $query)) {
        $response["msg"] = "User update response from server was a success ";
    } else {
        $response["msg"] = "User update response from server failed";
    }

    echo json_encode($response);
?>
view rawupdate.php hosted with ❤ by GitHub
Step 6:

Now create the “select.php” file and write the following code mentioned below. This file will be responsible for carrying out and handling the Request and Response system in the API whenever we select data.

<?php
    require "connection.php";

    $query = "CALL st_getUser()";
    $response = array();
    $res = mysqli_query($con, $query);

    if(mysqli_num_rows($res)) {
        while($row = mysqli_fetch_assoc($res)) {
            $response[] = $row;
        }
    } else {
        $response["msg"] = "No records";
    }

    echo json_encode($response);
?>
view rawselect.php hosted with ❤ by GitHub
Step 7:

Now create the “select.php” file and write the following code mentioned below. This file will be responsible for carrying out and handling the Request and Response system in the API whenever we select data.

<?php
    require "connection.php";
    $data = json_decode(file_get_contents("php://input"));
        $id = $data->id;

    $query = "CALL st_deleteUser($id)";

    if(mysqli_query($con, $query)) {
        $response["msg"] = "User deleted response from server was a success ";
    } else {
        $response["msg"] = "Delete user response from server failed";
    }

    echo json_encode($response);
?>
view rawdelete.php hosted with ❤ by GitHub
We know from the name of the files that they are performing a specific function, but if we use them, what will be point of using an API, to create a front end, it will be a singular HTML file, yes an HTML file, because that is the point of our API, it is sending request to the server which is responding us with some result. This file is basically the visual interface for our API since all the above files are the backend.

Frontend Framework

Create a “home.html” file and write the following code as shown below.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="Description" content="Enter your description here" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.0/css/all.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <!-- Angular Script -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>
    <title>Angular JS CRUD API</title>
    <style>
      //Color for jumbotron
        .jumbotron {
            background-color: rgba(73, 104, 105, 0.486);
        }
    </style>
</head>

<body ng-app="myApp" ng-controller="myCont">
    <div class="container" ng-init="retrieve(); btnName='SAVE'">
        <div class="jumbotron">
            <h3 class="text-center">Angular and PHP based Application Programming Interface</h3>
        </div>
        <div class="col-8 offset-2">
            <div class="form-group">
                <label for="name">Name: </label>
                <input type="text" class="form-control form-control-sm" ng-model="nameTxt" placeholder="Enter your name (e.g. Ali)">
            </div>

            <div class="form-group">
                <label for="name">Age: </label>
                <input type="text" class="form-control form-control-sm" ng-model="ageTxt" placeholder="Enter your age (e.g. 23)">
            </div>

            <div class="form-group">
                <label for="name">Phone: </label>
                <input type="text" class="form-control form-control-sm" ng-model="phoneTxt" placeholder="Enter number (e.g. 0900-78601)">
            </div>

            <div class="form-group">
                <input type="button" class="btn btn-dark btn-sm col-12" value="{{btnName}}" ng-click="insert()">
            </div>
            <p class="text-center alert alert-dark">{{ message }}</p>
            <hr />
            <table class="table table-secondary table-bordered">
                <thead>
                    <th class="text-center text-uppercase">S. No</th>
                    <th class="text-center text-uppercase">Name</th>
                    <th class="text-center text-uppercase">Age</th>
                    <th class="text-center text-uppercase">Phone</th>
                    <th class="text-center text-uppercase" colspan="2">Actions</th>
                </thead>

                <tbody>
                    <tr ng-repeat="x in myData">
                        <td>{{ x.ID }}</td>
                        <td>{{ x.Name }}</td>
                        <td>{{ x.Age }}</td>
                        <td>{{ x.Phone }}</td>
                        <td class="text-center" colspan="2">
                            <button class="btn btn-info" ng-click="edit(x.ID, x.Name, x.Age, x.Phone)">Edit</button>
                            <button class="btn btn-danger" ng-click="delete(x.ID)">Delete</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <script>
        var app = angular.module("myApp", []);
        app.controller("myCont", function($scope, $http) {
            //Data Deletion Starts
            $scope.delete = function(id) {
                $http.post("delete.php", {
                    'id': id
                }).then(function($response) {
                    $scope.message = $response.data.msg;
                    console.log($scope.message);
                    $scope.retrieve();
                    $scope.nameTxt = "";
                    $scope.ageTxt = "";
                    $scope.phoneTxt = "";
                });
            };
            //Data Deletion Ends
            //Data Fetching For Updation Starts
            $scope.edit = function(id, name, age, phone) {
                $scope.nameTxt = name;
                $scope.ageTxt = age;
                $scope.phoneTxt = phone;
                $scope.userID = id;
                $scope.btnName = "UPDATE";
            };
            //Data Fetching For Updation Ends

            $scope.insert = function() {
                //Data Updation Starts
                if ($scope.btnName == "UPDATE") {
                    $http.post("update.php", {
                        'id': $scope.userID,
                        'name': $scope.nameTxt,
                        'age': $scope.ageTxt,
                        'phone': $scope.phoneTxt
                    }).then(function($response) {
                        $scope.message = $response.data.msg;
                        $scope.nameTxt = "";
                        $scope.ageTxt = "";
                        $scope.phoneTxt = "";
                        $scope.userID = 0;
                        console.log($scope.message);
                        $scope.retrieve();
                    });
                    //Data Updation Ends
                } else {
                    // Data Insertion Starts
                    $http.post("insert.php", {
                        'name': $scope.nameTxt,
                        'age': $scope.ageTxt,
                        'phone': $scope.phoneTxt
                    }).then(function($response) {
                        $scope.message = $response.data.msg;
                        $scope.nameTxt = "";
                        $scope.ageTxt = "";
                        $scope.phoneTxt = "";
                        console.log($scope.message);
                        $scope.retrieve();
                    });
                    // Data Insertion Ends
                }

            };
            // Data Retrieval Starts
            $scope.retrieve = function() {
                $http.get('select.php').then(function($response) {
                    $scope.myData = $response.data;
                    console.log("$scope.myData");
                });
            };
        });
        // Data Retrieval Ends
    </script>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>

</html>
view rawhome.html hosted with ❤ by GitHub
On line 73 and forward of home.html basically, what we are doing is naming the angular module with the name “myApp” and defining it’s controller as “myCont“. Dependencies which we used are “$scope” (the glue between application controller and the view) and insert, update, select and delete files.

Then we create delete, insert, edit and retrieve methods which will be called from our view (home.html) to our controllers, the respective php files for each function by sending a request as seen with $http.post(“<controllers>.php”).

Basically, the point of this file is Angular JS sending a request to the server, the Angular code and callback functions are point to the specific pages where the request is being sent using a specific code block. This is what is the cause behind our HTML page inserting, updating, deleting and fetching the data on the webserver. And there guys, we have our code completed. Try running you API with going to the browser and posting the following URL, “localhost/api/home.html” and boo yeah, you have a working API. with complete CRUD (Create, Read, Update and Delete) function.

NOTE:

You will have to enter the first port number that you see under the Ports section of XAMPP. I have 80 so I do not have to pass it in my URL, if you have 81, 90 or 8080, you will have to enter your port after “localhost:<your-port>/api/home.html“.

Comments

Popular posts from this blog

IOT Projects souce code

IOT  Projects souce code What is IoT? The Internet of Things (IoT) is a network where everyday objects like devices, vehicles, and appliances have sensors and internet connectivity. It lets them gather and share data, work together, and perform tasks without human control. This helps boost automation and efficiency across different areas. You can learn IoT to understand its core components and get further knowledge of its functionalities. 20 IoT Projects with Source Code When it comes to IoT, there are many interesting ideas to explore, from making your home smarter to making an autonomous drone. No matter if you’re just starting or have experience, here are 20 Internet of things projects for beginners and advanced professionals. Simple IoT Project Ideas for Beginners For beginner-level, you can start with simple and fun IoT project ideas that involve basic components like sensors, actuators, and microcontrollers. Below are a few of them: 1. Smart Home Automation Smart home automat...

Connecting R to MySql in English #Training Trains

software design institute training

  ONLINE-OFFLINE IN-PLANT/INTERNSHIP With Certificate Training For B.E(ECE,EEE,CSE,IT,AI,ML,DataScience,Cyper Security),MCA, B.Sc,M.E,M.Tech. @ TrainingTrains.Online Classes Available 100 % Job placement Training Full Stack Developer | Placement Training In-plant Training/Internship Training with Project supports the various Engineering and Non-Engineering, Arts Students to develop their Skills on the IT Companies/Corporate Expectations. DURATION OF IN-PLANT TRAINING: 1 week and Above.DURATION OF INTERNSHIP: 1 Month and Above Internship-inplant training For All Departments students, Internship- inplant Training Python | Java | Full Stack Development | UI & UX | C& C++ | Php | Web Designing - HTML, CSS, Java Script, Bootstrap | MEAN Stack | MERN Stack | MEARNStack | Android | Kotlin | Flutter | Database - Oracle, Mongo DB, MySQL, MS SQL Serer | Visual Studio Code | Objective C | Swift | Go Lang | Frame work - Laravel, Django, Vue JS | Machine Learning | React JS | ...