Web Services Tutorial

Web Services TutorialIn my web services tutorial I will cover generating JSON and XML. We’ll then walk through examples in which we use REST, SOAP and RPC (Remote Procedure Calls). We’ll pull data from databases and if you haven’t seen them I have videos on PHP, MySQL and using PHP with MySQL.

Here I’ll focus on how JSON is structured and demonstrate how to pull data from MySQL and then generate and decode JSON using PHP. The code follows the video.

If you like videos like this, it helps to tell Google Plus with a click here

Code From the Video

JSON Code Example

{"first_name": "Dale",
"last_name": "Cooper",
"age": 35,
"enrolled": true,
"married": null,
"address":{
"street": "123 Main St",
"city": "Seattle",
"state": "WA"
},
"phone": [
{"type": "home",
"number": "4125551212"
},
{"type": "mobile",
"number": "4125552121"
}
]}

StudentDB.php

<?php

class StudentDB {

	public $first_name = "";
	public $last_name = "";
	public $email = "";
	public $street = "";
	public $city = "";
	public $state = "";
	public $zip;
	public $phone = "";
	public $birth_date = "";
	public $sex = "";
	public $date_entered = "";
	public $lunch_cost;
	public $student_id;
	
	function __construct($first_name, $last_name, $email, $street,
		$city, $state, $zip, $phone, $birth_date, $sex,
		$date_entered, $lunch_cost, $studentid){
	
		$this->first_name = $first_name;
		$this->last_name = $last_name;
		$this->email = $email;
		$this->street = $street;
		$this->city = $city;
		$this->state = $state;
		$this->zip = $zip;
		$this->phone = $phone;
		$this->birth_date = $birth_date;
		$this->sex = $sex;
		$this->date_entered = $date_entered;
		$this->lunch_cost = $lunch_cost;
		$this->student_id = $student_id;
	
	}

}

?>

mysqli_connect.php

<?php
// Opens a connection to the database
// Since it is a php file it won't open in a browser 
// It should be saved outside of the main web documents folder
// and imported when needed

/*
Command that gives the database user the least amount of power
as is needed.
GRANT INSERT, SELECT, DELETE, UPDATE ON test3.* 
TO 'studentweb'@'localhost' 
IDENTIFIED BY 'turtledove';
SELECT : Select rows in tables
INSERT : Insert new rows into tables
UPDATE : Change data in rows
DELETE : Delete existing rows (Remove privilege if not required)
*/

// Defined as constants so that they can't be changed
DEFINE ('DB_USER', 'studentweb');
DEFINE ('DB_PASSWORD', 'turtledove');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'test3');

// $dbc will contain a resource link to the database
// @ keeps the error from showing in the browser

$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Could not connect to MySQL: ' .
mysqli_connect_error());
?>

json_code.php

<?php

// Tell whomever is receiving this data the content type
// Needs to be set on the first line
// header('Content-Type: application/json');

// Insert to the StudentDB class
require_once('StudentDB.php');

// json_decode decodes a JSON string into a format we can use
$json_data = json_decode('{"first_name" : "Dale"}');

// Displays the structure of data
// object(stdClass)#1 (1) { ["first_name"]=> string(4) "Dale" }
// 1 object that contains a key of first_name and a 4 character string Dale
var_dump($json_data);

// Create an object and then encode that data using JSON

class Address {

	public $street = "";
	public $city = "";
	public $state = "";
	
	function __construct($street, $city, $state){
	
		$this->street = $street;
		$this->city = $city;
		$this->state = $state;
	
	}

}

class Student {

	public $first_name = "";
	public $last_name = "";
	public $age = 0;
	public $enrolled = false;
	public $married = null;
	public $address;
	public $phone;
	
	function __construct($first_name, $last_name, $age, $enrolled,
		$married, $street, $city, $state, $ph_home, $ph_mobile){
	
		$this->first_name = $first_name;
		$this->last_name = $last_name;
		$this->age = $age;
		$this->enrolled = $enrolled;
		$this->married = $married;
		$this->address = new Address($street, $city, $state);
		$this->phone = array("home" => $ph_home,
							"mobile" => $ph_mobile);
	
	}

}

$dale_cooper = new Student("Dale", "Cooper", 35, true, null,
		"123 Main St", "Seattle", "WA", "4125551212", "4125552121");

echo "<br /><br />";

// Encodes the object using JSON and prints it
$dale_data = json_encode($dale_cooper);
echo $dale_data . "<br /><br />";

// Get a connection to the database
require_once('../../mysqli_connect.php');

// Check the connection
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

// Query retrieves the student data
$query = "SELECT * FROM students WHERE student_id IN (1,2)";

// Will hold all students retreived
$student_array = array();

if($result = $dbc->query($query)){

	while ($obj = $result->fetch_object()){
	
		printf("%s %s %s %s %s %s %s %s %s %s %s %s %s <br />",
		$obj->first_name, $obj->last_name, $obj->email,
		$obj->street, $obj->city, $obj->state, $obj->zip,
		$obj->phone, $obj->birth_date, $obj->sex, 
		$obj->date_entered, $obj->lunch_cost, $obj->student_id);
		
		$temp_student = new StudentDB($obj->first_name, 
		$obj->last_name, $obj->email, $obj->street,
		$obj->city, $obj->state, $obj->zip, $obj->phone, 
		$obj->birth_date, $obj->sex, $obj->date_entered, 
		$obj->lunch_cost, $obj->studentid);
		
		$student_array[] = $temp_student;
	
	}
	
	echo "<br /><br />";
	
	// Surround the student data
	echo '{"students":[';
	
	// Take data array created and convert into JSON
	$dale_data = json_encode($student_array[0]);
	echo $dale_data;
	
	// Seperate the results
	echo ',<br />';
	
	$dale_data = json_encode($student_array[1]);
	echo $dale_data . "<br />";
	
	// Close the JSON data
	echo ']}';

	// Close the database connection
	$result->close();
	$dbc->close();

}

?>

2 Responses to “Web Services Tutorial”

  1. UTKARSH SAGAR SRIVASTAVA says:

    nice but still waiting for your struts, spring & hibernate videos a lot
    and SUBTITLES aloing with it!!!

Leave a Reply

Your email address will not be published.

Google+