REST API Insert Update Delete using PHP

REST API Insert Update Delete using PHP

In this Post We Will Explain About is REST API Insert Update Delete using PHP With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Create a RESTful services using Slim PHP FrameworkExample

In this post we will show you Best way to implement CRUD Operations in Laravel 5 with MYSQL, RESTFUL, hear for REST API CRUD using PHPwith Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Step 1 : .htaccess File

# Turn rewrite engine on
Options +FollowSymlinks
RewriteEngine on

# map neat URL to internal URL
RewriteRule ^products/list/$   RestController.php?uniq_page_key=list [nc,qsa]
RewriteRule ^products/list$   RestController.php?uniq_page_key=list [nc,qsa]

RewriteRule ^products/create/$   RestController.php?uniq_page_key=create [L]
RewriteRule ^products/create$   products/create/ [L,R=301]

RewriteRule ^products/delete/([0-9]+)/$   RestController.php?uniq_page_key=delete&mobile_id=$1 [L]
RewriteRule ^products/delete([0-9]+)$   products/delete/$1 [L,R=301]

RewriteRule ^products/update/([0-9]+)/$   RestController.php?uniq_page_key=update&mobile_id=$1 [L]
RewriteRule ^products/update/([0-9]+)$   products/update/$1/ [L,R=301]

Step 2 : dbcontroller.php

<?php
class DBController {
	private $db_con = "";
	private $cust_host = "localhost";
	private $user_name = "root";
	private $web_pass = "";
	private $sel_database = "live24u";

	function __construct() {
		$db_con = $this->connectDB();
		if(!empty($db_con)) {
			$this->db_con = $db_con;			
		}
	}

	function connectDB() {
		$db_con = mysqli_connect($this->cust_host,$this->user_name,$this->web_pass,$this->sel_database);
		return $db_con;
	}

	function queryExecute($my_sql_query) {
        $db_con = $this->connectDB();    
        $data_res = mysqli_query($db_con, $my_sql_query);
        if (!$data_res) {
           
            if($db_con->errno == 1062) {
                return false;
            } else {
                trigger_error (mysqli_error($db_con),E_USER_NOTICE);
				
            }
        }		
        $get_row_resdata = mysqli_affected_rows($db_con);
		return $get_row_resdata;
		
    }
	function executeSelectQuery($my_sql_query) {
		$data_res = mysqli_query($this->db_con,$my_sql_query);
		while($row=mysqli_fetch_assoc($data_res)) {
			$resultset[] = $row;
		}
		if(!empty($resultset))
			return $resultset;
	}
}
?>

Step 3 : Products.php

<?php
require_once("dbcontroller.php");
Class Products {
	private $mobiles = array();
	public function getAllMobile(){
		if(isset($_GET['client_nm'])){
			$client_nm = $_GET['client_nm'];
			$my_sql_query = 'SELECT * FROM my_products WHERE client_nm LIKE "%' .$client_nm. '%"';
		} else {
			$my_sql_query = 'SELECT * FROM my_products';
		}
		$dbcontroller = new DBController();
		$this->mobiles = $dbcontroller->executeSelectQuery($my_sql_query);
		return $this->mobiles;
	}

	public function addMobile(){
		if(isset($_POST['client_nm'])){
			$client_nm = $_POST['client_nm'];
				$data_model = '';
				$product_color = '';
			if(isset($_POST['data_model'])){
				$data_model = $_POST['data_model'];
			}
			if(isset($_POST['product_color'])){
				$product_color = $_POST['product_color'];
			}	
			$my_sql_query = "insert into my_products (client_nm,data_model,product_color) values ('" . $client_nm ."','". $data_model ."','" . $product_color ."')";
			$dbcontroller = new DBController();
			$data_res = $dbcontroller->queryExecute($my_sql_query);
			if($data_res != 0){
				$data_res = array('success'=>1);
				return $data_res;
			}
		}
	}
	
	public function deleteMobile(){
		if(isset($_GET['mobile_id'])){
			$mobile_id = $_GET['mobile_id'];
			$my_sql_query = 'DELETE FROM my_products WHERE mobile_id = '.$mobile_id;
			$dbcontroller = new DBController();
			$data_res = $dbcontroller->queryExecute($my_sql_query);
			if($data_res != 0){
				$data_res = array('success'=>1);
				return $data_res;
			}
		}
	}
	
	public function editMobile(){
		if(isset($_POST['client_nm']) && isset($_GET['mobile_id'])){
			$client_nm = $_POST['client_nm'];
			$data_model = $_POST['data_model'];
			$product_color = $_POST['product_color'];
			$my_sql_query = "UPDATE my_products SET client_nm = '".$client_nm."',data_model ='". $data_model ."',product_color = '". $product_color ."' WHERE mobile_id = ".$_GET['mobile_id'];
		}
		$dbcontroller = new DBController();
		$data_res= $dbcontroller->queryExecute($my_sql_query);
		if($data_res != 0){
			$data_res = array('success'=>1);
			return $data_res;
		}
	}
	
}
?>

Step 4 : ProductRestHandler.php

<?php
require_once("CustomRest.php");
require_once("Products.php");
		
class ProductRestHandler extends CustomRest {

	function getAllProducts() {	

		$products = new Products();
		$all_data_row = $products->getAllMobile();

		if(empty($all_data_row)) {
			$newStCode = 404;
			$all_data_row = array('success' => 0);		
		} else {
			$newStCode = 200;
		}

		$data_req_type = $_SERVER['HTTP_ACCEPT'];
		$this ->setHttpHeaders($data_req_type, $newStCode);
		
		$data_res["output"] = $all_data_row;
				
		if(strpos($data_req_type,'application/json') !== false){
			$results = $this->encodeJson($data_res);
			echo $results;
		}
	}
	
	function add() {	
		$products = new Products();
		$all_data_row = $products->addMobile();
		if(empty($all_data_row)) {
			$newStCode = 404;
			$all_data_row = array('success' => 0);		
		} else {
			$newStCode = 200;
		}
		
		$data_req_type = $_SERVER['HTTP_ACCEPT'];
		$this ->setHttpHeaders($data_req_type, $newStCode);
		$data_res = $all_data_row;
				
		if(strpos($data_req_type,'application/json') !== false){
			$results = $this->encodeJson($data_res);
			echo $results;
		}
	}

	function deleteMobileById() {	
		$products = new Products();
		$all_data_row = $products->deleteMobile();
		
		if(empty($all_data_row)) {
			$newStCode = 404;
			$all_data_row = array('success' => 0);		
		} else {
			$newStCode = 200;
		}
		
		$data_req_type = $_SERVER['HTTP_ACCEPT'];
		$this ->setHttpHeaders($data_req_type, $newStCode);
		$data_res = $all_data_row;
				
		if(strpos($data_req_type,'application/json') !== false){
			$results = $this->encodeJson($data_res);
			echo $results;
		}
	}
	
	function editMobileById() {	
		$products = new Products();
		$all_data_row = $products->editMobile();
		if(empty($all_data_row)) {
			$newStCode = 404;
			$all_data_row = array('success' => 0);		
		} else {
			$newStCode = 200;
		}
		
		$data_req_type = $_SERVER['HTTP_ACCEPT'];
		$this ->setHttpHeaders($data_req_type, $newStCode);
		$data_res = $all_data_row;
				
		if(strpos($data_req_type,'application/json') !== false){
			$results = $this->encodeJson($data_res);
			echo $results;
		}
	}
	
	public function encodeJson($responseData) {
		$jsonResponse = json_encode($responseData);
		return $jsonResponse;		
	}
}
?>

Step 5 : RestController.php

<?php
require_once("ProductRestHandler.php");
$method = $_SERVER['REQUEST_METHOD'];
$view = "";
if(isset($_GET["uniq_page_key"]))
	$uniq_page_key = $_GET["uniq_page_key"];
	switch($uniq_page_key){

		case "list":
			$myproductRestHandlerData = new ProductRestHandler();
			$data_res = $myproductRestHandlerData->getAllProducts();
			break;
	
		case "create":
			$myproductRestHandlerData = new ProductRestHandler();
			$myproductRestHandlerData->add();
		break;
		
		case "delete":
			$myproductRestHandlerData = new ProductRestHandler();
			$data_res = $myproductRestHandlerData->deleteMobileById();
		break;
		
		case "update":
			$myproductRestHandlerData = new ProductRestHandler();
			$myproductRestHandlerData->editMobileById();
		break;
}
?>

Step 6 : CustomRest.php

<?php 
class CustomRest {
	
	private $httpVersion = "HTTP/1.1";

	public function setHttpHeaders($contentType, $newStCode){
		
		$statusMessage = $this -> getHttpStatusMessage($newStCode);
		
		header($this->httpVersion. " ". $newStCode ." ". $statusMessage);		
		header("Content-Type:". $contentType);
	}
	
	public function getHttpStatusMessage($newStCode){
		$httpStatus = array(
			100 => 'infinityknow : Continue Message',  
			101 => 'infinityknow : Switching Protocols Message',  
			200 => 'infinityknow : OK Message',
			201 => 'infinityknow : Created Message',  
			202 => 'infinityknow : Accepted Message',  
			203 => 'infinityknow : Non-Authoritative Message Information',  
			204 => 'infinityknow : No Content Message',  
			205 => 'infinityknow : Reset Content Message',  
			206 => 'infinityknow : Partial Content Message',  
			300 => 'infinityknow : Multiple Choices Message',  
			301 => 'infinityknow : Moved Permanently Message',  
			302 => 'infinityknow : Found Message',  
			303 => 'infinityknow : See Other Message',  
			304 => 'infinityknow : Not Modified Message',  
			305 => 'infinityknow : Use Proxy Message',  
			306 => 'infinityknow : (Unused) Message',  
			307 => 'infinityknow : Temporary Redirect Message',  
			400 => 'infinityknow : Bad Request Message',  
			401 => 'infinityknow : Unauthorized Message',  
			402 => 'infinityknow : Payment Required Message',  
			403 => 'infinityknow : Forbidden Message',  
			404 => 'infinityknow : Not Found Message',  
			405 => 'infinityknow : Method Not Allowed Message',  
			406 => 'infinityknow : Not Acceptable Message',  
			407 => 'infinityknow : Proxy Authentication Message Required',  
			408 => 'infinityknow : Request Timeout Message',  
			409 => 'infinityknow : Conflict Message',  
			410 => 'infinityknow : Gone Message',  
			411 => 'infinityknow : Length Required',  
			412 => 'infinityknow : Precondition Message Failed',  
			413 => 'infinityknow : Request Entity more Large Message',  
			414 => 'infinityknow : Request-URI more Long Message',  
			415 => 'infinityknow : Unsupported Media Type Message',  
			416 => 'infinityknow : Requested any Range Not Satisfiable Message',  
			417 => 'infinityknow : Expectation Failed Message',  
			500 => 'infinityknow : Internal Server Error Message',  
			501 => 'infinityknow : Not Implemented Message',  
			502 => 'infinityknow : Bad Gateway Message',  
			503 => 'infinityknow : Service Unavailable Message',  
			504 => 'infinityknow : Gateway Timeout Message',  
			505 => 'infinityknow : HTTP Version Not Supported Message');
		return ($httpStatus[$newStCode]) ? $httpStatus[$newStCode] : $status[500];
	}
}
?>

Example

Read Also:  Bootstrap On-Off Toggle Switch jQuery Plugins

I hope you have Got What is PHP Restful API Framework SLIM to Create REST API And how it works.I would Like to have FeadBack From My Blog(Pakainfo.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(Pakainfo.com) Are Most Always Welcome.


Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  Vue js Axios HTTP Post Method Example Tutorial From Scratch
  2. Read Also:  defer parsing of javascript htaccess
  3. Read Also:  Laravel ajax post CSRF Protection
  4. Read Also:  how to create api in php json tutorial
  5. Read Also:  REST API CRUD Example in PHP with MySQLi
  6. Read Also:  What is function overriding in php?
  7. Read Also:  Laravel 6 Custom Middleware Tutorial With Example
  8. Read Also:  Create Canned Responses using PHP Auto-Replies
  9. Read Also:  Create RESTful API using PHP
  10. Read Also:  PHP Magento extension soap must be loaded error
CLOSEX