Posted inProgramming / Mysql / Mysqli / php

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

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

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

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

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

 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

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.

I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

Leave a Reply

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

We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype