Restful API insert update delete using angularjs and php

In this Post We Will Explain About is Restful API insert update 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 insert update delete using php mysqlExample

In this post we will show you Best way to implement AngularJS CRUD Example with Material Design – Step by Step, hear for Restful insert, update, edit, delete using angularjs and phpwith Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Index.html



    <title>step by step Restful insert update and delete using angularjs and php Step By step</title>
    
    
	

<div>
<div class="container">
<br />
<h3><a>step by step Restful insert update and delete using angularjs and php Example</a></h3>
<br />
<h1>Welcome to infinityknow.com</h1>
    <div id="ng-view"></div>
   
</div>
</div>
<!-- Include External Libs by infinityknow.com -->
<a href="http://js/angular.min.js">http://js/angular.min.js</a>
<a href="http://js/angular-route.min.js">http://js/angular-route.min.js</a>
<a href="http://app/app.js">http://app/app.js</a>    

	ul>li, a{cursor: pointer;}
     


app.js

var liveapp = angular.module('liveApp', ['ngRoute']);
liveapp.factory("services", ['$http', function($http) {
  var liveservice = 'services/'
    var myobj = {};
    myobj.getUsers = function(){
	//simple retur using function
        return $http.get(liveservice + 'users');
    }
    myobj.getUser = function(userID){
	//simple retur using function
        return $http.get(liveservice + 'user?id=' + userID);
    }

    myobj.insertUser = function (user) {
    return $http.post(liveservice + 'insertUser', user).then(function (results) {
	//simple retur using function
        return results;
    });
	};

	myobj.updateUser = function (id,user) {
	    return $http.post(liveservice + 'updateUser', {id:id, user:user}).then(function (app_status) {
		//simple retur using function
	        return app_status.response_data;
	    });
	};

	myobj.deleteUser = function (id) {
	    return $http.delete(liveservice + 'deleteUser?id=' + id).then(function (app_status) {
		//simple retur using function
	        return app_status.response_data;
	    });
	};

    return myobj;   
}]);

liveapp.controller('liveCtrl', function ($scope, services) {
    services.getUsers().then(function(response_data){
        $scope.users = response_data.response_data;
    });
});

liveapp.controller('liveresponse_dataeditctrl', function ($scope, $resultootScope, $location, $resultouteParams, services, user) {
    var userID = ($resultouteParams.userID) ? parseInt($resultouteParams.userID) : 0;
    $resultootScope.title = (userID > 0) ? 'Edit user' : 'Add user';
    $scope.buttonText = (userID > 0) ? 'Update user' : 'Add New user';
      var main_org = user.response_data;
      main_org._id = userID;
      $scope.user = angular.copy(main_org);
      $scope.user._id = userID;

      $scope.isClean = function() {
	  //simple retur using function
        return angular.equals(main_org, $scope.user);
      }

      $scope.deleteUser = function(user) {
        $location.path('/');
        if(confirm("Are you sure to delete user number: "+$scope.user._id)==true)
        services.deleteUser(user.userNumber);
      };

      $scope.saveCustomer = function(user) {
        $location.path('/');
        if (userID <= 0) {
            services.insertUser(user);
        }
        else {
            services.updateUser(userID, user);
        }
    };
});

liveapp.config(['$resultouteProvider',
  function($resultouteProvider) {
    $resultouteProvider.
      when('/', {
        title: 'Users',
        templateUrl: 'partials/users.html',
        controller: 'liveCtrl'
      })
      .when('/edit-user/:userID', {
        title: 'Edit Users',
        templateUrl: 'partials/edit-user.html',
        controller: 'liveresponse_dataeditctrl',
        resolve: {
          user: function(services, $resultoute){
            var userID = $resultoute.current.params.userID;
			//simple retur using function
            return services.getUser(userID);
          }
        }
      })
      .otherwise({
        redirectTo: '/'
      });
}]);
liveapp.run(['$location', '$resultootScope', function($location, $resultootScope) {
    $resultootScope.$on('$resultouteChangeSuccess', function (event, current, previous) {
        $resultootScope.title = current.$$resultoute.title;
    });
}]);

api.php

dbConnect();					
		}
		
		private function dbConnect(){
			//all pages to connect db
			$this->mysqli = new mysqli(self::DB_SERVER, self::DB_USER, self::DB_PASSWORD, self::DB);
		}
		
		public function liveprocessAPI(){
			$func = strtolower(trim(str_replace("/","",$_REQUEST['x'])));
			if((int)method_exists($this,$func) > 0)
				$this->$func();
			else
				$this->response('',404); // If the method not exist with in this class "Page not found".
		}
				
		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)){
					$sql_query="SELECT uid, name, email FROM users WHERE email = '$email' AND password = '".md5($password)."' LIMIT 1";
					$result = $this->mysqli->sql_query($sql_query) or die($this->mysqli->error.__LINE__);

					if($result->num_rows > 0) {
						$resultesult = $result->fetch_assoc();	
						
						$this->response($this->json($resultesult), 200);
					}
					$this->response('', 204);	// If no records "No Content" app_status
				}
			}
			
			$error = array('app_status' => "Failed", "comments" => "Invalid your Email address as well as Password");
			$this->response($this->json($error), 400);
		}
		
		private function users(){	
			if($this->get_request_method() != "GET"){
				$this->response('',406);
			}
			$sql_query="SELECT distinct c.userNumber, c.userName, c.email, c.address, c.user_city, c.user_state, c.postalCode, c.user_country FROM livecode_users c order by c.userNumber desc";
			$result = $this->mysqli->sql_query($sql_query) or die($this->mysqli->error.__LINE__);

			if($result->num_rows > 0){
				$resultesult = array();
				while($resultow = $result->fetch_assoc()){
					$resultesult[] = $resultow;
				}
				$this->response($this->json($resultesult), 200);
			}
			$this->response('',204);
		}
		private function user(){	
			if($this->get_request_method() != "GET"){
				$this->response('',406);
			}
			$id = (int)$this->_request['id'];
			if($id > 0){	
				$sql_query="SELECT distinct c.userNumber, c.userName, c.email, c.address, c.user_city, c.user_state, c.postalCode, c.user_country FROM livecode_users c where c.userNumber=$id";
				$result = $this->mysqli->sql_query($sql_query) or die($this->mysqli->error.__LINE__);
				if($result->num_rows > 0) {
					$resultesult = $result->fetch_assoc();	
					$this->response($this->json($resultesult), 200); 
				}
			}
			$this->response('',204);
		}
		
		private function insertUser(){
			if($this->get_request_method() != "POST"){
				$this->response('',406);
			}

			$user = json_decode(file_get_contents("php://input"),true);
			$name_colm = array('userName', 'email', 'user_city', 'address', 'user_country');
			$keys = array_keys($user);
			$data_colm = '';
			$values = '';
			foreach($name_colm as $publ_key){ 
			   if(!in_array($publ_key, $keys)) {
			   		$$publ_key = '';
				}else{
					$$publ_key = $user[$publ_key];
				}
				$data_colm = $data_colm.$publ_key.',';
				$values = $values."'".$$publ_key."',";
			}
			$sql_query = "INSERT INTO livecode_users(".trim($data_colm,',').") VALUES(".trim($values,',').")";
			if(!empty($user)){
				$result = $this->mysqli->sql_query($sql_query) or die($this->mysqli->error.__LINE__);
				$success = array('app_status' => "Success", "comments" => "user Created Successfully.", "response_data" => $user);
				$this->response($this->json($success),200);
			}else
				$this->response('',204);	//"No Content" app_status
		}
		private function updateUser(){
			if($this->get_request_method() != "POST"){
				$this->response('',406);
			}
			$user = json_decode(file_get_contents("php://input"),true);
			$id = (int)$user['id'];
			$name_colm = array('userName', 'email', 'user_city', 'address', 'user_country');
			$keys = array_keys($user['user']);
			$data_colm = '';
			$values = '';
			foreach($name_colm as $publ_key){ 
			   if(!in_array($publ_key, $keys)) {
			   		$$publ_key = '';
				}else{
					$$publ_key = $user['user'][$publ_key];
				}
				$data_colm = $data_colm.$publ_key."='".$$publ_key."',";
			}
			$sql_query = "UPDATE livecode_users SET ".trim($data_colm,',')." WHERE userNumber=$id";
			if(!empty($user)){
				$result = $this->mysqli->sql_query($sql_query) or die($this->mysqli->error.__LINE__);
				$success = array('app_status' => "Success", "comments" => "user ".$id." Updated data record Successfully.", "response_data" => $user);
				$this->response($this->json($success),200);
			}else
				$this->response('',204);
		}
		
		private function deleteUser(){
			if($this->get_request_method() != "DELETE"){
				$this->response('',406);
			}
			$id = (int)$this->_request['id'];
			//simple retur using function
			if($id > 0){				
				$sql_query="DELETE FROM livecode_users WHERE userNumber = $id";
				$result = $this->mysqli->sql_query($sql_query) or die($this->mysqli->error.__LINE__);
				$success = array('app_status' => "Success", "comments" => "Successfully your response_data deleted one record.");
				$this->response($this->json($success),200);
			}else
				$this->response('',204);
		}
		
		private function json($response_data){
			if(is_array($response_data)){
			//simple retur using function
				return json_encode($response_data);
			}
		}
	}
	$api = new API;
	$api->liveprocessAPI();
?>

Rest.inc.php

inputs();
		}
		
		public function get_referer(){
		//simple retur using function
			return $_SERVER['HTTP_REFERER'];
		}
		
		public function response($response_data,$app_status){
			$this->_code = ($app_status)?$app_status:200;
			$this->response_data_set_head();
			echo $response_data;
			exit;
		}
		private function get_all_status_msg(){
			// All the Web app code error / success / info
			$app_status = array(
						200 => 'OK',
						201 => 'Created',  
						204 => 'No Content',  
						404 => 'Not Found',  
						406 => 'Not Acceptable');
						//simple retur using function
			return ($app_status[$this->_code])?$app_status[$this->_code]:$app_status[500];
		}
		
		public function get_request_method(){
		//simple retur using function
			return $_SERVER['REQUEST_METHOD'];
		}
		
		private function inputs(){
			switch($this->get_request_method()){
				case "POST":
					$this->_request = $this->dliveInputs($_POST);
					break;
				case "GET":
				case "DELETE":
					$this->_request = $this->dliveInputs($_GET);
					break;
				case "PUT":
					parse_str(file_get_contents("php://input"),$this->_request);
					$this->_request = $this->dliveInputs($this->_request);
					break;
				default:
					$this->response('',406);
					break;
			}
		}		
		
		private function dliveInputs($response_data){
			$my_array = array();
			if(is_array($response_data)){
				foreach($response_data as $k => $v){
					$my_array[$k] = $this->dliveInputs($v);
				}
			}else{
				if(get_magic_quotes_gpc()){
					$response_data = trim(stripslashes($response_data));
				}
				$response_data = strip_tags($response_data);
				$my_array = trim($response_data);
			}
			//simple retur using function
			return $my_array;
		}		
		
		private function response_data_set_head(){
			//set header response_data
			header("HTTP/1.1 ".$this->_code." ".$this->get_all_status_msg());
			header("Content-Type:".$this->_content_type);
		}
	}	
?>

Example

READ :  Add Remove and Update specific data In JSON using AngularJS

I hope you have Got What is Restful insert, update, edit, delete using angularjs and 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.