HOME
PRIVACY POLICY
ABOUT US

Creating simple PHP RESTFull Web Api performing CRUD Operation using MYSQL

What is RestFull Web API ?

API ( Application Programming Interface ) . As the name Suggested it is interface used to talk to system by Exchange Data with the system or taking required data from the system . API is a medium to exchange data between server and client technology . It Basically uses two type of data transfer technique JSON or XML . We will try to explain this through an example . Lets say you have simple website which has static contain and you take contact information through form in website . But let say now you want to develop Application for both android and ios and you also want that contact information should also be taken through this application . In this scenario you need to talk to your server for Saving data to the server . You have to write SERVER Side WEB API to accept data from any node ( clients ) and save it to your server .


How to Create RESTFull Web API ?

API Can be Created in Any WEB server technology like PHP , NODEJS , ASP.net , Python , Ruby etc . In this Article we will be creating for Web API for PHP for our Student Detail System . We Will Perform Full CRUD Operation through Web API . To know more about our TASK Kindly Refer to this blog

Requirements

  1. Visual Studio Code . Installing Procedure .
  2. WAMP Server 2.5 . Download from here .
  3. POSTMAN ( To Test Web API) . Download from here .

STEP 1,2:

You can see from here. From the blog you will able to create database , tables for student details system .


STEP 3:CREATE PROJECT


  1. Create New Folder name as StudentApi . In C:/wamp/www/
  2. Now Create new file name as index.php in that folder .In C:/wamp/www/Student/
  3. Open this folder in Visual Studio Code

STEP 4:CRUD Operations

We Will be writing API only in one file for simplicity of understanding name as index.php . We will be Accepting All Request in POST method only because it is more secure than GET and we will Distinguishing all our operation using Following Keywords for Type parameters which will be


  1. Insert ( for insert Operation)
  2. Update ( for Update Operation which will be done on student_id parameter)
  3. Search ( for Searching single Records using student_id )
  4. GetAllRecords ( For Getting all Student Records Available in table)
  5. Delete ( For Deleting Single Records on student_id )

Checking Function

A function is there to check the presence of parameter in POST query in API . It will Check Parameters


function CheckAllParameters($Name,$Address,$Telephone,$Standard,$Roll_Number)
{
    if($Name == "" || $Address == "" || $Telephone == "" || $Standard == "" || $Roll_Number == "")
    {
        $data = array('status' =>0 , 'msg'=>'Kindly Enter all Information');
        echo json_encode($data);
    return false;
    }else
    {
        return true;
    }
}


Connecting to the Database by


$dbc=mysqli_connect("localhost","root","","studentdb");


How to take POST parameters in PHP


$Type = $_POST["Type"];

We will Distinguish Different Request Of Operation on the Basis of Type which will be requested by client .


INSERT OPERATION

We will Insert Records To the system by Getting Parameters from POST request . Code Show below


if($Type == "Insert")
{
$Name= $_POST['Name'];
$Address= $_POST['Address'];
$Telephone= $_POST['Telephone'];
$Standard= $_POST['Standard'];
$Roll_Number= $_POST['Roll_Number'];
 $checker = CheckAllParameters($Name,$Address,$Telephone,$Standard,$Roll_Number);
 if($checker)
 {
    $query = "Insert into student_table(Name,Address,Telephone,Standard,Roll_Number) Values('$Name','$Address','$Telephone','$Standard','$Roll_Number')";            
    $res  = $dbc->query($query);
    if($res)
    {
        $data = array('status' =>1 , 'msg'=>'Information Saved Successfully');
        echo json_encode($data);
    }else
    {
        $data = array('status' => 0, 'msg'=>'Some Error Occured');
        echo json_encode($data);
    }
 }
}

In the above code we are taking All Parameters from POST request and Checking it . if it is OK we will INSERT it in our students table and return success message otherwise we will return Error Message that some error has occured .

Update Operation

We will Update Records On the basis of student_id which will be getting through Parameters from POST request . We can update all fields in the table through this operation . Code Shown Below .

if($Type == "Update")
{
    $Name= $_POST['Name'];
    $Address= $_POST['Address'];
    $Telephone= $_POST['Telephone'];
    $Standard= $_POST['Standard'];
    $Roll_Number= $_POST['Roll_Number'];
    $Student_Id=$_POST['student_id'];
    $checker = CheckAllParameters($Name,$Address,$Telephone,$Standard,$Roll_Number);
    if($checker)
    {
        $query = "UPDATE  student_table SET Name='$Name',Address='$Address',Telephone='$Telephone',Standard='$Standard',Roll_Number='$Roll_Number' WHERE student_id=$Student_Id";            
       $res  = $dbc->query($query);
       if($res)
       {
           $data = array('status' =>1 , 'msg'=>'Information Updated Successfully');
           echo json_encode($data);
       }else
       {
           $data = array('status' => 0, 'msg'=>'Some Error Occured');
           echo json_encode($data);
       }
    }
}

In the above code we are taking All Parameters from POST request and Checking it . if it is OK we will Update it in our students table on the basis on student_id and return success message otherwise we will return Error Message that some error has occured .

Search Operation

We will Search Records on the basis of student_id . If we Found the record we will giving data in json to the client or node . So that it can consume it properly.

if($Type == "Search")
{
    $Student_Id=$_POST['student_id'];
    $query = "select * from student_table where student_id='$Student_Id'";       
    $res  = $dbc->query($query);
    if($res)
   { 
    $data['status']="1";
    $row = $res->fetch_assoc();
    $data['data'] = $row;
 
    echo json_encode($data);
   }else 
   {
    $data = array('status' => 0, 'msg'=>'No Record Found');
    echo json_encode($data);
   }

}

GET ALL RECORDS

We will Get All Records through this type . We will pass all this data in JSON format so that client can properly consumes it .

if($Type == "GetAllRecords")
{
    $query = "select * from student_table";       
    $res  = $dbc->query($query);
    if($res)
   { 
    $data['status']="1";
       while($row = $res->fetch_assoc())
         { $data['data'][] = $row;}
       
    echo json_encode($data);
   }else 
   {
    $data = array('status' => 0, 'msg'=>'No Record Found');
    echo json_encode($data);
   }

}

DELETE OPERATION

We Can Delete record using this student_id . Return its success message if executes successfully .

if($Type == "Delete")
{
    $Student_Id=$_POST['student_id'];
    $query = "DELETE FROM  student_table  WHERE student_id=$Student_Id";            
    $res  = $dbc->query($query);
    if($res)
    {
        $data = array('status' =>1 , 'msg'=>'Information Deleted Successfully');
        echo json_encode($data);
    }else
    {
        $data = array('status' => 0, 'msg'=>'Some Error Occured');
        echo json_encode($data);
    }

}

FULL Code is Available Below . Just Copy Paste it in your index.php file

<?php 
$dbc=mysqli_connect("localhost","root","","studentdb");
$Type = $_POST["Type"];

function CheckAllParameters($Name,$Address,$Telephone,$Standard,$Roll_Number)
{
    if($Name == "" || $Address == "" || $Telephone == "" || $Standard == "" || $Roll_Number == "")
    {
        $data = array('status' =>0 , 'msg'=>'Kindly Enter all Information');
        echo json_encode($data);
    return false;
    }else
    {
        return true;
    }
}

if($Type == "Insert")
{
$Name= $_POST['Name'];
$Address= $_POST['Address'];
$Telephone= $_POST['Telephone'];
$Standard= $_POST['Standard'];
$Roll_Number= $_POST['Roll_Number'];
 $checker = CheckAllParameters($Name,$Address,$Telephone,$Standard,$Roll_Number);
 if($checker)
 {
    $query = "Insert into student_table(Name,Address,Telephone,Standard,Roll_Number) Values('$Name','$Address','$Telephone','$Standard','$Roll_Number')";            
    $res  = $dbc->query($query);
    if($res)
    {
        $data = array('status' =>1 , 'msg'=>'Information Saved Successfully');
        echo json_encode($data);
    }else
    {
        $data = array('status' => 0, 'msg'=>'Some Error Occured');
        echo json_encode($data);
    }
 }
}else if($Type == "Update")
{
    $Name= $_POST['Name'];
    $Address= $_POST['Address'];
    $Telephone= $_POST['Telephone'];
    $Standard= $_POST['Standard'];
    $Roll_Number= $_POST['Roll_Number'];
    $Student_Id=$_POST['student_id'];
    $checker = CheckAllParameters($Name,$Address,$Telephone,$Standard,$Roll_Number);
    if($checker)
    {
        $query = "UPDATE  student_table SET Name='$Name',Address='$Address',Telephone='$Telephone',Standard='$Standard',Roll_Number='$Roll_Number' WHERE student_id=$Student_Id";            
       $res  = $dbc->query($query);
       if($res)
       {
           $data = array('status' =>1 , 'msg'=>'Information Updated Successfully');
           echo json_encode($data);
       }else
       {
           $data = array('status' => 0, 'msg'=>'Some Error Occured');
           echo json_encode($data);
       }
    }
}else if($Type == "Search")
{
    $Student_Id=$_POST['student_id'];
    $query = "select * from student_table where student_id='$Student_Id'";       
    $res  = $dbc->query($query);
    if($res)
   { 
    $data['status']="1";
    $row = $res->fetch_assoc();
    $data['data'] = $row;
 
    echo json_encode($data);
   }else 
   {
    $data = array('status' => 0, 'msg'=>'No Record Found');
    echo json_encode($data);
   }

}else if($Type == "GetAllRecords")
{
    $query = "select * from student_table";       
    $res  = $dbc->query($query);
    if($res)
   { 
    $data['status']="1";
       while($row = $res->fetch_assoc())
         { $data['data'][] = $row;}
       
    echo json_encode($data);
   }else 
   {
    $data = array('status' => 0, 'msg'=>'No Record Found');
    echo json_encode($data);
   }

}else if($Type == "Delete")
{
    $Student_Id=$_POST['student_id'];
    $query = "DELETE FROM  student_table  WHERE student_id=$Student_Id";            
    $res  = $dbc->query($query);
    if($res)
    {
        $data = array('status' =>1 , 'msg'=>'Information Deleted Successfully');
        echo json_encode($data);
    }else
    {
        $data = array('status' => 0, 'msg'=>'Some Error Occured');
        echo json_encode($data);
    }

}
?>

TESTING WITH POSTMAN :

POSTMAN is a RestFULL Web API testing tools . It makes life really easy to test Web API . All our Web APIs URL and parameters detail is given below


  1. INSERT OPERATION
  • URL:http://localhost/StudentApi
  • TYPE=POST
  • PARAMETERS : { Type=Insert, Name=Can be any,Address=Can be any ,Telephone=Can be any , Standard=Can be any ,Roll_Number=Can be any}


2.UPDATE OPERATION


  • URL:http://localhost/StudentApi
  • TYPE=POST
  • PARAMETERS : : { Type=Update,student_id=Of Changing Record, Name=Can be any',Address=Can be any ,Telephone=Can be any, Standard=Can be any ,Roll_Number=Can be any}


3.SEARCH OPERATION


  • URL:http://localhost/StudentApi
  • TYPE=POST
  • PARAMETERS : { Type=Search ,student_id=Of Record }


4.GETALLRECORDS.


  • URL:http://localhost/StudentApi
  • TYPE=POST
  • PARAMETERS : { Type=GetAllRecords }


5.DELETE OPERATION

  • URL:http://localhost/StudentApi
  • TYPE=POST
  • PARAMETERS : { Type=Delete,student_id=Of Record }

For more Queries and Question kindly post on Facebook group

Want to know more about me .click here

Taher Software Engineer

Related Posts