Welcome to RohanSakhale.com | Home » Codes » Create web service using php & jsonTime: 01-06-2016 06:06:06 | Contact me


Create web service using php & json

Added by: Rohan Sakhale | Date: (24-05-2012 | 02:05:40) | Tags: PHP | Views: 8612 | Comments: 4

The following program will help us create a web service which can be called via HTTP calls from any language example Java application that can be a mobile app, desktop app or web app.

Goal is to retrieve data stored on a server

We will consider an example of a database having information of teachers.

So our database will have a table name 'teacher' which will have fields called 'id' -> teacher id, 'name' -> teacher name, 'address' -> address of teacher, 'qualification' -> qualification of teacher, 'contact' -> contact number of teacher etc.

So when we make calls to our web service by giving additional information via url we can retrieve details of particular teacher or all teachers.

The output data after requesting the server will be given into json format which can be accessed very easily from any language like Java etc.

DEMO: http://rohansakhale.com/getteacherdata.php

You can also read on how to use this service: http://rohansakhale.com/codes/33/using-json-web-service-into-java-program

Below is the Code:
First we will see if the user is requesting particular data or he wants all the data
So we will use get method parameters to retrieve single teacher data by taking his id

$query = "select * from `teachers`";
Query to retrieve all teachers data

	$query .= " where `id` = " . $_GET['id'];
above if condition will help to sort data according to teacher id

//Execute and store resultant object
$result = mysql_query($query);

//check if result is more than 0
if(mysql_num_rows($result) > 0){
	$arr = array();
	// create arr object
	while($row = mysql_fetch_assoc($result))
		$arr[] = $row;
		// add entire row of sql resultant as element into array object
	echo json_encode($arr);
	// output the entire arr into json format
	echo 'invalid teacher id';
	// Display invalid id given

No attachment added for this code

Next Code
Previous Code
Back to Codes Page

Rohan Sakhale
Date: (12-07-2013 | 02:07:51)
@Sheeshkamal, In case no results were found, you can send an error json response with error code and error message usually done in empty response body in case it happens due to some error Ex: {"error":1,"message":"No results found"}

Date: (14-06-2013 | 03:06:46)
What to do and how to detect if no result is returned?

Rohan Sakhale
Date: (03-01-2013 | 06:01:30)
@Angsuman: Yes, you will need to make use of PHP or any other language to invoke the webservice which later could be manipulated by javascript and everything this can be carried out using AJAX calls.

Angsuman Chatterjee
Date: (22-12-2012 | 03:12:59)
Is it possible to call this web service from a HTML5 mobile app with jQuery ajax?

Add your Comment