Restful insert update edit delete using Angularjs and PHP

In this Post We Will Explain About is Restful insert update edit delete using Angularjs and PHP With Example and Demo.

Welcome on infinityknow.com – Examples ,The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Angularjs Select Insert Update Delete In Php MySQL

In this post we will show you Best way to implement AngularJS – Insert Update Delete using PHP and MySQL, hear for How to AngularJS update using php MYSQL with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Index.html

<!DOCTYPE html>
<html ng-app lang =en>
<head>
    <meta charset="utf-8">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
    ul>li, a{cursor: pointer;}
    </style>
    <title>Step By Step Restful application using Angularjs and PHP</title>
</head>
<body>
<div>
<div class="container">
<br/>
<h1><h4><a>Restful Easy way to Application Using Angularjs and PHP with Mysql</a></h4></h1>
<br/>
    <div ng-view="" id="ng-view"></div>
   
</div>
</div>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="app/app.js"></script>         
</body>
</html>

app.js

var app = angular.module('liveApp', ['ngRoute']);
app.factory("services", ['$http', function($http) {
  var liveServiceBase = 'services/'
    var obj = {};
    obj.allgetcustlist = function(){
        return $http.get(liveServiceBase + 'customers');
    }
    obj.getStudents = function(itemID){
        return $http.get(liveServiceBase + 'items?id=' + itemID);
    }
 
    obj.addStudents = function (items) {
    return $http.post(liveServiceBase + 'addStudents', items).then(function (results) {
        return results;
    });
	};
 
	obj.allCustUpdate = function (id,items) {
	    return $http.post(liveServiceBase + 'allCustUpdate', {id:id, items:items}).then(function (status) {
	        return status.data;
	    });
	};
 
	obj.RemoveProduct = function (id) {
	    return $http.delete(liveServiceBase + 'RemoveProduct?id=' + id).then(function (status) {
	        return status.data;
	    });
	};
 
    return obj;   
}]);
 
app.controller('listCtrl', function ($scope, services) {
    services.allgetcustlist().then(function(data){
        $scope.customers = data.data;
    });
});
 
app.controller('editCtrl', function ($scope, $rootScope, $location, $routeParams, services, items) {
    var itemID = ($routeParams.itemID) ? parseInt($routeParams.itemID) : 0;
    $rootScope.title = (itemID > 0) ? 'Edit products' : 'Add products';
    $scope.buttonText = (itemID > 0) ? 'Update products' : 'Add New products';
      var original = items.data;
      original._id = itemID;
      $scope.items = angular.copy(original);
      $scope.items._id = itemID;
 
      $scope.isClean = function() {
        return angular.equals(original, $scope.items);
      }
 
      $scope.RemoveProduct = function(items) {
        $location.path('/');
        if(confirm("Are you sure to delete items number: "+$scope.items._id)==true)
        services.RemoveProduct(items.itemnumber);
      };
 
      $scope.saveCustomer = function(items) {
        $location.path('/');
        if (itemID <= 0) {
            services.addStudents(items);
        }
        else {
            services.allCustUpdate(itemID, items);
        }
    };
});
 
app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        title: 'Customers',
        templateUrl: 'partials/customers.html',
        controller: 'listCtrl'
      })
      .when('/edit-items/:itemID', {
        title: 'Edit Customers',
        templateUrl: 'partials/edit-items.html',
        controller: 'editCtrl',
        resolve: {
          items: function(services, $route){
            var itemID = $route.current.params.itemID;
            return services.getStudents(itemID);
          }
        }
      })
      .otherwise({
        redirectTo: '/'
      });
}]);
app.run(['$location', '$rootScope', function($location, $rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        $rootScope.title = current.$$route.title;
    });
}]);

api.php

<?php
 	require_once("Rest.inc.php");
	
	class API extends REST {
	
		public $data = "";
		
		const DB_SERVER = "localhost";
		const DB_USER = "live24u";
		const DB_PASSWORD = "[email protected]@#256sFERD";
		const DB = "Products_mst";
 
		private $db = NULL;
		private $mysqli = NULL;
		public function __construct(){
			parent::__construct();				
			$this->dbConnect();					
		}
		
		private function dbConnect(){
			$this->mysqli = new mysqli(self::DB_SERVER, self::DB_USER, self::DB_PASSWORD, self::DB);
		}
		
		public function processApi(){
			$func = strtolower(trim(str_replace("/","",$_REQUEST['x'])));
			if((int)method_exists($this,$func) > 0)
				$this->$func();
			else
				$this->response('',404);
		}
				
		private function login(){
			if($this->get_request_method() != "POST"){
				$this->response('',406);
			}
			$email = $this->_request['email'];		
			$password = $this->_request['pwd'];
			if(!empty($email) and !empty($password)){
				if(filter_var($email, FILTER_VALIDATE_EMAIL)){
					$query="SELECT uid, name, email FROM users WHERE email = '$email' AND password = '".md5($password)."' LIMIT 1";
					$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
 
					if($r->num_rows > 0) {
						$result = $r->fetch_assoc();	
						
						$this->response($this->json($result), 200);
					}
					$this->response('', 204);	
				}
			}
			
			$error = array('status' => "Failed", "msg" => "Invalid Email recaddress or Password");
			$this->response($this->json($error), 400);
		}
		
		private function customers(){	
			if($this->get_request_method() != "GET"){
				$this->response('',406);
			}
			$query="SELECT distinct c.itemnumber, c.studentName, c.email, c.recaddress, c.city, c.state, c.postalCode, c.studCountry FROM livestude_items c order by c.itemnumber desc";
			$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
 
			if($r->num_rows > 0){
				$result = array();
				while($row = $r->fetch_assoc()){
					$result[] = $row;
				}
				$this->response($this->json($result), 200); 
			}
			$this->response('',204);	
		}
		private function items(){	
			if($this->get_request_method() != "GET"){
				$this->response('',406);
			}
			$id = (int)$this->_request['id'];
			if($id > 0){	
				$query="SELECT distinct c.itemnumber, c.studentName, c.email, c.recaddress, c.city, c.state, c.postalCode, c.studCountry FROM livestude_items c where c.itemnumber=$id";
				$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
				if($r->num_rows > 0) {
					$result = $r->fetch_assoc();	
					$this->response($this->json($result), 200); // send user details
				}
			}
			$this->response('',204);	// If no records "No Content" status
		}
		
		private function addStudents(){
			if($this->get_request_method() != "POST"){
				$this->response('',406);
			}
 
			$items = json_decode(file_get_contents("php://input"),true);
			$column_names = array('studentName', 'email', 'city', 'recaddress', 'studCountry');
			$keys = array_keys($items);
			$liveColms = '';
			$values = '';
			foreach($column_names as $uniqdb_key){ 
			   if(!in_array($uniqdb_key, $keys)) {
			   		$$uniqdb_key = '';
				}else{
					$$uniqdb_key = $items[$uniqdb_key];
				}
				$liveColms = $liveColms.$uniqdb_key.',';
				$values = $values."'".$$uniqdb_key."',";
			}
			$query = "INSERT INTO livestude_items(".trim($liveColms,',').") VALUES(".trim($values,',').")";
			if(!empty($items)){
				$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
				$success = array('status' => "Success", "msg" => "products Created Successfully.", "data" => $items);
				$this->response($this->json($success),200);
			}else
				$this->response('',204);	
		}
		private function allCustUpdate(){
			if($this->get_request_method() != "POST"){
				$this->response('',406);
			}
			$items = json_decode(file_get_contents("php://input"),true);
			$id = (int)$items['id'];
			$column_names = array('studentName', 'email', 'city', 'recaddress', 'studCountry');
			$keys = array_keys($items['items']);
			$liveColms = '';
			$values = '';
			foreach($column_names as $uniqdb_key){ // Check the items received. If key does not exist, insert blank into the array.
			   if(!in_array($uniqdb_key, $keys)) {
			   		$$uniqdb_key = '';
				}else{
					$$uniqdb_key = $items['items'][$uniqdb_key];
				}
				$liveColms = $liveColms.$uniqdb_key."='".$$uniqdb_key."',";
			}
			$query = "UPDATE livestude_items SET ".trim($liveColms,',')." WHERE itemnumber=$id";
			if(!empty($items)){
				$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
				$success = array('status' => "Success", "msg" => "products ".$id." Updated Successfully.", "data" => $items);
				$this->response($this->json($success),200);
			}else
				$this->response('',204);	
		}
		
		private function RemoveProduct(){
			if($this->get_request_method() != "DELETE"){
				$this->response('',406);
			}
			$id = (int)$this->_request['id'];
			if($id > 0){				
				$query="DELETE FROM livestude_items WHERE itemnumber = $id";
				$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
				$success = array('status' => "Success", "msg" => "Successfully deleted one record.");
				$this->response($this->json($success),200);
			}else
				$this->response('',204);
		}
		
		private function json($data){
			if(is_array($data)){
				return json_encode($data);
			}
		}
	}
	
	liveApi = new API;
	liveApi->processApi();
?>

Rest.inc.php

<?php
	class REST {
		
		public $_allow = array();
		public $_content_type = "application/json";
		public $_request = array();
		
		private $_method = "";		
		private $_code = 200;
		
		public function __construct(){
			$this->inputs();
		}
		
		public function get_referer(){
			return $_SERVER['HTTP_REFERER'];
		}
		
		public function response($data,$status){
			$this->_code = ($status)?$status:200;
			$this->set_headers();
			echo $data;
			exit;
		}
		private function get_status_message(){
			$status = array(
						200 => 'OK',
						201 => 'Created',  
						204 => 'No Content',  
						404 => 'Not Found',  
						406 => 'Not Acceptable');
			return ($status[$this->_code])?$status[$this->_code]:$status[500];
		}
		
		public function get_request_method(){
			return $_SERVER['REQUEST_METHOD'];
		}
		
		private function inputs(){
			switch($this->get_request_method()){
				case "POST":
					$this->_request = $this->mymethodInputs($_POST);
					break;
				case "GET":
				case "DELETE":
					$this->_request = $this->mymethodInputs($_GET);
					break;
				case "PUT":
					parse_str(file_get_contents("php://input"),$this->_request);
					$this->_request = $this->mymethodInputs($this->_request);
					break;
				default:
					$this->response('',406);
					break;
			}
		}		
		
		private function mymethodInputs($data){
			$live_inputs = array();
			if(is_array($data)){
				foreach($data as $k => $v){
					$live_inputs[$k] = $this->mymethodInputs($v);
				}
			}else{
				if(get_magic_quotes_gpc()){
					$data = trim(stripslashes($data));
				}
				$data = strip_tags($data);
				$live_inputs = trim($data);
			}
			return $live_inputs;
		}		
		
		private function set_headers(){
			header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
			header("Content-Type:".$this->_content_type);
		}
	}	
?>

Example

READ :  Angular dependable Country State City Cascading DropDownList

I hope you have Got Insert, Update, Delete Data in MySQL using AngularJS with PHP And how it works.I would Like to have FeadBack From My Blog(infinityknow.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(infinityknow.com) Are Most Always Welcome.