Create Web Service using PHP & JSON

5/24/2012 code-examplephp

# Summary

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 request 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 Get Teacher Data (opens new window)

You can also read on Using JSON Web Service in Java

# 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
*/

if(isset($_GET['id'])){
	// if teacher id exists, search by id only to give precised results
	$query .= " where `id` = " . $_GET['id'];
}

//Execute and store resultant object
$result = $con->query($query);

//check if result is more than 0
if($result && $result->num_rows > 0){
	$arr = [];
	// create arr object
	while($row = $result->fetch_assoc())
	{
		$arr[] = $row;
		// add entire row of sql resultant as element into array object
	}
	echo json_encode($arr);
	// output the entire arr into json format
}else{
	echo json_encode(['error' => 'invalid teacher id']);
	// Display invalid id given
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33