How to fetch PHP database values in Json? - php

I have to create Matrix tree view in my project. So am plan to use json. My question is how to fetch PHP values in Json ?. I did static matrix tree but i want dynamic. Thank you for advance.
My code is following:
<?php
include('db.php');
$select = mysql_query("select * from table1");
while($row = mysql_fetch_array($select))
{
?>
{
"name": "A", // Here database values come $row['name'];
"children": [
{
"name": "B",
"children": [
{"name": "B-1"}
]
},
{
"name": "C",
"children": [
{"name": "C-1", "size": 1082},
{"name": "C-2", "size": 1681}
]
},
{
"name": "D",
"children": [
{
"name": "D-1",
"children": [
{"name": "D-1 1", "size": 1302},
{"name": "D-1 2", "size": 6703}
]
},
{"name": "D-2", "size": 16540}
]
}
]
}
<?php
}
?>

In this example Im using the mysqli driver. Do not use the mysql driver.
you just need to convert your output data into a json object.
Its possible to extract all the rows at once which is going to give you a marginally less overhead.
$data = mysqli_fetch_all($select); // returns everything in an associative array
$json_data = json_encode($data); // converts that array to json.
if you need specific keys, then manipulate your query to rename columns as necessary eg.
$query = "select name as firstname from ....";

You can just retrieve data from your database and store it in arrays like you normally would. Then call PHP's built in function json_encode() to transform your PHP array into json (assuming your PHP array is well formed (which should be the case if you get it out of a database)).
You could argue that this is slower because you're iterating over the data twice instead of once, but it shouldn't matter, the complexity remains the same.

Related

Need MySQL query results as array of JSONs, NOT array of arrays holding JSONs

I'm running MySQL 8 in a dev environment, learning as I go. I'm running a very simple PHP 7 RestAPI.
Here is how I'm executing a simply MySQL lookup:
$blockStmt = 'SELECT JSON_ARRAY(JSON_OBJECT("value", titleId, "title", titleDesc))
FROM titleTable ORDER BY titleDesc';
$preppedQuery = $db->query($blockStmt);
$blockResult = mysqli_fetch_all($preppedQuery);
print_r(json_encode($blockResult));
Here is how the result set is being returned by the print_r
[
[{"title": "Title 1", "value": "title1"}],
[{"title": "Title 2", "value": "title2"}],
[{"title": "Title 3", "value": "title3"}]
]
Here is how I WANT the results to be formatted:
[
{"title": "Title 1", "value": "title1"},
{"title": "Title 2", "value": "title2"},
{"title": "Title 3", "value": "title3"}
]
I've been working with the various JSON commands and can't seem to keep MySQL from encapsulating each result row as an array containing a single JSON, instead of just returning it as a JSON only.
Any tips? Thanks so much in advance!
Don't use the JSON functions, just return the columns that you want. mysqli_fetch_all() will then return associative arrays, and json_encode() will convert them to JSON.
$blockStmt = 'SELECT titleId AS value, titleDesc AS title
FROM titleTable ORDER BY titleDesc';
$preppedQuery = $db->query($blockStmt);
$blockResult = mysqli_fetch_all($preppedQuery, MYSQLI_ASSOC);
print_r(json_encode($blockResult));

How to get values of json arrays in php

I have a json array within {} braces and which are retrieved from $response5.
$json ='[
{
"Collectioncentre_Name": "Kattupakkam - Collection Centre 001",
"Session_ID": "20/04/2019/AM/CC001",
"Date": "2019-04-20T00:00:00",
"MilkSession": "AM",
"Farmer_ID": "VASAN/000000037",
"Row_ID": 332713,
"Milkman_Code": "310",
"Farmer_Name": "VASANTHA",
"Gender": "Female",
"Received_Quantity": 1.3
},
{
"Collectioncentre_Name": "Kattupakkam - Collection Centre 001",
"Session_ID": "20/04/2019/AM/CC001",
"Date": "2019-04-20T00:00:00",
"MilkSession": "AM",
"Farmer_ID": "CHIND/000000366",
"Row_ID": 332714,
"Milkman_Code": "449",
"Farmer_Name": "CHINDIRA E",
"Gender": "Female",
"Received_Quantity": 3
},
{
"Collectioncentre_Name": "Kattupakkam - Collection Centre 001",
"Session_ID": "20/04/2019/AM/CC001",
"Date": "2019-04-20T00:00:00",
"MilkSession": "AM",
"Farmer_ID": "PERUN/000000017",
"Row_ID": 332715,
"Milkman_Code": "492",
"Farmer_Name": "V.Perundevi",
"Gender": "Female",
"Received_Quantity": 3
}
]';
$data=json_decode($json,true);
$your_string="";
foreach($data as $key=>$v){
$your_string.=$data[$key]['Collectioncentre_Name'].",".$data[$key]
['Session_ID'].",".$data[$key]['Date'].",".$data[$key]
['MilkSession'].",".$data[$key]['Farmer_ID'].",".$data[$key]
['Row_ID'].",".$data[$key]['Milkman_Code'].",".$data[$key]
['Farmer_Name'].",".$data[$key]['Gender'].",".$data[$key]
['Received_Quantity']."\r\n";
}
$csvdata= trim($your_string, ",");
//$csvdata = $your_string;
echo $csvdata."\r\n";
Actually these json arrays are the output from $response5. And if I put the code like $json ='[$response5;] instead of adding whole arrays, am not getting the actual result which I got when I added array values. Did I miss anything or did I need to add more code?
To put the various comments together, when trying to put the whole JSON together from the original data, instead of...
$json ='[$response5;]
to make it a valid JSON array you need to use...
$json ="[$response5]";
Then to output each row of data plus headings (using implode rather than long winded adding each field together), you can use...
$data=json_decode($json,true);
$your_string=implode(",",array_keys($data[0])).PHP_EOL;
foreach($data as $key=>$v){
$your_string.=implode(",",$v).PHP_EOL;
}
echo $your_string."\r\n";

Excluding numbered-index elements of PDO::fetchAll()

$allrows = $pdo->fetchAll(); // select * from ....
I want to transform this $allrows into JSON by doing :
echo (json_encode($allrowl,JSON_PRETTY_PRINT));
My problem is that this fetchAll will not only extracting data as associate array but also indexed array for each element, hence repeating elements.
[
{
"org_id": "1",
"0": "1",
"category": "A",
"1": "A",
},
{
"org_id": "2",
"0": "2",
"category": "A",
"1": "A",
}
]
Thank you.
That's becuase the default fetch mode is FETCH_BOTH. CHange your mode to FETCH_ASSOC and you'll only get the non-numeric keys.
Assuming $pdo is a PDOStatement, set it like this prior to the fetch.
$pdo->setFetchMode(PDO::FETCH_ASSOC);
You can also set it in the fetch statement:
$pdo->fetchAll(PDO::FETCH_ASSOC);
Use PDO::FETCH_ASSOC to get only the associated arrays:
$allrows = $pdo->fetchAll(PDO::FETCH_ASSOC);

How to extract the JSON encoded POST parameters in PHP

I have passed JSON encoded parameters by POST which we have captured and decoded in another PHP file. I have used the following code to do that.
$entityBody = file_get_contents('php://input');
$entityBody = json_decode($entityBody, true);
I have passed the JSON encoded parameters as follows:
{
"id": "5",
"name": "abcd",
"imei": "1234"
}
Here my code works perfectly fine. However, I want to get all the parameters into a single object so that we can store them efficiently because otherwise there will be too many ifs and elses to get each parameter. So I have encoded the parameters as follows:
device = {
"id": "5",
"name": "abcd",
"imei": "1234"
}
But it is not working. Being new to JSON and PHP I do not know how to handle such cases. How can I achieve this?
use json_decode($_POST['device'], true) since your actually passing a parameter called 'device' to the php file.
You should pass json objects as follow:
{"device" : {
"id": "5",
"name": "abcd",
"imei": "1234"
}}
or if you have an array of devices
{"device" : [{
"id": "5",
"name": "abcd",
"imei": "1234"}
]}

Accessing data from a json structure

I am loading in a JSON feed from Facebook (snippet below).
{
"data": [
{
"id": "115972604762",
"from": {
"name": "Title Here",
"category": "Musicians",
"id": "20274769762"
},
"name": "It was an amazing gig!!",
"picture": "http://photos-h.ak.fbcdn.net/hphotos-ak-snc1/hs196.snc1/6616_115972604762_20274769762_2185148_6347071_s.jpg",
"source": "http://sphotos.ak.fbcdn.net/hphotos-ak-snc1/hs196.snc1/6616_115972604762_20274769762_2185148_6347071_n.jpg",
"height": 453,
"width": 604,
"images": [
{
I am loading it in using $data['pics'] = json_decode(file_get_contents('https://graph.facebook.com/'. $id .'/photos'));
How would I go about echo'ing out the from->name value to get the 'Title Here' value?
I think it should just be this:
$array = json_decode(file_get_contents('https://graph.facebook.com/'. $id .'/photos'));
echo $array["data"]["from"]["name"];
You can echo out the array using print_r($array) and then see the structure of your php array if it didn't work as expected.
First thing I would do is var_dump() the response, that would explain the exact structure of how PHP has decoded it. My guess is that $response['data']['from']['name'] might work.

Categories