CRUD Operation with AngularJS
This tutorial will teach you how to create a CRUD Application using AngularJS,PHP,MySQL and Slim framework.
You can find the source code of this article here
AngularJS is a Java Script framework for dynamic web apps.It lets you extend HTML tags.
Slim is a PHP micro framework which we are going to use for create REST service in php.
Below you can find file structure of the Application.
- js - This folder include all the JavaScript files we use here.
- api - This folder will contain Slim framework.
- pages - This folder contains all the front end pages.
well let's get started with Installing Slim framework inside api folder . Follow the link, If you have any doubts over how to installing it. It's fairly easy process and I am not going write it in detail here.
After installing Slim you'll get a folder call Slim inside you api folder.we'll leave it there for the current been.
Next create the index.html file and put below code segment inside it.
<html>
<head>
<meta charset='utf-8'>
<title>Angular Apptitle>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
head>
<body ng-app="Application">
<div class="container">
<div ng-view>div>
div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js">script>
<script type="text/javascript" src ="js/app.js">script>
body>
html>
|
Well lets go through this code. We load AngularJS to our app and remember we have to load the angular-route.js too.I will tell you why later in this tutorial. Optionally I load bootstrap style sheet to have to have some sort of user friendly front end
You can say this as a starting point of a Angular Application. ng-app directive responsible for auto-bootstrap angular application.
This directive is simply responsible for View of the Application.
Now inside JS folder create app.js file.
var app = angular.module('Application', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl: 'pages/lists.html', controller: 'CustomerListControler'}).
when('/NewCustomer', {templateUrl: 'pages/new.html', controller: 'CustomerAddControler'}).
when('/UpdateCustomer/:id', {templateUrl: 'pages/edit.html', controller: 'CustomerEditControler'}).
otherwise({redirectTo: '/'});
}]);
|
Here we have our 'Application' module.
In First line we declare our module.In this case it's Application. Second argument is a array. It consist of dependencies for the module.Here we need 'ng-Route' since it is the module that responsible for provide routing and deeplinking services and directives for angular apps.
Rest of the code is for set routs for the App.$routeProvider use for configuring routes.I recommend you to go through above link to get a better understand about $routeProvider. Actually this is where we need above discussed 'ng-Route' module to be installed as a dependency for $routeProvider.
Lets we move on to create our first Controller.
app.controller ('CustomerListControler',[
'$scope','$http',
function ($scope, $http) {
$http.get('api/Customers').success(function(data) {
$scope.customers = data;
});
}
]),
|
This is the controller for get the list of customer details.
AngularJs application are controlled by Controllers. 'CustomerListControler' is a JavaScript function and $scope is the application object. Which means it owns the application variable and objects.
$http use to communicate with web servers.
$http.get is the function use to read the server data and those data will store in property call customers.
app.controller ('CustomerAddControler',[
'$scope','$http','$location',
function ($scope, $http, $location) {
$scope.master = {};
$scope.activePath = null;
$scope.New_Customer = function(customer, AddNewForm) {
console.log(customer);
$http.post('api/New_Customer', customer).success(function(){
$scope.reset();
$scope.activePath = $location.path('/');
});
$scope.reset = function() {
$scope.customer = angular.copy($scope.master);
};
$scope.reset();
};
}
]),
|
What we have here is Controller for add a new customer.
One of new thing we come across here is $location. $location service parses the URL in the browser address bar and makes the URL available to your application.Changes to the URL in the address bar are reflected into $location service & changes to $location are reflected into the browser address bar.
Then we move onto create 'CustomerEditController', The Controller that will responsible for handle Edit and Delete.
app.controller('CustomerEditControler',[
'$scope','$http','$location','$routeParams',
function ($scope, $http, $location, $routeParams) {
var id = $routeParams.id;
$scope.activePath = null;
$http.get('api/Customers/'+id).success(function(data) {
$scope.CustomerDetail = data;
});
$scope.Update_Customer = function(customer) {
$http.put('api/Customers/'+id, customer).success(function(data) {
$scope.CustomerDetail = data;
$scope.activePath = $location.path('/');
});
};
$scope.Delete_Customer = function(customer) {
console.log(customer);
var deleteCustomer = confirm('Are you absolutely sure you want to delete?');
if (deleteCustomer) {
$http.delete('api/Customers/'+customer.id);
$scope.activePath = $location.path('/');
}
};
}
]);
|
Hm..looks like we don't have anything new to discuss here. So we'll move on to create database handling section.
Go to index.php file inside Slim folder.
In first two lines we call & create instance of Slim. Then comes the interesting part of Slim's route handling.As you can see it's really easy to understand .That is the one of main reason we use Slim framework here.If you want to know more about Slim routing follow this
require 'Slim/Slim.php';
$app = new Slim();
$app->get('/Customers', 'getCustomers');
$app->get('/Customers/:id', 'getCustomer');
$app->post('/New_Customer', 'addCustomer');
$app->put('/Customers/:id', 'updateCustomer');
$app->delete('/Customers/:id', 'deleteCustomer');
$app->run();
|
Then we'll create actual database connection & database handling.
// Get Database Connection
function DB_Connection() {
$dbhost = "127.0.0.1";
$dbuser = "root";
$dbpass = "";
$dbname = "angular_crud";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
//Get Customer Details
function getCustomers() {
$sql = "select id,Username,First_Name,Last_Name,Email,Status FROM customers";
try {
$db = DB_Connection();
$stmt = $db->query($sql);
$list = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($list);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
// Add new Customer to the Database
function addCustomer() {
$request = Slim::getInstance()->request();
$cus = json_decode($request->getBody());
$sql = "INSERT INTO customers (Username, First_Name, Last_Name, Email, Status) VALUES (:username, :firstname, :lastname, :email, :status)";
try {
$db = DB_Connection();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $cus->Username);
$stmt->bindParam("firstname", $cus->First_Name);
$stmt->bindParam("lastname", $cus->Last_Name);
$stmt->bindParam("email", $cus->Email);
$stmt->bindParam("status", $cus->Status);
$stmt->execute();
$cus->id = $db->lastInsertId();
$db = null;
echo json_encode($cus);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
// GET One Customer Details
function getCustomer($id) {
$sql = "select id,Username,First_Name,Last_Name,Email,Status FROM customers WHERE id=".$id." ORDER BY id";
try {
$db = DB_Connection();
$stmt = $db->query($sql);
$list = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($list);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
//Update Cutomer Details
function updateCustomer($id) {
$request = Slim::getInstance()->request();
$cus = json_decode($request->getBody());
$sql = "UPDATE customers SET Username=:username,First_Name=:firstname,Last_Name=:lastname, Email=:email, Status=:status WHERE id=:id";
try {
$db = DB_Connection();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $cus->Username);
$stmt->bindParam("firstname", $cus->First_Name);
$stmt->bindParam("lastname", $cus->Last_Name);
$stmt->bindParam("email", $cus->Email);
$stmt->bindParam("status", $cus->Status);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
echo json_encode($cus);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
//DELETE Customer From the Database
function deleteCustomer($id) {
$sql = "DELETE FROM customers WHERE id=".$id;
try {
$db = DB_Connection();
$stmt = $db->query($sql);
$list = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($list);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
|
Go to pages folder and create list.html,new.html and edit.html files
<h2>Edit Customerh2>
<div class="row" ng-controller='CustomerEditControler'>
<div class="col-md-6">
<form novalidate ng-repeat="customer in CustomerDetail" name="AddNewForm" id="add-new-form" method="post" action="">
<input type="hidden" ng-model="customer.id" value="{{customer.id}}" />
<div class="form-group">
<label>Usernamelabel>
<input class="form-control" type="text" ng-model="customer.Username" value="{{customer.Username}}" required />
div>
<div class="form-group">
<label>First Namelabel>
<input class="form-control" type="text" ng-model="customer.First_Name" value="{{customer.First_Name}}" required />
div>
<div class="form-group">
<label>Last Namelabel>
<input class="form-control" type="text" ng-model="customer.Last_Name" value="{{customer.Last_Name}}" required />
div>
<div class="form-group">
<label >Emaillabel>
<input class="form-control" type="text" ng-model="customer.Email" value="{{customer.Email}}" required />
div>
<div class="form-group">
<label>Statuslabel>
<input class="form-control" type="text" ng-model="customer.Status" value="{{customer.Status}}" required />
div>
<button class="btn btn-primary" ng-disabled="AddNewForm.$invalid || isUnchanged(customer)" id="add-new-btn" ng-click="Update_Customer(customer)">Update
<span class="glyphicon glyphicon-floppy-disk">span>button>
<button class="btn btn-danger" ng-click="Delete_Customer(customer)">Delete <span class="glyphicon glyphicon-trash">span>button>
<a href="#/" class="btn">Cancela>
form>
div>
div>
|
<h2>Customersh2>
<div ng-controller="CustomerListControler">
<table class="table table-condensed">
<thead>
<tr>
<th>Usernameth>
<th>First Nameth>
<th>Last Nameth>
<th>Emailth>
<th>Statusth>
<th>Optionth>
tr>
thead>
<tbody>
<tr ng-repeat="res in customers | orderBy: 'First_Name'">
<td>{{res.Username}}td>
<td>{{res.First_Name}}td>
<td>{{res.Last_Name}}td>
<td>{{res.Email}}td>
<td>{{res.Status}}td>
<td><a href="#/UpdateCustomer/{{res.id}}" class="btn btn-default btn-sm"><i class="glyphicon glyphicon-pencil">i>button>td>
tr>
tbody>
table>
<a class="btn btn-primary" href="#/NewCustomer">Add New Customera>
div>
|
<h2>New Customerh2>
<div class="row" ng-controller="CustomerAddControler">
<div class="col-md-6">
<form name="AddNewForm" id="add-new-form" method="post" action="">
<div class="form-group">
<label for="name">Usernamelabel>
<input class="form-control" type="text" ng-model="customer.Username" required />
div>
<div class="form-group">
<label for="name">First Namelabel>
<input class="form-control" type="text" ng-model="customer.First_Name" required />
div>
<div class="form-group">
<label for="name">Last Namelabel>
<input class="form-control" type="text" ng-model="customer.Last_Name" required />
div>
<div class="form-group">
<label for="email">Emaillabel>
<input class="form-control" type="text" ng-model="customer.Email" required />
div>
<div class="form-group">
<label for="country">Statuslabel>
<input class="form-control" type="text" ng-model="customer.Status" required />
div>
<button class="btn btn-primary" ng-disabled="AddNewForm.$invalid || isUnchanged(customer)" id="add-new-btn" ng-click="New_Customer(customer)">Savebutton>
<a href="#/" class="btn">Cancela>
form>
div>
div>
|
Well..It's done guys.Now we have your own little AngularJS application whichcapable of doing CRUD operation.I hope you enjoy the tutorial.
Happy coding.
You can find the source code of this article here