REST API CRUD Example in PHP with MySQLi

REST API CRUD Example in PHP with MySQLi

Today, We want to share with you REST API CRUD Example in PHP with MySQLi.In this post we will show you PHP CRUD RESTFul Webservice API Using PDOModel, hear for How to Create a Simple CRUD REST API in PHP PDO we will give you demo and example for implement.In this post, we will learn about Create and Consume Simple REST API in PHP with an example.

REST API CRUD Example in PHP with MySQLi

There are the Following The simple About REST API CRUD Example in PHP with MySQLi Full Information With Example and source code.

As I will cover this Post with live Working example to develop php rest api tutorial step by step, so the Creating a simple REST API in PHP Directory structures for this example is following below.

Step 1: dbcontroller.php

<?php
class DBController {
  private $conn = "";
  private $host = "localhost";
  private $user = "root";
  private $password = "";
  private $database = "blog_product";

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

  function connectDB() {
    $conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
    return $conn;
  }

  function executeQuery($query) {
        $conn = $this->connectDB();    
        $result = mysqli_query($conn, $query);
        if (!$result) {
            //check for duplicate entry
            if($conn->errno == 1062) {
                return false;
            } else {
                trigger_error (mysqli_error($conn),E_USER_NOTICE);
        
            }
        }   
        $affectedRows = mysqli_affected_rows($conn);
    return $affectedRows;
    
    }
  function executeSelectQuery($query) {
    $result = mysqli_query($this->conn,$query);
    while($row=mysqli_fetch_assoc($result)) {
      $resultset[] = $row;
    }
    if(!empty($resultset))
      return $resultset;
  }
}
?>

Step 2: Product.php

<?php
require_once("dbcontroller.php");

Class Product {
  private $mobiles = array();
  public function getAllProduct(){
    if(isset($_GET['name'])){
      $name = $_GET['name'];
      $query = 'SELECT * FROM tbl_product WHERE name LIKE "%' .$name. '%"';
    } else {
      $query = 'SELECT * FROM tbl_product';
    }
    $dbcontroller = new DBController();
    $this->mobiles = $dbcontroller->executeSelectQuery($query);
    return $this->mobiles;
  }

  public function addProduct(){
    if(isset($_POST['name'])){
      $name = $_POST['name'];
        $model = '';
        $color = '';
      if(isset($_POST['model'])){
        $model = $_POST['model'];
      }
      if(isset($_POST['color'])){
        $color = $_POST['color'];
      } 
      $query = "insert into tbl_product (name,model,color) values ('" . $name ."','". $model ."','" . $color ."')";
      $dbcontroller = new DBController();
      $result = $dbcontroller->executeQuery($query);
      if($result != 0){
        $result = array('success'=>1);
        return $result;
      }
    }
  }
  
  public function deleteProduct(){
    if(isset($_GET['id'])){
      $id = $_GET['id'];
      $query = 'DELETE FROM tbl_product WHERE id = '.$id;
      $dbcontroller = new DBController();
      $result = $dbcontroller->executeQuery($query);
      if($result != 0){
        $result = array('success'=>1);
        return $result;
      }
    }
  }
  
  public function editProduct(){
    if(isset($_POST['name']) && isset($_GET['id'])){
      $name = $_POST['name'];
      $model = $_POST['model'];
      $color = $_POST['color'];
      $query = "UPDATE tbl_product SET name = '".$name."',model ='". $model ."',color = '". $color ."' WHERE id = ".$_GET['id'];
    }
    $dbcontroller = new DBController();
    $result= $dbcontroller->executeQuery($query);
    if($result != 0){
      $result = array('success'=>1);
      return $result;
    }
  }
  
}
?>

Step 3: ProducTresThandler.php

<?php
require_once("SimpleRest.php");
require_once("Product.php");
    
class MobileRestHandler extends SimpleRest {

  function getAllProducts() { 

    $product = new Product();
    $proDuctData = $product->getAllProduct();

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

    $requestContentType = $_SERVER['HTTP_ACCEPT'];
    $this ->setHttpHeaders($requestContentType, $statusCode);
    
    $result["output"] = $proDuctData;
        
    if(strpos($requestContentType,'application/json') !== false){
      $response = $this->encodeJson($result);
      echo $response;
    }
  }
  
  function add() {  
    $product = new Product();
    $proDuctData = $product->addProduct();
    if(empty($proDuctData)) {
      $statusCode = 404;
      $proDuctData = array('success' => 0);   
    } else {
      $statusCode = 200;
    }
    
    $requestContentType = $_SERVER['HTTP_ACCEPT'];
    $this ->setHttpHeaders($requestContentType, $statusCode);
    $result = $proDuctData;
        
    if(strpos($requestContentType,'application/json') !== false){
      $response = $this->encodeJson($result);
      echo $response;
    }
  }

  function deleteProductById() {  
    $product = new Product();
    $proDuctData = $product->deleteProduct();
    
    if(empty($proDuctData)) {
      $statusCode = 404;
      $proDuctData = array('success' => 0);   
    } else {
      $statusCode = 200;
    }
    
    $requestContentType = $_SERVER['HTTP_ACCEPT'];
    $this ->setHttpHeaders($requestContentType, $statusCode);
    $result = $proDuctData;
        
    if(strpos($requestContentType,'application/json') !== false){
      $response = $this->encodeJson($result);
      echo $response;
    }
  }
  
  function editProductById() {  
    $product = new Product();
    $proDuctData = $product->editProduct();
    if(empty($proDuctData)) {
      $statusCode = 404;
      $proDuctData = array('success' => 0);   
    } else {
      $statusCode = 200;
    }
    
    $requestContentType = $_SERVER['HTTP_ACCEPT'];
    $this ->setHttpHeaders($requestContentType, $statusCode);
    $result = $proDuctData;
        
    if(strpos($requestContentType,'application/json') !== false){
      $response = $this->encodeJson($result);
      echo $response;
    }
  }
  
  public function encodeJson($responseData) {
    $jsonResponse = json_encode($responseData);
    return $jsonResponse;   
  }
}
?>

Step 4: ApiController.php

<?php
require_once("ProducTresThandler.php");
$method = $_SERVER['REQUEST_METHOD'];
$view = "";
if(isset($_GET["page_key"]))
  $page_key = $_GET["page_key"];
/*
controls the RESTful services
URL mapping
*/
  switch($page_key){

    case "list":
      // to handle REST Url /product/list/
      $productRestHandler = new ProducTresThandler();
      $result = $productRestHandler->getAllProducts();
      break;
  
    case "create":
      // to handle REST Url /product/create/
      $productRestHandler = new ProducTresThandler();
      $productRestHandler->add();
    break;
    
    case "delete":
      // to handle REST Url /product/delete/<row_id>
      $productRestHandler = new ProducTresThandler();
      $result = $productRestHandler->deleteProductById();
    break;
    
    case "update":
      // to handle REST Url /product/update/<row_id>
      $productRestHandler = new ProducTresThandler();
      $productRestHandler->editProductById();
    break;
}
?>


Step 5: SimpleRest.php

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

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

Step 6: .htaccess

# Turn rewrite engine on
Options +FollowSymlinks
RewriteEngine on

# map neat URL to internal URL
RewriteRule ^product/list/$   ApiController.php?page_key=list [nc,qsa]
RewriteRule ^product/list$   ApiController.php?page_key=list [nc,qsa]

RewriteRule ^product/create/$   ApiController.php?page_key=create [L]
RewriteRule ^product/create$   product/create/ [L,R=301]

RewriteRule ^product/delete/([0-9]+)/$   ApiController.php?page_key=delete&id=$1 [L]
RewriteRule ^product/delete([0-9]+)$   product/delete/$1 [L,R=301]

RewriteRule ^product/update/([0-9]+)/$   ApiController.php?page_key=update&id=$1 [L]
RewriteRule ^product/update/([0-9]+)$   product/update/$1/ [L,R=301]

Web Programming Tutorials Example with Demo

Read :

  How to Integrate Google No CAPTCHA reCAPTCHA using VueJS

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about REST API CRUD Example in PHP with MySQLi.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Reply

avatar
  Subscribe  
Notify of