Coverting Object to PHP from Database [Mysql] into JSON, Usable in client side JavaScript ~ Coding Savvy
FB Twitter Google
» »

Coverting Object to PHP from Database [Mysql] into JSON, Usable in client side JavaScript

Hello Hope you have been good,I will also like to use this opportunity to acknowledge that you can now request for tutorials through the Request Tutorial page .
Being a programmer that love to code in an object oriented patters, I can't help but make sure that my objects remain an object from the database to the server also to the client side.
Today we are going to work on transforming objects from Sever side (PHP,JAVA,C,.NET) to Client side (JavaScript), This will be fun because we are going to achieve this using The JavaScript Object Notation (JSON), JSON is well understood by many programming languages.
Coverting Object to PHP from Database [Mysql] into JSON usable in client side JavaScript

Download Source
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.--JSON.ORG
To help demonstrate this kind of situation we are going to use a player object from Sever side (PHP) to Client Browser (JavaScript). First of all let us create a demo database like below :
-- phpMyAdmin SQL Dump
-- version 3.4.5
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jul 17, 2015 at 06:40 PM
-- Server version: 5.5.16
-- PHP Version: 5.3.8

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";



/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;


--
-- Database: `teamdb`
--

-- --------------------------------------------------------

--
-- Table structure for table `players`
--

CREATE TABLE IF NOT EXISTS `players` (
`player_id` int(11) NOT NULL AUTO_INCREMENT,
`full_name` varchar(100) NOT NULL,
`age` int(11) NOT NULL,
`position` varchar(20) NOT NULL,
`height` varchar(30) NOT NULL,
`foot` varchar(30) NOT NULL,
`acceleration` int(11) NOT NULL,
`agility` int(11) NOT NULL,
PRIMARY KEY (`player_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `players`
--

INSERT INTO `players` (`player_id`, `full_name`, `age`, `position`, `height`, `foot`, `acceleration`, `agility`) VALUES
(1, 'C. Ronaldo dos Santos Aveiro', 29, 'LW', '185cm | 6\\''0\\"', 'Right', 91, 93),
(2, 'Carlos Tevez', 29, 'RW', '182cm', 'Both', 94, 90);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Now let us create a player object in php like below :
class player {
public $player_id;
public $name;
public $age;
public $position;
public $height;
public $foot;
public $acceleration;
public $agility;
public function __construct($player) {
if ( is_array($player) )
: $this->player_id = $player['player_id']; 
$this->name = $player['full_name']; 
$this->age =$player['age'];
$this->position =$player['position'];
$this->height =$player['height'];
$this->foot =$player['foot'];
$this->acceleration = $player['acceleration'];
$this->agility = $player['agility'];
else: throw new Exception("No Player data was supplied."); endif;


}

}


Below is the process.php file that will be responsible for converting the php object to JSON and send it to the client.
// Database connection variables
require_once('connect.php');
// Include the player object
require_once('player.php');
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query = "SELECT * FROM players";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) > 1) {
//create all players array
$all_players = array();
// Loop Through the players
while($row = mysqli_fetch_array($data)){
$player = new player($row);
//Get player object variables and push it into $all_players array
array_push($all_players, get_object_vars($player));

}
}

//decode to JSON
echo json_encode($all_players);
Below is the output of out process.php file.
JSON Output.
Now to create our client side index.html for decoding the out puted JSON from process.php on the server.
To retrieve the JSON we are going to use XMLHTTP request using the script below.
<script>
window.onload = function (){
getPlayers_XHR();

}

function displayPlayers(players){
//decode the JSON FROM THE SERVER
var plys = JSON.parse(players);
alert(plys.players.length);

}


function getPlayers_XHR() {
// change the URL to match the location where you
// put the process.php file
var url = "http://127.0.0.1/jt/process.php";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
displayPlayers(request.responseText);
}
};
request.send(null);
}
</script>

This is what our final output will look like
Final HTML Output

Try it yourself.
Download Source
Was this article helpful?
Thanks! Your feedback helps us improve tutorials.

You May Also Like...

No comments:

Post a Comment