How to create a Restful Service in Php and MySQL with JSON data as output? (In Simple Steps)

Step 1 : 

Go to phpMyAdmin ,
select an existing database or create one

Step 2 : 

Create a sample Table (for eg: customers)

Step 3 : 

Insert a few records into the table

Step 4 : 

Create a new php page under www folder (or public_html folder)
Give name for your page (for eg: Get_Customers.php)

Step 5 : 

In the php page, follow these steps
              

             1. Connect to your database

       
 <?php
       
 $con = mysqli_connect("localhost", "<user name>" , "<password>", "<db name>") or die('could not connect');

//Write a query
$qry = "SELECT * FROM  Customers"

//Execute the query
$result = mysqli_query($con,$qry);
?>

               2. Put the data into array

<?php

$json = array();

//Loop through each record in the database and read the values
while($row=mysqli_fetch_array($result))
  {
      $arrcustomers = array
      (
         'customer_id' => $row['customer_id'],
         'customer_name' => $row['customer_name'],
         'shop_name' => $row['shop_name'],
         'loyalty_points' => $row['loyalty_points']
      );
           //push each row into an array
         array_push($json, $arrcustomers);
  }
?>


               3. Output the array as json


<?php

$json1['Customers']=$json;
echo json_encode($json1);

?>

Step 6 : 

Call Php Page in browser (for eg: http://localhost/Get_Customers.php)

Step 7 : 

Get the Result in Web Page in JSON format

Result:

{"Customers":[{"customer_id":"1","customer_name":"sam","shop_name":"SamMedicals","loyalty_points":"50"},{"customer_id":"2","customer_name":"sandy","shop_name":"upahar_gruha","loyalty_points":"100"},{"customer_id":"3","customer_name":"vishal","shop_name":"vishal_panshop","loyalty_points":"30"},{"customer_id":"4","customer_name":"sunny","shop_name":"sunnys shop","loyalty_points":"40"}]}


I hope this article was helpful for beginners trying to create a simple php RESTful service.
I am Shruti Kulkarni and I am a beginner myself with one month of total experience working at Nanite Solutions as an iOS developer.

If you have further questions about RESTful services please feel free to write to me at shruti@nanitesol.com

Thanks

Guided by: Praveen Kumar, Nanite Solutions

Other blogs by the author
55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 

Comments

Popular posts from this blog

Internet of Things - MindMap

Creating a Mobile Strategy: Find out the top 10 ways!

Trends in Cloud Computing for 2016 and Beyond