How to create REST API using PHP and MySQL.

This tutorial we are implement basic REST API using PHP and MySQL. Mostly use for Mobile Apps Developments Request and server give Response back to user. Let’s start with basic introduction of REST API.

What is REST API.

REST stands for Representational State Transfer. it use for exchanging server data from client to server. REST is work on HTTP protocol principal, it can be GET, POST, PUT and DELETE.
It can be easily integrated with other platforms hence, it programme independence. you can use it any programming language.

API stands for Application programming interface. It allow to communicate web and mobile and We are implement CRUD(Create, Read, Update, Delete) an example.

Create REST API DB and add dummy data.

CREATE DATABASE programmerdesk;

CREATE TABLE `product_rest_api` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_name` varchar(255) NOT NULL,
  `product_desc` varchar(255) NOT NULL,
  `datetime` datetime NOT NULL,
  `price` float(11,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Create config.php

Create common database connection file which use in every file.

<?php
class Confi{
	private $servername = "localhost:3360";
	private $username = "root";
	private $password = "";
	private $db = "test";
	
 	
	public function connection(){
		
	    if(!isset($this->conn)){
            // Connect to the database
            $mysqli = new mysqli($this->servername, $this->username, $this->password, $this->db);
            if($mysqli->connect_error){
                die("Failed to connect with MySQL: " . $mysqli->connect_error);
            }else{
                $this->conn = $mysqli;
            }
			return $this->conn; 
         }
     }
}

Now, all set for create new class file and just include that connection file. We can create products.php file where we can setup add, view, update and delete functions. So, let’s start with view data and implement view call .

Create products.php

<?php
	class products{
		private $conn;
		public $id;
		public $product_name;
		public $product_desc;
		public $datetime;
		public $price;
		
		function __construct($db){
			$this->db=$db;
		}
		
		function read($id=''){
			$where=!empty($id)?" WHERE id='".$id."'":"";
			$result=$this->db->query("SELECT * FROM product_rest_api $where ORDER BY id DESC");
			
			$response=array();
			$data=array();
			if($result->num_rows > 0){
				while($row = $result->fetch_assoc()){
					$data[] = $row;
				}
				$response['response']='HTTP/1.1 200 OK';
				$response['result']=$data;
 				
			}else{
				$response['response']='HTTP/1.1 404 Not Found';
				$response['result']=null;

			}
			return $response;
			exit;
		}

After products.php file and let’s create view.php, in this file we can add config.php and products.php file. Read can perform single and display all data. if user pass single id then it retrieve single records, other wise all data display from table.

Create view.php file

<?php
	header("Access-Control-Allow-Origin: *");
	header("Content-Type: application/json; charset=UTF-8");
	include("./config.php");
	include("./products.php");
	
	$config=new Confi();
	$db=$config->connection();
	
	$product=new products($db);
	
	if(isset($_GET['id']) && is_numeric($_GET['id'])){
		$result=$product->read($_GET['id']);
	
	}else{
		$result=$product->read();
	}
	
	echo json_encode($result);	
?>
How to create REST API using PHP and MySQL.

Let’s create add records using API, we can add new create function call as adddata() and do add operation. So, copy and past below function code in product.php file.

function adddata($data){
	if(!empty($data) && is_array($data)){
		$i=0;
		$columns='';
		$values  = '';
		foreach($data as $key=>$val){
			$pre = ($i > 0)?', ':'';
			$columns .= $pre.$key;
			$values  .= $pre."'".$this->db->real_escape_string($val)."'";
			$i++;
		}
				
		$query = "INSERT INTO product_rest_api (".$columns.") VALUES (".$values.")";$insert = $this->db->query($query);
		return $insert?$this->db->insert_id:false;
	}
}

Further operation is for user to add data from front end side, so create new file call adddata.php. best example for insert data is register user input from mobile to store data in DB.

Create new file adddata.php

<?php
	header("Access-Control-Allow-Origin: *");
	header("Content-Type: application/json; charset=UTF-8");
	header("Access-Control-Allow-Methods: POST");
	header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
	
	include("./config.php");
	include("./products.php");
	
	$config=new Confi();
	$db=$config->connection();
	
	$product=new products($db);
	
	$data = json_decode(file_get_contents("php://input"));
	
	 
	$products=array();
	if(!empty($data->product_name) && !empty($data->product_desc) && !empty($data->price)){ 
		
		
		$products['product_name'] 	= $data->product_name;
		$products['product_desc']	= $data->product_desc;
		$products['price'] 		= $data->price;
		$products['datetime'] 		= date('Y-m-d H:m:s');	
		
		
		if($product->adddata($products)){         
			http_response_code(200);         
			echo json_encode(array("message" => "Product was created."));
		
		}else{
			http_response_code(503);        
			echo json_encode(array("message" => "Unable to create Product."));
		}
	
	}else{    
		http_response_code(400);    
		echo json_encode(array("message" => "Data is incomplete, Unable to create Product."));
	}		
How to create REST API using PHP and MySQL.

After READ and INSERT DATA let’s do another operation UPDATE, inside products.php create new function updatedata.php.

function updatedata($data,$condition){
	if(!empty($data) && is_array($data)){
		$i=0;
		$columns='';
		$values  = '';
		$whereSql='';
				
		foreach($data as $key=>$val){
			$pre = ($i > 0)?', ':'';
			$columns .= $pre.$key."='".$this->db->real_escape_string($val)."'";
			$i++;
		}
				
		if(!empty($condition)&& is_array($condition)){
			$whereSql .= ' WHERE ';
			$i = 0;
			foreach($condition as $key => $value){
				$pre = ($i > 0)?' AND ':'';
				$whereSql .= $pre.$key." = '".$value."'";
				$i++;
			}
		}
				
		$query = "UPDATE product_rest_api SET ".$columns.$whereSql;
		$update = $this->db->query($query);
		return $update?$this->db->affected_rows:false;
	}
}

Next, create new file updatedata.php for update data which user queried.

create new file updatadata.php

<?php

	header("Access-Control-Allow-Origin: *");
	header("Content-Type: application/json; charset=UTF-8");
	header("Access-Control-Allow-Methods: POST");
	header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
	
	include("./config.php");
	include("./products.php");
	
	$config=new Confi();
	$db=$config->connection();
	
	$product=new products($db);
	
	$data = json_decode(file_get_contents("php://input"));
	
	 
	$products=array();
	$condition=array();
	
	
	if(!empty($data->id) && !empty($data->product_name) && !empty($data->product_desc) && !empty($data->price)){ 
		
		$condition['id']		= $data->id;
		$products['product_name'] 	= $data->product_name;
		$products['product_desc']	= $data->product_desc;
		$products['price'] 		= $data->price;
		$products['datetime'] 		= date('Y-m-d H:m:s');	
		
		
		if($product->updatedata($products,$condition)){
			http_response_code(200);         
			echo json_encode(array("message" => "Product was created."));
		
		}else{
			http_response_code(503);        
			echo json_encode(array("message" => "Unable to create Product."));
		}
	
	}else{    
		http_response_code(400);    
		echo json_encode(array("message" => "Data is incomplete, Unable to create Product."));
	}		
?>
How to create REST API using PHP and MySQL.

Create new function deletedata

function deletedata($id){
	if(!empty($id) && is_numeric($id)){
		$query = "DELETE FROM product_rest_api WHERE id = ".$this->db->real_escape_string($id);
		$delete = $this->db->query($query);
		return $delete?true:false;
	}
}	

deletedata.php

Above delete function accepts the id and delete record from DB. Now, create user input field and delete data.

<?php
	header("Access-Control-Allow-Origin: *");
	header("Content-Type: application/json; charset=UTF-8");
	header("Access-Control-Allow-Methods: POST");
	header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
	
	include("./config.php");
	include("./products.php");
	
	$config=new Confi();
	$db=$config->connection();
	
	$product=new products($db);
	
	$data = json_decode(file_get_contents("php://input"));
	
	
	if(!empty($data->id)){
		if($product->deletedata($data->id)){
			http_response_code(200);         
			echo json_encode(array("message" => "Product was deleted."));
		
		}else{
			http_response_code(503);        
			echo json_encode(array("message" => "Unable to deleted Product."));
		}
	
	}else{
		http_response_code(400);    
		echo json_encode(array("message" => "Data is incomplete, Unable to deleted Product."));
	}
?>
How to create REST API using PHP and MySQL.

Create .htaccess file which helps to generate user friendly URL. Copy and Past below code inside .htaccess file.

RewriteEngine On    # Turn on the rewriting engine
RewriteRule ^view$ view.php [NC,L]
RewriteRule ^view/([0-9_-]*)$ view.php?id=$1 [NC,L]
RewriteRule ^create$ adddata.php [NC,L]
RewriteRule ^update$ updatedata.php [NC,L]
RewriteRule ^delete$ deletedata.php [NC,L]