PHP AngularJS CRUD with Search and Pagination Example From Scratch
In this post we will give you information about PHP AngularJS CRUD with Search and Pagination Example From Scratch. Hear we will give you detail about PHP AngularJS CRUD with Search and Pagination Example From ScratchAnd how to use it also give you demo for it if it is necessary.
I would like to share this post with you. you can learn how to use AngularJS in native php. In this post you i did example with create, read, update, delete, search and pagination of items table. I use angularJS MVC with native PHP this way you can easily implement in your project. AngularJS is a awesome library of JS, Because that way you can make application without page load. I mean you have to just one time page load and then whole crud, search and pagination will work without page reload. I create this example that way you can undestand very well and it is very simple to integrate with your project.
So, you have to just follow few step for angularJS crud application. you can also REST API in AngularJS code, I build AngularJS with native PHP is very easily change and you can understandable script. I would like to show you preview of our PHP and AngularJS CRUD application layout demo.
Follow Only 4 step:
1.Create items table, DB Config file and index.php
2.Use AngularJS Code
3.Create Template files
4.Database Logic
Preview:
Step 1: Create items table, DB Config file and index.php
In first step we should create database and items table. so let’s create database i did create “learn” database and “items” table inside that database. so you can create database as you want but you have to craete “items” table if you are doing from scratch. so create “items” table using following mysql query:
Items Table Query
CREATE TABLE IF NOT EXISTS 'items' (
'id' int(10) unsigned NOT NULL AUTO_INCREMENT,
'title' varchar(255) COLLATE utf8_unicode_ci NOT NULL,
'description' text COLLATE utf8_unicode_ci NOT NULL,
'created_at' timestamp NULL DEFAULT NULL,
'updated_at' timestamp NULL DEFAULT NULL,
PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=63 ;
Ok, let’s proceed this way, we are doing from scratch so we require to create database configration file that way we can use that file in many other file. so let’s craete db_config.php file in your root directory and put bellow code:
db_config.php
define (DB_USER, "root");
define (DB_PASSWORD, "");
define (DB_DATABASE, "learn");
define (DB_HOST, "localhost");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
In Above file please make sure to check your batabase configration because could problem you find someware. that’s way i tell you check it two times. It was just for your kind information.
Ok, now we also require to create index.php file in our root directory. so let’s create index.php file and put bellow content in that file.
index.php
<html lang="en">
<head>
<title>PHP AngularJS CRUD</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
<!-- Angular JS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-route.min.js"></script>
<!-- MY App -->
<script src="app/packages/dirPagination.js"></script>
<script src="app/routes.js"></script>
<script src="app/services/myServices.js"></script>
<script src="app/helper/myHelper.js"></script>
<!-- App Controller -->
<script src="app/controllers/ItemController.js"></script>
</head>
<body ng-app="main-App">
<div >
<ng-view></ng-view>
</div>
</body>
</html>
Step 2: Use AngularJS Code
we will create angularJS code in this step, so first we have to create “app” folder in your root directory. we will do whole angular JS code in this folder that way we can eaily re-use this code.
Next create routes.js file inside app folder. we will create all angular js route in routes.js file. so create routes.js file and put bellow code in routes.js file.
app/routes.js
var app = angular.module('main-App',['ngRoute','angularUtils.directives.dirPagination']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/items.html',
controller: 'ItemController'
});
}]);
now we also require to create controller for angular route. so create another directory as controller(app/controller) in app folder and also create ItemController.js(app/controller/ItemController.js) for manage route request. So, let’s put bellow code in that file.
app/controller/ItemController.js
var URL = "http://testcode.hd/angularjsCrud";
app.controller('ItemController', function(dataFactory,$scope,$http){
$scope.data = [];
$scope.libraryTemp = {};
$scope.totalItemsTemp = {};
$scope.totalItems = 0;
$scope.pageChanged = function(newPage) {
getResultsPage(newPage);
};
getResultsPage(1);
function getResultsPage(pageNumber) {
if(! $.isEmptyObject($scope.libraryTemp)){
dataFactory.httpRequest(URL + '/api/getData.php?search='+$scope.searchText+'&page='+pageNumber).then(function(data) {
$scope.data = data.data;
$scope.totalItems = data.total;
});
}else{
dataFactory.httpRequest(URL + '/api/getData.php?page='+pageNumber).then(function(data) {
$scope.data = data.data;
$scope.totalItems = data.total;
});
}
}
$scope.searchDB = function(){
if($scope.searchText.length >= 3){
if($.isEmptyObject($scope.libraryTemp)){
$scope.libraryTemp = $scope.data;
$scope.totalItemsTemp = $scope.totalItems;
$scope.data = {};
}
getResultsPage(1);
}else{
if(! $.isEmptyObject($scope.libraryTemp)){
$scope.data = $scope.libraryTemp ;
$scope.totalItems = $scope.totalItemsTemp;
$scope.libraryTemp = {};
}
}
}
$scope.saveAdd = function(){
dataFactory.httpRequest(URL + '/api/add.php','POST',{},$scope.form).then(function(data) {
$scope.data.push(data);
$(".modal").modal("hide");
});
}
$scope.edit = function(id){
dataFactory.httpRequest(URL + '/api/edit.php?id='+id).then(function(data) {
console.log(data);
$scope.form = data;
});
}
$scope.saveEdit = function(){
dataFactory.httpRequest(URL + '/api/update.php?id='+$scope.form.id,'POST',{},$scope.form).then(function(data) {
$(".modal").modal("hide");
$scope.data = apiModifyTable($scope.data,data.id,data);
});
}
$scope.remove = function(item,index){
var result = confirm("Are you sure delete this item?");
if (result) {
dataFactory.httpRequest(URL + '/api/delete.php?id='+item.id,'DELETE').then(function(data) {
$scope.data.splice(index,1);
});
}
}
});
next we need to create helper(app/helper) folder in add directory. we are creating helper folder because we store all helper function we can manage in this folder. so let’s create also myHelper.js(app/helper/myHelper.js) file in helper folder. now i did just one helper for modify table but you can add more helper function for your angulerJS application.
app/helper/myHelper.js
function apiModifyTable(originalData,id,response){
angular.forEach(originalData, function (item,key) {
if(item.id == id){
originalData[key] = response;
}
});
return originalData;
}
Now create another folder “services”(app/services) in your app directory. in this folder we will store our service file for example i did use app.factory of angularjs. that way we can manage it proper way. so let’s create myServices.js(app/services/myServices.js) file and put bellow code in that file.
app/services/myServices.js
app.factory('dataFactory', function($http) {
var myService = {
httpRequest: function(url,method,params,dataPost,upload) {
var passParameters = {};
passParameters.url = url;
if (typeof method == 'undefined'){
passParameters.method = 'GET';
}else{
passParameters.method = method;
}
if (typeof params != 'undefined'){
passParameters.params = params;
}
if (typeof dataPost != 'undefined'){
passParameters.data = dataPost;
}
if (typeof upload != 'undefined'){
passParameters.upload = upload;
}
var promise = $http(passParameters).then(function (response) {
if(typeof response.data == 'string' && response.data != 1){
if(response.data.substr('loginMark')){
location.reload();
return;
}
$.gritter.add({
title: 'Application',
text: response.data
});
return false;
}
if(response.data.jsMessage){
$.gritter.add({
title: response.data.jsTitle,
text: response.data.jsMessage
});
}
return response.data;
},function(){
$.gritter.add({
title: 'Application',
text: 'An error occured while processing your request.'
});
});
return promise;
}
};
return myService;
});
Ok, now create one another folder “packages”, we are creating packages folder because we can store all package file store in this folder. now i use package for pagination, so create file dirPagination.js(app/packages/dirPagination.js) and put code of following link:
Step 3: Create Template files
In this step we will create template files. when we call angular js route then it will fetch one template file for layout so we have to create “templates” directory in your root file.
First craete itesms.html file for items module layout so carete items.html file and put bellow code.
templates/items.html
<div >
<div >
<div >
<h1 style="color:#3276B1"><strong>Manage Item</h1>
</div>
<div style="padding-top:30px">
<div style="display:inline-table">
<div >
<input type="text" placeholder="Search" ng-change="searchDB()" ng-model="searchText" name="table_search" title="" tooltip="" data-original-title="Min character length is 3">
<span >Search</span>
</div>
</div>
<button data-toggle="modal" data-target="#create-user">Create New</button>
</div>
</div>
</div>
<table >
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Description</th>
<th width="220px">Action</th>
</tr>
</thead>
<tbody>
<tr dir-paginate="value in data | itemsPerPage:5" total-items="totalItems">
<td>{{ $index + 1 }}</td>
<td>{{ value.title }}</td>
<td>{{ value.description }}</td>
<td>
<button data-toggle="modal" ng-click="edit(value.id)" data-target="#edit-data" >Edit</button>
<button ng-click="remove(value,$index)" >Delete</button>
</td>
</tr>
</tbody>
</table>
<dir-pagination-controls on-page-change="pageChanged(newPageNumber)" template-url="templates/dirPagination.html" ></dir-pagination-controls>
<!-- Create Modal -->
<div id="create-user" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div role="document">
<div >
<form method="POST" name="addItem" role="form" ng-submit="saveAdd()">
<div >
<button type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 id="myModalLabel">Create Item</h4>
</div>
<div >
<div >
<div >
<div >
<strong>Title : </strong>
<div >
<input ng-model="form.title" type="text" placeholder="Name" name="title" required />
</div>
</div>
<div >
<strong>Description : </strong>
<div >
<textarea ng-model="form.description" required>
</textarea>
</div>
</div>
</div>
<button type="button" data-dismiss="modal">Close</button>
<button type="submit" ng-disabled="addItem.$invalid" >Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Edit Modal -->
<div id="edit-data" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div role="document">
<div >
<form method="POST" name="editItem" role="form" ng-submit="saveEdit()">
<input ng-model="form.id" type="hidden" placeholder="Name" name="name" />
<div >
<button type="button" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 id="myModalLabel">Edit Item</h4>
</div>
<div >
<div >
<div >
<div >
<div >
<input ng-model="form.title" type="text" placeholder="Name" name="title" required />
</div>
</div>
<div >
<div >
<textarea ng-model="form.description" required>
</textarea>
</div>
</div>
</div>
<button type="button" data-dismiss="modal">Close</button>
<button type="submit" ng-disabled="editItem.$invalid" >Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Last craete dirPagination.html file for pagination layout and put following code in that file.
templates/dirPagination.html
<ul ng-if="1 < pages.length">
<li ng-if="boundaryLinks" ng->
<a href="" ng-click="setCurrent(1)">«</a>
</li>
<li ng-if="directionLinks" ng->
<a href="" ng-click="setCurrent(pagination.current - 1)">‹</a>
</li>
<li ng-repeat="pageNumber in pages track by $index" ng->
<a href="" ng-click="setCurrent(pageNumber)">{{ pageNumber }}</a>
</li>
<li ng-if="directionLinks" ng->
<a href="" ng-click="setCurrent(pagination.current + 1)">›</a>
</li>
<li ng-if="boundaryLinks" ng->
<a href="" ng-click="setCurrent(pagination.last)">»</a>
</li>
</ul>
Step 4: Database Logic
this is a last step and you can skip this step if you have already made REST API method, if not then follow me. first create “api” folder in your root directory. first craete getData.php file that file will return all records from items table. we will also create new 4 files for add,edit,update and delete. so follow that file.
api/getData.php
require '../db_config.php';
$num_rec_per_page = 5;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
if (!empty($_GET["search"])){
$sqlTotal = "SELECT * FROM items
WHERE (title LIKE '%".$_GET["search"]."%'
OR description LIKE '%".$_GET["search"]."%')";
$sql = "SELECT * FROM items
WHERE (title LIKE '%".$_GET["search"]."%'
OR description LIKE '%".$_GET["search"]."%')
LIMIT $start_from, $num_rec_per_page";
}else{
$sqlTotal = "SELECT * FROM items";
$sql = "SELECT * FROM items LIMIT $start_from, $num_rec_per_page";
}
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()){
$json[] = $row;
}
$data['data'] = $json;
$result = mysqli_query($mysqli,$sqlTotal);
$data['total'] = mysqli_num_rows($result);
echo json_encode($data);
api/add.php
require '../db_config.php';
$post = file_get_contents('php://input');
$post = json_decode($post);
$sql = "INSERT INTO items (title,description)
VALUES ('".$post->title."','".$post->description."')";
$result = $mysqli->query($sql);
$sql = "SELECT * FROM items Order by id desc LIMIT 1";
$result = $mysqli->query($sql);
$data = $result->fetch_assoc();
echo json_encode($data);
api/edit.php
require '../db_config.php';
$id = $_GET["id"];
$sql = "SELECT * FROM items WHERE id = '".$id."'";
$result = $mysqli->query($sql);
$data = $result->fetch_assoc();
echo json_encode($data);
api/update.php
require '../db_config.php';
$id = $_GET["id"];
$post = file_get_contents('php://input');
$post = json_decode($post);
$sql = "UPDATE items SET title = '".$post->title."'
,description = '".$post->description."'
WHERE id = '".$id."'";
$result = $mysqli->query($sql);
$sql = "SELECT * FROM items WHERE id = '".$id."'";
$result = $mysqli->query($sql);
$data = $result->fetch_assoc();
echo json_encode($data);
api/delete.php
require '../db_config.php';
$id = $_GET["id"];
$sql = "DELETE FROM items WHERE id = '".$id."'";
$result = $mysqli->query($sql);
echo json_encode([$id]);
Now we are ready to use try to run your projects.
IF you want to download this from git then you can download from here : GitHub
Hope this code and post will helped you for implement PHP AngularJS CRUD with Search and Pagination Example From Scratch. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs