PHP AngularJS CRUD with Search and Pagination Example From Scratch

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hello devs,hope all are good. I like to share on this post with you. You can learn from here how to use PHP AngularJS CRUD. Now in this post i did a simple example with create, read, update, delete, search and pagination of items on table.Here i use angularJS MVC with native PHP. In this way you can easily implement in your project.

Now AngularJS is a very awesome library of JS. Because on that way we can make application without page load. That’s mean we have to just one time page load and then whole crud, search and pagination will work without any page reload. So I create this example PHP and AngularJS CRUD that way you can understand very well and also it is very simple to integrate with any project.

So, now just you have to follow few step for angularJS crud application. Also you can use REST API in AngularJS code. Now I build a AngularJS with native PHP is very easily change and you can easily understand this script. Now I would like to show you on PHP and AngularJS CRUD application layout demo.

Only need Follow 4 step:

1.Create items table, DB Config file and index.php

2.Use AngularJS Code

3.Create Template files

4.Database Logic

Step 1: Create items table, DB Config file and index.php

In the very first step we need to create database and items table. So let’s create database we did create “learn” database and “items” table inside that database. So you can create database as you want but you also have to crate “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, now let’s proceed this way, we are now 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 some ware. That’s way i tell you check it two times. It was just for your kind information.

Ok, now we also require t create index.php file in our root directory. So let’s create index.php file and also 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 class="container">
		<ng-view></ng-view>
	</div>
</body>
</html>

Step 2: Use AngularJS Code

Now in this step we will create a angularJS code. So first we have to create  a “app” folder in our root directory. Then we will write whole angular JS code in this folder that way we can easily re-use this code in our future applications.

Next create a routes.js file inside our app folder. Then we will create our all angular js route in routes.js file. So now create routes.js file and also 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 creating a controller for our angular route. So now we create another directory as controller(app/controller) in our app folder . And also create a ItemController.js in directory (app/controller/ItemController.js) for manage our route request. So, let’s put all 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 a helper file(app/helper) folder in add directory. We are now creating a helper folder because we should store all helper function. We can manage in this folder. So let’s create also myHelper.js in this directory (app/helper/myHelper.js) file in our helper folder. Now i write just one helper for modify our table but if you want 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 name “services”(app/services) in your app directory. In this folder we will store our all service file for example i did use app.factory of angularjs. That way we can easily manage it proper way.

 So let’s create myServices.js(app/services/myServices.js) file and also put bellow code in this 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 weneed to create one another folder name”packages”.  We are creating packages folder because we can store all package file store in this folder for easily re-used.

Now we need to download dirPagination.js file from here: Pagination Directive.

Read Also: Angularjs PHP MySQL Pagination Example

Step 3: Create Template files

In this step we need to create template files. When we call angular js route then it will fetch one template file for layout so we have to create this “templates” directory in your root file.

First create items.html file for items module layout so create items.html file and also put bellow code.

templates/items.html

<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h1 style="color:#3276B1"><strong>Manage Item</h1>
        </div>
        <div class="pull-right" style="padding-top:30px">
            <div class="box-tools" style="display:inline-table">
              <div class="input-group">
                  <input type="text" class="form-control input-sm ng-valid ng-dirty" placeholder="Search" ng-change="searchDB()" ng-model="searchText" name="table_search" title="" tooltip="" data-original-title="Min character length is 3">
                  <span class="input-group-addon">Search</span>
              </div>
            </div>
            <button class="btn btn-success" data-toggle="modal" data-target="#create-user">Create New</button>
        </div>
    </div>
</div>
<table class="table table-bordered pagin-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" class="btn btn-primary">Edit</button>
            <button ng-click="remove(value,$index)" class="btn btn-danger">Delete</button>
            </td>
        </tr>
    </tbody>
</table>
<dir-pagination-controls class="pull-right" on-page-change="pageChanged(newPageNumber)" template-url="templates/dirPagination.html" ></dir-pagination-controls>
<!-- Create Modal -->
<div class="modal fade" id="create-user" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="POST" name="addItem" role="form" ng-submit="saveAdd()">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="myModalLabel">Create Item</h4>
            </div>
            <div class="modal-body">
                <div class="container">
                    <div class="row">
                        <div class="col-xs-12 col-sm-6 col-md-6">
                            <strong>Title : </strong>
                            <div class="form-group">
                                <input ng-model="form.title" type="text" placeholder="Name" name="title" class="form-control" required />
                            </div>
                        </div>
                        <div class="col-xs-12 col-sm-6 col-md-6">
                            <strong>Description : </strong>
                            <div class="form-group" >
                                <textarea ng-model="form.description" class="form-control" required>
                                </textarea>
                            </div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" ng-disabled="addItem.$invalid" class="btn btn-primary">Submit</button>
                </div>
            </div>
            </form>
        </div>
    </div>
</div>
</div>
<!-- Edit Modal -->
<div class="modal fade" id="edit-data" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="POST" name="editItem" role="form" ng-submit="saveEdit()">
                <input ng-model="form.id" type="hidden" placeholder="Name" name="name" class="form-control" />
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="myModalLabel">Edit Item</h4>
            </div>
            <div class="modal-body">
                <div class="container">
                    <div class="row">
                        <div class="col-xs-12 col-sm-6 col-md-6">
                            <div class="form-group">
                               <input ng-model="form.title" type="text" placeholder="Name" name="title" class="form-control" required />
                            </div>
                        </div>
                        <div class="col-xs-12 col-sm-6 col-md-6">
                            <div class="form-group">
                               <textarea ng-model="form.description" class="form-control" required>
                                </textarea>
                            </div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" ng-disabled="editItem.$invalid" class="btn btn-primary create-crud">Submit</button>
                </div>
            </div>
            </form>
        </div>
    </div>
</div>
</div>

Last create dirPagination.html file for pagination layout and put following code in that file.

templates/dirPagination.html

<ul class="pagination pull-right" ng-if="1 < pages.length">
    <li ng-if="boundaryLinks" ng-class="{ disabled : pagination.current == 1 }">
        <a href="" ng-click="setCurrent(1)">«</a>
    </li>
    <li ng-if="directionLinks" ng-class="{ disabled : pagination.current == 1 }">
        <a href="" ng-click="setCurrent(pagination.current - 1)">‹</a>
    </li>
    <li ng-repeat="pageNumber in pages track by $index" ng-class="{ active : pagination.current == pageNumber, disabled : pageNumber == '...' }">
        <a href="" ng-click="setCurrent(pageNumber)">{{ pageNumber }}</a>
    </li>
    <li ng-if="directionLinks" ng-class="{ disabled : pagination.current == pagination.last }">
        <a href="" ng-click="setCurrent(pagination.current + 1)">›</a>
    </li>
    <li ng-if="boundaryLinks"  ng-class="{ disabled : pagination.current == pagination.last }">
        <a href="" ng-click="setCurrent(pagination.last)">»</a>
    </li>
</ul>

Step 4: Database Logic

This is our last step and you can skip this step if you have already made REST API method, if not know then you need to follow me.

First create “api” folder in our root directory. First create getData.php file and that file will return all records from items table on Database. 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 finally  ready to use try to run your projects.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →

Leave a Reply

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

three × two =