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
Post a Comment