Saturday, 12 May 2018

How to Make Simple Crud Rest Api in PHP with Mysql



We have already learned how can we do Create, Read, Update and delete CRUD operation by using PHP PDO, Mysql and Ajax. But in this post we have discuss how can do this all CRUD operation by using PHP api with Ajax. So, here we will make simple PHP Restful Api step by step.

What is REST Api in PHP?


But First we need to know what is Restful Api and what is the use of this Api in web development. Here REST means "REpresentational State Transfer". It is a simple method for manage information on internet. REST ideas are referred to as simple resources and rendering of resources should be stateless. It is mainly displayed by JSON format.

Same way API means "Application Programming Interface". This Api is place or guideline which allows one set of web application can be communicate with another. In that guidelines we can insert, update and delete data operation.

Rest API allow you web application to communicate with one or various different application by using REST concepts.

Why should we need PHP Rest API?


There are many PHP web application in which REST API is required because it is a simplest way to insert, update or delete data between various application over the internet by using HTTP protocol. REST API can be used by any type of web application which has been connected with internet. If any information from an web application has been inserted, updated or deleted by using another web application that means it has use REST API.

Now we have make a RESTful web service in PHP for CRUD operations. The REST API has been used by creating HTTP GET or POST or PUT or DELETE operation from client to server or server to get or put data. The REST API based web services can be given output in different format like CSV JSON etc. In this tutorial we will learn how to make simple REST API by using PHP Mysql. Now let's start learn how to create API in PHP.



File Structure


Following are the file structure of PHP REST API for CRUD operation.


  • api //In this folder we have store PHP API File
    • Api.php
    • //This is API class for Insert Update Delete
    • test_api.php
    • //This file will handle API request.
  • work //In this folder we will make file for send API request
    • index.php
    • fetch.php
    • action.php

How to Display or Fetch data by using PHP REST API


First we want to learn how to select all or fetch all data from Mysql database and display on web page. For this we have use Ajax with PHP. For this we have make Ajax function and this function has send request to fetch.php page and this page has send request to API which we have make under api/test_api.php. This page received api request for API class which we have make.

work/index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysql REST API CRUD</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   
   <h3 align="center">PHP Mysql REST API CRUD</h3>
   <br />
   <div align="right" style="margin-bottom:5px;">
    <button type="button" name="add_button" id="add_button" class="btn btn-success btn-xs">Add</button>
   </div>

   <div class="table-responsive">
    <table class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Edit</th>
       <th>Delete</th>
      </tr>
     </thead>
     <tbody></tbody>
    </table>
   </div>
  </div>
 </body>
</html>

<script type="text/javascript">
$(document).ready(function(){

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"fetch.php",
   success:function(data)
   {
    $('tbody').html(data);
   }
  })
 }
</script>


work/fetch.php



<?php

//fetch.php

$api_url = "http://localhost/tutorial/rest-api-crud-using-php/api/test_api.php?action=fetch_all";

$client = curl_init($api_url);

curl_setopt($client, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($client);

$result = json_decode($response);

$output = '';

if(count($result) > 0)
{
 foreach($result as $row)
 {
  $output .= '
  <tr>
   <td>'.$row->first_name.'</td>
   <td>'.$row->last_name.'</td>
   <td><button type="button" name="edit" class="btn btn-warning btn-xs edit" id="'.$row->id.'">Edit</button></td>
   <td><button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row->id.'">Delete</button></td>
  </tr>
  ';
 }
}
else
{
 $output .= '
 <tr>
  <td colspan="4" align="center">No Data Found</td>
 </tr>
 ';
}

echo $output;

?>


api/test_api.php



<?php

//test_api.php

include('Api.php');

$api_object = new API();

if($_GET["action"] == 'fetch_all')
{
 $data = $api_object->fetch_all();
}

echo json_encode($data);

?>


api/Api.php



<?php

//Api.php

class API
{
 private $connect = '';

 function __construct()
 {
  $this->database_connection();
 }

 function database_connection()
 {
  $this->connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 }

 function fetch_all()
 {
  $query = "SELECT * FROM tbl_sample ORDER BY id";
  $statement = $this->connect->prepare($query);
  if($statement->execute())
  {
   while($row = $statement->fetch(PDO::FETCH_ASSOC))
   {
    $data[] = $row;
   }
   return $data;
  }
 }

?>





How to Insert or Add Data into Mysql table using PHP REST API


If you have web application and if you want to make Android or IOS application then at that time from that application you want to Insert or Add data into your web application database then at that time PHP web services are use. PHP webservices has been created by using PHP api. So here we have learn how to insert or add data into Mysql table by using API from any mobile application. Here we have we have use Ajax for insert data into mysql table by using PHP api. For this we have send Ajax request to from index.php to action.php and on action.php we have send api request to api/test_api.php for insert or add data into mysql table. On api/test_api.php it has run method for insert or add data of api/Api.php. Below you can find complete code for insert data using PHP API.

work/index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysql REST API CRUD</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   
   <h3 align="center">PHP Mysql REST API CRUD</h3>
   <br />
   <div align="right" style="margin-bottom:5px;">
    <button type="button" name="add_button" id="add_button" class="btn btn-success btn-xs">Add</button>
   </div>

   <div class="table-responsive">
    <table class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Edit</th>
       <th>Delete</th>
      </tr>
     </thead>
     <tbody></tbody>
    </table>
   </div>
  </div>
 </body>
</html>

<div id="apicrudModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <form method="post" id="api_crud_form">
    <div class="modal-header">
           <button type="button" class="close" data-dismiss="modal">&times;</button>
           <h4 class="modal-title">Add Data</h4>
         </div>
         <div class="modal-body">
          <div class="form-group">
            <label>Enter First Name</label>
            <input type="text" name="first_name" id="first_name" class="form-control" />
           </div>
           <div class="form-group">
            <label>Enter Last Name</label>
            <input type="text" name="last_name" id="last_name" class="form-control" />
           </div>
       </div>
       <div class="modal-footer">
        <input type="hidden" name="hidden_id" id="hidden_id" />
        <input type="hidden" name="action" id="action" value="insert" />
        <input type="submit" name="button_action" id="button_action" class="btn btn-info" value="Insert" />
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
         </div>
   </form>
  </div>
   </div>
</div>


<script type="text/javascript">
$(document).ready(function(){

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"fetch.php",
   success:function(data)
   {
    $('tbody').html(data);
   }
  })
 }

 $('#add_button').click(function(){
  $('#action').val('insert');
  $('#button_action').val('Insert');
  $('.modal-title').text('Add Data');
  $('#apicrudModal').modal('show');
 });

 $('#api_crud_form').on('submit', function(event){
  event.preventDefault();
  if($('#first_name').val() == '')
  {
   alert("Enter First Name");
  }
  else if($('#last_name').val() == '')
  {
   alert("Enter Last Name");
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     fetch_data();
     $('#api_crud_form')[0].reset();
     $('#apicrudModal').modal('hide');
     if(data == 'insert')
     {
      alert("Data Inserted using PHP API");
     }
     if(data == 'update')
     {
      alert("Data Updated using PHP API");
     }
    }
   });
  }
 });

</script>


work/action.php



<?php

//action.php

if(isset($_POST["action"]))
{
 if($_POST["action"] == 'insert')
 {
  $form_data = array(
   'first_name' => $_POST['first_name'],
   'last_name'  => $_POST['last_name']
  );
  $api_url = "http://localhost/tutorial/rest-api-crud-using-php/api/test_api.php?action=insert";
  $client = curl_init($api_url);
  curl_setopt($client, CURLOPT_POST, true);
  curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
  curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($client);
  curl_close($client);
  $result = json_decode($response, true);
  foreach($result as $keys => $values)
  {
   if($result[$keys]['success'] == '1')
   {
    echo 'insert';
   }
   else
   {
    echo 'error';
   }
  }
 }
?>


api/test_api.php



<?php

//test_api.php

include('Api.php');

$api_object = new API();

if($_GET["action"] == 'insert')
{
 $data = $api_object->insert();
}

echo json_encode($data);

?>


api/Api.php



<?php

//Api.php

class API
{
 private $connect = '';

 function __construct()
 {
  $this->database_connection();
 }

 function database_connection()
 {
  $this->connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 }

 function insert()
 {
  if(isset($_POST["first_name"]))
  {
   $form_data = array(
    ':first_name'  => $_POST["first_name"],
    ':last_name'  => $_POST["last_name"]
   );
   $query = "
   INSERT INTO tbl_sample 
   (first_name, last_name) VALUES 
   (:first_name, :last_name)
   ";
   $statement = $this->connect->prepare($query);
   if($statement->execute($form_data))
   {
    $data[] = array(
     'success' => '1'
    );
   }
   else
   {
    $data[] = array(
     'success' => '0'
    );
   }
  }
  else
  {
   $data[] = array(
    'success' => '0'
   );
  }
  return $data;
 }

?>


How to Update or Edit Mysql data using PHP API


Above we have seen how to insert or add data using PHP API. But suppose we want to make some changes in data which we have inserted or store under mysql table from any Mobile application. Then at that time PHP API can we used by using PHP API we can edit or update our web application data remotly from any location and from any web device which has been connected with internet. We have to just send update or edit data request to PHP API. Below you can find complete source code for how to update or edit Mysql table data by using PHP Restful API.

work/index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysql REST API CRUD</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   
   <h3 align="center">PHP Mysql REST API CRUD</h3>
   <br />
   <div align="right" style="margin-bottom:5px;">
    <button type="button" name="add_button" id="add_button" class="btn btn-success btn-xs">Add</button>
   </div>

   <div class="table-responsive">
    <table class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Edit</th>
       <th>Delete</th>
      </tr>
     </thead>
     <tbody></tbody>
    </table>
   </div>
  </div>
 </body>
</html>

<div id="apicrudModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <form method="post" id="api_crud_form">
    <div class="modal-header">
           <button type="button" class="close" data-dismiss="modal">&times;</button>
           <h4 class="modal-title">Add Data</h4>
         </div>
         <div class="modal-body">
          <div class="form-group">
            <label>Enter First Name</label>
            <input type="text" name="first_name" id="first_name" class="form-control" />
           </div>
           <div class="form-group">
            <label>Enter Last Name</label>
            <input type="text" name="last_name" id="last_name" class="form-control" />
           </div>
       </div>
       <div class="modal-footer">
        <input type="hidden" name="hidden_id" id="hidden_id" />
        <input type="hidden" name="action" id="action" value="insert" />
        <input type="submit" name="button_action" id="button_action" class="btn btn-info" value="Insert" />
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
         </div>
   </form>
  </div>
   </div>
</div>


<script type="text/javascript">
$(document).ready(function(){

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"fetch.php",
   success:function(data)
   {
    $('tbody').html(data);
   }
  })
 }

 $('#add_button').click(function(){
  $('#action').val('insert');
  $('#button_action').val('Insert');
  $('.modal-title').text('Add Data');
  $('#apicrudModal').modal('show');
 });

 $('#api_crud_form').on('submit', function(event){
  event.preventDefault();
  if($('#first_name').val() == '')
  {
   alert("Enter First Name");
  }
  else if($('#last_name').val() == '')
  {
   alert("Enter Last Name");
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     fetch_data();
     $('#api_crud_form')[0].reset();
     $('#apicrudModal').modal('hide');
     if(data == 'insert')
     {
      alert("Data Inserted using PHP API");
     }
     if(data == 'update')
     {
      alert("Data Updated using PHP API");
     }
    }
   });
  }
 });

 $(document).on('click', '.edit', function(){
  var id = $(this).attr('id');
  var action = 'fetch_single';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{id:id, action:action},
   dataType:"json",
   success:function(data)
   {
    $('#hidden_id').val(id);
    $('#first_name').val(data.first_name);
    $('#last_name').val(data.last_name);
    $('#action').val('update');
    $('#button_action').val('Update');
    $('.modal-title').text('Edit Data');
    $('#apicrudModal').modal('show');
   }
  })
 });

</script>


work/action.php



<?php

//action.php

if(isset($_POST["action"]))
{

 if($_POST["action"] == 'fetch_single')
 {
  $id = $_POST["id"];
  $api_url = "http://localhost/tutorial/rest-api-crud-using-php/api/test_api.php?action=fetch_single&id=".$id."";
  $client = curl_init($api_url);
  curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($client);
  echo $response;
 }

 if($_POST["action"] == 'update')
 {
  $form_data = array(
   'first_name' => $_POST['first_name'],
   'last_name'  => $_POST['last_name'],
   'id'   => $_POST['hidden_id']
  );
  $api_url = "http://localhost/tutorial/rest-api-crud-using-php/api/test_api.php?action=update";
  $client = curl_init($api_url);
  curl_setopt($client, CURLOPT_POST, true);
  curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
  curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($client);
  curl_close($client);
  $result = json_decode($response, true);
  foreach($result as $keys => $values)
  {
   if($result[$keys]['success'] == '1')
   {
    echo 'update';
   }
   else
   {
    echo 'error';
   }
  }
 }

?>


api/test_api.php



<?php

//test_api.php

include('Api.php');

$api_object = new API();


if($_GET["action"] == 'fetch_single')
{
 $data = $api_object->fetch_single($_GET["id"]);
}

if($_GET["action"] == 'update')
{
 $data = $api_object->update();
}

echo json_encode($data);

?>


api/Api.php



<?php

//Api.php

class API
{
 private $connect = '';

 function __construct()
 {
  $this->database_connection();
 }

 function database_connection()
 {
  $this->connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 }

 function fetch_all()
 {
  $query = "SELECT * FROM tbl_sample ORDER BY id";
  $statement = $this->connect->prepare($query);
  if($statement->execute())
  {
   while($row = $statement->fetch(PDO::FETCH_ASSOC))
   {
    $data[] = $row;
   }
   return $data;
  }
 }

 function fetch_single($id)
 {
  $query = "SELECT * FROM tbl_sample WHERE id='".$id."'";
  $statement = $this->connect->prepare($query);
  if($statement->execute())
  {
   foreach($statement->fetchAll() as $row)
   {
    $data['first_name'] = $row['first_name'];
    $data['last_name'] = $row['last_name'];
   }
   return $data;
  }
 }

 function update()
 {
  if(isset($_POST["first_name"]))
  {
   $form_data = array(
    ':first_name' => $_POST['first_name'],
    ':last_name' => $_POST['last_name'],
    ':id'   => $_POST['id']
   );
   $query = "
   UPDATE tbl_sample 
   SET first_name = :first_name, last_name = :last_name 
   WHERE id = :id
   ";
   $statement = $this->connect->prepare($query);
   if($statement->execute($form_data))
   {
    $data[] = array(
     'success' => '1'
    );
   }
   else
   {
    $data[] = array(
     'success' => '0'
    );
   }
  }
  else
  {
   $data[] = array(
    'success' => '0'
   );
  }
  return $data;
 }

?>


How to Delete or Remove data from Mysql using PHP API


This is last operation of CRUD and here we want to learn how can we delete or remove Mysql table data by using PHP REST API. API we can access from any place and from any device just we have access key particular API. So, suppose we want to just delete or remove some information from wep application by using web device application. So, from application we have to just send request to API from delete or remove particular data from your database. API will remove or delete data and it will send request back to particular application from where it has received request. Below you find how to delete or remove Mysql table data by using PHP API with Ajax.

work/index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysql REST API CRUD</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   
   <h3 align="center">PHP Mysql REST API CRUD</h3>
   <br />
   <div align="right" style="margin-bottom:5px;">
    <button type="button" name="add_button" id="add_button" class="btn btn-success btn-xs">Add</button>
   </div>

   <div class="table-responsive">
    <table class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Edit</th>
       <th>Delete</th>
      </tr>
     </thead>
     <tbody></tbody>
    </table>
   </div>
  </div>
 </body>
</html>

<div id="apicrudModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <form method="post" id="api_crud_form">
    <div class="modal-header">
           <button type="button" class="close" data-dismiss="modal">&times;</button>
           <h4 class="modal-title">Add Data</h4>
         </div>
         <div class="modal-body">
          <div class="form-group">
            <label>Enter First Name</label>
            <input type="text" name="first_name" id="first_name" class="form-control" />
           </div>
           <div class="form-group">
            <label>Enter Last Name</label>
            <input type="text" name="last_name" id="last_name" class="form-control" />
           </div>
       </div>
       <div class="modal-footer">
        <input type="hidden" name="hidden_id" id="hidden_id" />
        <input type="hidden" name="action" id="action" value="insert" />
        <input type="submit" name="button_action" id="button_action" class="btn btn-info" value="Insert" />
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
         </div>
   </form>
  </div>
   </div>
</div>


<script type="text/javascript">
$(document).ready(function(){

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"fetch.php",
   success:function(data)
   {
    $('tbody').html(data);
   }
  })
 }

 $('#add_button').click(function(){
  $('#action').val('insert');
  $('#button_action').val('Insert');
  $('.modal-title').text('Add Data');
  $('#apicrudModal').modal('show');
 });

 $('#api_crud_form').on('submit', function(event){
  event.preventDefault();
  if($('#first_name').val() == '')
  {
   alert("Enter First Name");
  }
  else if($('#last_name').val() == '')
  {
   alert("Enter Last Name");
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     fetch_data();
     $('#api_crud_form')[0].reset();
     $('#apicrudModal').modal('hide');
     if(data == 'insert')
     {
      alert("Data Inserted using PHP API");
     }
     if(data == 'update')
     {
      alert("Data Updated using PHP API");
     }
    }
   });
  }
 });

 $(document).on('click', '.edit', function(){
  var id = $(this).attr('id');
  var action = 'fetch_single';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{id:id, action:action},
   dataType:"json",
   success:function(data)
   {
    $('#hidden_id').val(id);
    $('#first_name').val(data.first_name);
    $('#last_name').val(data.last_name);
    $('#action').val('update');
    $('#button_action').val('Update');
    $('.modal-title').text('Edit Data');
    $('#apicrudModal').modal('show');
   }
  })
 });

 $(document).on('click', '.delete', function(){
  var id = $(this).attr("id");
  var action = 'delete';
  if(confirm("Are you sure you want to remove this data using PHP API?"))
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{id:id, action:action},
    success:function(data)
    {
     fetch_data();
     alert("Data Deleted using PHP API");
    }
   });
  }
 });

});
</script>


work/action.php



<?php

//action.php

if(isset($_POST["action"]))
{
 
 if($_POST["action"] == 'delete')
 {
  $id = $_POST['id'];
  $api_url = "http://localhost/tutorial/rest-api-crud-using-php/api/test_api.php?action=delete&id=".$id."";
  $client = curl_init($api_url);
  curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($client);
  echo $response;
 }
}


?>


api/test_api.php



<?php

//test_api.php

include('Api.php');

$api_object = new API();

if($_GET["action"] == 'delete')
{
 $data = $api_object->delete($_GET["id"]);
}

echo json_encode($data);

?>


api/Api.php


<?php

//Api.php

class API
{
 private $connect = '';

 function __construct()
 {
  $this->database_connection();
 }

 function database_connection()
 {
  $this->connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 }

 function delete($id)
 {
  $query = "DELETE FROM tbl_sample WHERE id = '".$id."'";
  $statement = $this->connect->prepare($query);
  if($statement->execute())
  {
   $data[] = array(
    'success' => '1'
   );
  }
  else
  {
   $data[] = array(
    'success' => '0'
   );
  }
  return $data;
 }
}

?>


So, this is complete web tutorial on How to Create RESTful API in PHP and by using PHP API how to insert, update and delete data from Mysql table. If you want to download complete source code of PHP RESTful API then you have to click on below link.




0 comments:

Post a Comment