Thursday, November 2, 2017

Create JSON Object And Array Using PHP MySQL

If you want to transfer your data to another client (mobile or server) you have to create your own JSON. JSON or JavaScript Object Notation is a file that used to transfer data between clients/server or between two different programming languages.

JSON have two types, they are :

  • JSON type Object
  • JSON type Array
What the different of these type?

JSON Type Object


JSON Type Object has characteristic always using mark {}, please take a look at the following sample json :


{
"data":{
"nama_web":"androidbie.com",
"owner_web":"putuguna",
"hosting_web":"Host A"
}
}
view raw Object.json hosted with ❤ by GitHub

JSON type Array


We can call a json as an array is the JSON use the mark [] in its data. Why this json use the mark []? Because the data that will be send is more that one object. Please take a look at the following sample :

{
"data":[
{
"nama_web":"androidbie.com",
"owner_web":"Android Newbie",
"hosting_web":"hosting A"
},
{
"nama_web":"facebook dot com",
"owner_web":"Mark Z",
"hosting_web":"Hosting B"
}
]
}
view raw Array.json hosted with ❤ by GitHub

If you will transfer data more that one object, use the JSON type array. But, if you just transfer only one object, use JSON type Object as its format.

Create JSON Array using PHP and MySQL 


First, you have to preparing your data and has been saved in your MySQL database. In this project i will using data in my database and look like the follows :


Create your connection to connect the database and your project. Here is the code :

Connection.php


<?php
/**
* Created by PhpStorm.
* User: putuguna
* Date: 22/09/17
* Time: 21:07
*/
class Connection {
function getConnection(){
$host = "localhost"; // your host
$username = "root"; // your username
$password = ""; // your database password
$dbname = "mapsandroid"; // your database name
try{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}catch (Exception $e){
echo $e->getMessage();
}
}
}
view raw Connection.php hosted with ❤ by GitHub
After you connection has works well. Now create your JSON type Array

JSONArray.php



<?php
/**
* Created by PhpStorm.
* User: putuguna
* Date: 22/09/17
* Time: 23:26
*/
require_once("Connection.php");
class JsonDisplayMarker {
function getMarkers(){
//buat koneksinya
$connection = new Connection();
$conn = $connection->getConnection();
//create its response
$response = array();
$code = "code";
$message = "message";
try{
//display all data from mysql
$queryMarker = "SELECT * FROM location";
$getData = $conn->prepare($queryMarker);
$getData->execute();
$result = $getData->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $data){
array_push($response,
array(
'nama_lokasi'=>$data['namelocation'],
'latitude'=>$data['latitude'],
'longitude'=>$data['longitude'])
);
}
}catch (PDOException $e){
echo "Failed displaying data".$e->getMessage();
}
//Create a condition if the data success displayed or not
if($queryMarker){
echo json_encode(
array("data"=>$response,$code=>1,$message=>"Success")
);
}else{
echo json_encode(
array("data"=>$response,$code=>0,$message=>"Failed displaying data")
);
}
}
}
$location = new JsonDisplayMarker();
$location->getMarkers();
view raw JsonArray.php hosted with ❤ by GitHub
Running the above file, and you will show your data as list in json.

Create JSON type Object Using PHP and MySQL


Here is the file that you can use to create JSON type Object.

<?php
/**
* Created by PhpStorm.
* User: putuguna
* Date: 1/24/2017
* Time: 10:54 AM
*/
require_once("../db/Connection.php");
class InsertFood{
function startInsertFood(){
$connection = new Connection();
$conn = $connection->getConnection();
//array for json response
$response = array();
$foodName = $_POST['foodname'];
$foodQty = $_POST['foodqty'];
try{
if(isset($foodName) && isset($foodQty)){
$sqlInsert = "INSERT INTO food (foodname, foodqty) VALUES ('$foodName', '$foodQty')";
$conn->exec($sqlInsert);
}
}catch (PDOException $e){
echo "Error while inserting ".$e->getMessage();
}
//cek is the row was inserted or not
if($sqlInsert){
//success inserted
$response["success"] = 1;
$response["message"] = "Food successful inserted!";
echo json_encode($response);
}else{
//failed inserted
$response["success"] = 0;
$response["message"] = "Failed while insert data";
echo json_encode($response);
}
}
}
$insert = new InsertFood();
$insert->startInsertFood();
view raw JsonObject.php hosted with ❤ by GitHub
The above json will catch data type object from android and will send its data to database. I have been implemented it and has been post the project in this blog. Please open this : Tutorial insert data from android using retrofit to Server (PHP + MySQL).

That's all. Hope this article helps you. Thank you.

Related Posts


EmoticonEmoticon

:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:o
:>)
(o)
:p
:-?
(p)
:-s
8-)
:-t
:-b
b-(
(y)
x-)
(h)