I'm having trouble correctly display, in JSON, a result originated from two tables in my database.
The situation is this: I have orders in a table (A) and the products these orders in another table (B).
My code:
$sqlcode2 = mysql_query("Select a.numero as numOrc, a.nomeclie, a.valortotal, a.formapagto, a.emissao, b.codprod, b.qtdade, b.valorunit, b.tipopreco from orcamento a, prodorc b");
$jsonObj= array();
if($something == 'all')
{
while($result=mysql_fetch_object($sqlcode2))
{
$jsonObj[] = $result;
$teste= array('pedidos' => $jsonObj);
}
}
$final_res =json_encode($teste);
echo $final_res;
The JSON result is like this:
{
"pedidos": [
{
"numOrc": "1",
"nomeclie": "CONSUMIDOR",
"valortotal": "2.077,20",
"formapagto": "2",
"emissao": "2013-02-15 16:09:11",
"codprod": "4775",
"qtdade": "1",
"valorunit": "500,00",
"tipopreco": "B"
},
{
"numOrc": "2",
"nomeclie": "MARCELO AUGUSTO BOTURA",
"valortotal": "2.077,20",
"formapagto": "2",
"emissao": "2013-02-15 16:21:56",
"codprod": "4775",
"qtdade": "1",
"valorunit": "500,00",
"tipopreco": "B"
}
]
}
As you can see, the result is only one product in each order. I needed the result to be as below (Detalhes TAG):
{
"pedidos": [
{
"numOrc": "2",
"nomeclie": "MARCELO AUGUSTO BOTURA",
"valortotal": "2.077,20",
"formapagto": "2",
"emissao": "2013-02-15 16:21:56",
"Detalhes":
[
{
"codprod": "4775",
"qtdade": "1",
"valorunit": "500,00",
"tipopreco": "B"
},
{
"codprod": "5555",
"qtdade": "3",
"valorunit": "800,00",
"tipopreco": "A"
}
]
}
]
}
A quick example of what FirstOne suggests would look like this. See how the orders are selected first and then a 2nd query is used to gather additional information about that order.
$sqlcode2 = mysql_query("Select a.numero as numOrc, a.nomeclie, a.valortotal, a.formapagto, a.emissao from orcamento a");
$jsonObj= array();
if($something == 'all')
{
while($result=mysql_fetch_object($sqlcode2))
{
$sqlcode3 = mysql_query("Select b.codprod, b.qtdade, b.valorunit, b.tipopreco
FROM prodorc b WHERE b.numOrc = " . $result->numOrc);
$Detalhes = array();
while($orderResult=mysql_fetch_object($sqlcode3))
{
$Detalhes[] = $orderResult;
}
$result->Detalhes = $Detalhes;
$jsonObj[] = $result;
}
}
$teste= array('pedidos' => $jsonObj);
$final_res =json_encode($teste);
echo $final_res;
Related
I'm trying to create an array of objects with data coming from multiple tables, lets say there is table that hold patient data and there is table that hold diagnosis, and medicine for every patient that admitted to clinic, and i need to create an array of objects with the following output.
Screen shot
And i have to write the following code
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'new_nhif');
define('USERNAME', 'root');
define('PASSWORD', '');
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);
$sql = sprintf(
'SELECT
nh.MembershipNo,
nh.FullName,
nh.id as nhid,
lb.labrequest,
fd.diagnosis,
fd.DiseaseCode,
fd.CreatedBy as fdcrb,
dz.name
FROM nhif_data AS nh
LEFT JOIN laboratory AS lb ON lb.re_id = nh.id
LEFT JOIN foliodisease AS fd ON fd.re_id = nh.id
LEFT JOIN dawa_zilizotoka AS dz ON dz.re_id = nh.id
WHERE lb.re_id = nh.id
AND fd.re_id = nh.id
AND dz.re_id = nh.id
-- GROUP BY nh.MembershipNo
'
);
$obj = new stdClass;
$result = $connection->query($sql);
$vipimo = array();
$dawa = array();
$all = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// print_r(json_encode(['entities'=> $row],JSON_PRETTY_PRINT));
$obj->MembershipNo = $row['MembershipNo'];
$obj->FullName = $row['FullName'];
$id = $row['nhid'];
$sql2 = "SELECT * FROM foliodisease WHERE re_id ='$id'";
$result1 = $connection->query($sql2);
if ($result1->num_rows > 0) {
while($row2 = $result1->fetch_assoc()) {
$vipimo['diagnosis']= $row2['diagnosis'];
$vipimo['DiseaseCode']= $row2['DiseaseCode'];
$obj->FolioDiseases[] = $vipimo;
}
}
$sql3 = "SELECT * FROM dawa_zilizotoka WHERE re_id = $id";
$result3 = $connection->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$dawa['name']= $row3['name'];
$obj->FolioItems[] = $dawa;
}
}
$all[] = $obj;
}
print_r(json_encode(['entities'=> $all], JSON_PRETTY_PRINT));
}
?>
And it give out the following output
{
"entities": [
{
"MembershipNo": "602124502",
"FullName": "Omari M Simba",
"FolioDiseases": [
{
"diagnosis": "typhoid",
"DiseaseCode": "J54"
},
{
"diagnosis": "homa",
"DiseaseCode": "L54"
},
{
"diagnosis": "malaria",
"DiseaseCode": "b54"
}
],
"FolioItems": [
{
"name": " Fluticasone furoate\t"
},
{
"name": " Acyclovir Eye ointment\t"
},
{
"name": " Acyclovir\t"
},
{
"name": " Acyclovir\t"
}
]
},
{
"MembershipNo": "602124502",
"FullName": "Omari M Simba",
"FolioDiseases": [
{
"diagnosis": "typhoid",
"DiseaseCode": "J54"
},
{
"diagnosis": "homa",
"DiseaseCode": "L54"
},
{
"diagnosis": "malaria",
"DiseaseCode": "b54"
}
],
"FolioItems": [
{
"name": " Fluticasone furoate\t"
},
{
"name": " Acyclovir Eye ointment\t"
},
{
"name": " Acyclovir\t"
},
{
"name": " Acyclovir\t"
}
]
}
]
}
My tables are
nhif_data ----
nhif_data ,
laboratory ----
laboratory,
foliodisease ---
foliodisease ,
dawa_zilizotoka ----
dawa_zilizotoka
You don't need to create an object array for the desired output, 'json_encode()' basically objectifies anything, meaning, no matter what you store with 'json_encode()' function, 'json_decode()' will always return you an object/array of objects, and so on.
All you need to fetch the records off the database, make child nesting as required, append the record to an array, and just 'json_encode()'; with 'json_decode()', you will end up with an array of objects.
$JSONItem = []; // Initialize the array
while($Record = $Query->fetch_assoc()){ // Iterate through main recordset
...subsequent child query
// Iterate though child recordset
while($ChildRecord = $ChildQuery->fetch_assoc())$Record["Child"][] = $ChildRecord; // Append child node to main record
$JSONItem[] = $Record; // Append record for JSON conversion
}
var_dump(json_decode(json_encode($JSONItem))); // This should return an array of ojects
Following should allow a better understanding of the mechanism;
var_dump(json_decode(json_encode([
["ID" => 1, "Name" => "Apple", "Source" => ["Name" => "Amazon", "URL" => "http://Amazon.Com", ], ],
["ID" => 2, "Name" => "Banana", "Source" => ["Name" => "eBay", "URL" => "http://eBay.Com", ], ],
["ID" => 3, "Name" => "Carrot", "Source" => ["Name" => "GearBest", "URL" => "http://GearBest.Com", ], ],
])));
Or, with newer PHP version, I hope you can simply prepare/construct the array and objectify it with something like;
$JSON = (object) $JSONItem;
My database have three tables(category,catgory_details,questions), Now one category have many questions. I want to have a JSON response like this:
[
{
"category": "Accountant",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"Who is your idiol",
"What is ur name?"
]
}
},
{
"category": "Actuary",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"What is great?",
"What is ur name?"
]
}
}
]
but my code is returning only one row from questions tables like this:
[
{
"category": "Accountant",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"Who is your idiol"
]
}
},
{
"category": "Actuary",
"deatils": {
"video_link": "https://www.youtube.com/",
"form_link": "https://docs.google.com/forms/u/0/",
"questions": [
"What is great?"
]
}
}
]
Following is my php code:
<?php
header("Content-Type: application/json");
include('db.php');
$result = mysqli_query($conn,"SELECT * FROM categories ORDER BY id ASC");
$json_response = array();
while ($row = mysqli_fetch_array($result))
{
$row_array = array();
$row_array['category'] = $row['category'];
$id = $row['id'];
$detail_query = mysqli_query($conn,"SELECT * FROM category_details WHERE category_id=$id");
$question_query = mysqli_query($conn,"SELECT * FROM questions WHERE category_id=$id");
if($question_query->num_rows !== 0){
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
while ($question_fetch = mysqli_fetch_array($question_query))
{
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
'questions' => [$question_fetch['question'][1],$question_fetch['question'][2]],
);
}
}
}
else{
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
$myid = $detail_fetch['id'];
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
);
}
}
array_push($json_response, $row_array);
}
echo json_encode($json_response);
?>
What changes should I make in order to get my required JSON response?
Instead of building $row_array['deatils'] within the question_fetch loop, you should do it within the detail_fetch loop, and then populate just the questions sub-array within the question_fetch loop
while ($detail_fetch = mysqli_fetch_array($detail_query))
{
$row_array['deatils'] = array(
'video_link' => $detail_fetch['video_link'],
'form_link' => $detail_fetch['form_link'],
'questions' => array(),
);
while ($question_fetch = mysqli_fetch_array($question_query))
{
$row_array['deatils']['questions'][] = $question_fetch['question'];
}
}
Try to change :
'questions' => [$question_fetch['question'][1],$question_fetch['question'][2]],
to :
'questions' => $question_fetch['question'],
So you will have the full array of questions included in the response.
I have 2 table users(id,userid,fn,ln) and userdetails(id,userid,image,history,location,activity)
And i have written a query for first table to retrieve all the data and i want only history and location ,from second table.
i have retrieved the array and i am sending it to json_encode.
Now i want to retrieve the history,location and create a new key History and i want to add history location values to history key.
I need a query and json format for these.
For particular user i need to retrieve is own history
In both tables user id in common
Thanks in advance
$sth = mysql_query("SELECT * FROM users");$result = mysql_fetch_assoc($sth);
$i=0;
foreach($result as $data) {
$final_array[$i]['id'] = $data['id'];
$final_array[$i]['email'] = $data['email'];
$final_array[$i]['fname'] = $data['fname'];
$final_array[$i]['lname'] = $data['lname'];
$sth2 = mysql_query("SELECT id,places,act FROM user_dates WHERE user_id= '".$data['email']."'");
$result2 = mysql_fetch_assoc($sth2);
$j=0;
$history_array = array();
foreach($result2 as $data2) {
$history_array[$j] = array("id" => $data2['id'],"places" => $data2['places'], "act " => $data2['act ']);
$j++;
}
$final_array[$i]['history'] = $history_array;
$i++;
}
echo json_encode($final_array);
[
{
"id": "81",
"user_id": "2011",
"fn": "asd.",
"ln": "wer",
"History": [
{
"id": "350",
"history": "make1",
"Location": "qwe"
}
]
},
{
"id": "82",
"user_id": "2012",
"fn": "asd1",
"ln": "wer1",
"History": [
{
"id": "350",
"history": "make2",
"Location": "qwe2"
}
]
}
]
Userdetails table contains multiple records per user. So you need to do sub query and get the results and then form a mulch-dimensional array. Finally, encode as a JSON.
$sth = $dbh->prepare("SELECT * FROM users");
$sth->execute();
$result = $sth->fetchAll();
$i=0;
foreach($result as $data) {
$final_array[$i]['id'] = $data['id'];
$final_array[$i]['userid'] = $data['userid'];
$final_array[$i]['fn'] = $data['fn'];
$final_array[$i]['ln'] = $data['ln'];
$sth2 = $dbh->prepare("SELECT location,activity FROM userdetails WHERE userid= ".$data['id']."");
$sth2->execute();
$result2 = $sth2->fetchAll();
$j=0;
$history_array = array();
foreach($result2 as $data2) {
$history_array[$j] = array("location" => $data2['location'], "activity " => $data2['activity ']);
$j++;
}
$final_array[$i]['history'] = $history_array;
$i++;
}
echo json_encode($final_array);
I'm facing an issue regarding the json structure.
I have this:
function loadActiveTrackers($host_l, $username_l, $password_l, $dbName_l, $companyId_l){
$trackerId = 0;
$trackerName = "";
$trackerCreator = "";
$projectName = "";
$dataArray = [];
$trackerIdsArray = [];
$trackerNamesArray = [];
$trackerCreatorsArray = [];
$projectNamesArray = [];
$mysqli = new mysqli($host_l, $username_l, $password_l, $dbName_l);
$getActiveTrackersQuery = "SELECT tracker_id, tracker_name, tracker_creator, project_name FROM trackers WHERE "
. "company_id = ? AND is_active=1 ORDER BY tracker_creation_date";
if($stmt = $mysqli->prepare($getActiveTrackersQuery)){
$stmt->bind_param('s',$companyId_l);
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Bind the result to variables */
$stmt->bind_result($trackerId, $trackerName, $trackerCreator, $projectName);
while ($stmt->fetch()) {
$trackerIdsArray[] = $trackerId;
$trackerNamesArray[] = $trackerName;
$trackerCreatorsArray[] = $trackerCreator;
$projectNamesArray[] = $projectName;
}
$dataArray['ids'] = $trackerIdsArray;
$dataArray['names'] = $trackerNamesArray;
$dataArray['creators'] = $trackerCreatorsArray;
$dataArray['projectNames'] = $projectNamesArray;
// print_r($trackerIdsArray);
/* free results */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
echo json_encode($dataArray);
}
The above code works ok, but the structure is not valid.
What I mean is that it returns:
{
"ids": [1,2,3,4],
"names": ["1","2","test tracker","test1"],
"creators": ["1","test","test","test"],
"projectNames": ["1","1","test project","test"]
}
But it is supposed to return:
[
{"id": 1, "name": "1", "creator": "1", "projectName": "1"},
{"id": 2, "name": "2", "creator": "test", "projectName": "1"},
{"id": 3, "name": "test tracker", "creator": "test", "projectName": "test project"},
{"id": 4, "name": "test1", "creator": "test", "projectName": "test"}
]
Can you guide me trough it? I know that it's something really small, but I'm not able to spot it as a php newbie. In java the json library is pretty strong and with a single push() it can be achieved, but here I really can't find the way.
The current code creates arrays of the ids, names, creators, and project names.
So, instead of this code:
while ($stmt->fetch()) {
$trackerIdsArray[] = $trackerId;
$trackerNamesArray[] = $trackerName;
$trackerCreatorsArray[] = $trackerCreator;
$projectNamesArray[] = $projectName;
}
$dataArray['ids'] = $trackerIdsArray;
$dataArray['names'] = $trackerNamesArray;
$dataArray['creators'] = $trackerCreatorsArray;
$dataArray['projectNames'] = $projectNamesArray;
Change your structure to be like so:
while ($stmt->fetch()) {
$dataArray[] = array( 'id' => $trackerId,
'name' => $trackerName,
'creator' => $trackerCreator,
'projectName' => $projectName
);
}
echo json_encode($dataArray);
This will return the structure you desire, which is arrays of the ids, names, creators, and project names.
I have 3 different tables in my database called consoleConsole, consoleModel, and consoleGame. Then what I want to do is that each console will have a loop inside for its models, and each models will have another loop inside for its games like this:
[
{
"Console":"PlayStation",
"Information":[
{
"Model":"PlayStation 3",
"Title":[
{
"Game":"007 Legends",
"Publisher":"Electronic Arts"
},
{
"Game":"Ace Combat: Assault Horizon",
"Publisher":"Namco"
}
]
},
{
"Model":"PlayStation 2",
"Title":[
{
"Game":"007: Agent of Fire",
"Publisher":"Electronic Arts"
},
{
"Game":"Ace Combat 4: Shattered Skies",
"Publisher":"Namco"
}
]
},
{
"Model":"PlayStation 1",
"Title":[
{
"Game":"007 Racing",
"Publisher":"Electronic Arts"
},
{
"Game":"Ace Combat",
"Publisher":"Namco"
}
]
}
]
},
{
"Console":"Wii",
"Information":[
{
"Model":"Wii",
"Title":[
{
"Game":"007: Quantum of Solace",
"Publisher":"Activision"
},
{
"Game":"AC/DC Live: Rock Band Track Rack",
"Publisher":"MTV Games"
}
]
}
]
},
{
"Console":"Xbox",
"Information":[
{
"Model":"Xbox",
"Title":[
{
"Game":"AFL",
"Publisher":"Acclaim"
},
{
"Game":"American Chopper",
"Publisher":"Activision"
}
]
},
{
"Model":"Xbox 360",
"Title":[
{
"Game":"AFL Live",
"Publisher":"Electronic Arts"
},
{
"Game":"Akai Katana Shin",
"Publisher":"Cave"
}
]
}
]
}
]
But sadly, I was not using my database with this one but instead I just wrote it straight in a php file.
EDIT
Anyways, moving on. I have modified my code and ended up like this.
<?PHP
$consoleQuery = "SELECT * ".
"FROM consoleConsole ".
"JOIN consoleModel ".
"ON consoleConsole.consoleId = consoleModel.consoleId ".
"JOIN consoleGame ".
"ON consoleModel.modelId = consoleGame.gameId";
$consoleResult = mysql_query($consoleQuery);
$consoleFields = array_fill_keys(array(
'consoleName',
), null);
$modelFields = array_fill_keys(array(
'modelName',
), null);
$console = array();
$rowConsole = array();
while ($rowConsole = mysql_fetch_assoc($consoleResult)) {
$consoleId = $rowConsole['consoleId'];
$modelId = $row['modelId'];
if (isset($console[$consoleId]['Information'])) {
$console[$consoleId]['Information'][] = array_intersect_key($rowConsole, $modelFields);
}
else {
$console[$consoleId] = array_intersect_key($rowConsole, $consoleFields);
$console[$consoleId]['Information'] = array(array_intersect_key($rowConsole, $modelFields));
}
}
$console = array_values($console);
echo json_encode($console);
?>
I was able to produce an output but it doesn't look like the output above.
[
{
"consoleName": "PlayStation",
"Information": [
{
"modelName": "PlayStation"
},
{
"modelName": "PlayStation 2"
},
{
"modelName": "PlayStation 3"
},
{
"modelName": "PlayStation 3"
}
]
},
{
"consoleName": "Wii",
"Information": [
{
"modelName": "Wii"
},
{
"modelName": "Wii"
}
]
},
{
"consoleName": "Xbox",
"Information": [
{
"modelName": "Xbox"
},
{
"modelName": "Xbox 360"
}
]
}
]
Their relations:
What my problem is right now, I can't add the Title of the each Game.
Ok so I have written up your solution. You have to be sure that the order by is included there because it assumes that you are ordering them with there items together. I also didnt know how your publisher was stored so I separated that out into a separate table (this will allow you to then get items by just there publisher as well), which is now 4 joins. Also on another note I have updated it to do inner joins as well. This way you will not get empty results for consoles that don't have any games assigned to them. If you want these you could simply change the joins so that it would give you those results as well. Let me know if this helps
//get all of the information
$query = '
SELECT c.consoleId,c.consoleName,m.modelId,m.modelName,g.gameId,g.gameName,p.publisherId,p.publisherName
FROM `consoleconsole` c
INNER JOIN `consolemodel` m ON c.consoleId=m.consoleId
INNER JOIN `consolegame` g ON m.modelId=g.modelId
INNER JOIN `consolepublisher` p ON g.publisherId = p.publisherId
ORDER BY c.consoleName, m.modelName, g.gameName
';
//get the results
$result = mysql_query($query);
//setup array to hold information
$consoles = array();
//setup holders for the different types so that we can filter out the data
$consoleId = 0;
$modelId = 0;
//setup to hold our current index
$consoleIndex = -1;
$modelIndex = -1;
//go through the rows
while($row = mysql_fetch_assoc($result)){
if($consoleId != $row['consoleId']){
$consoleIndex++;
$modelIndex = -1;
$consoleId = $row['consoleId'];
//add the console
$consoles[$consoleIndex]['console'] = $row['consoleName'];
//setup the information array
$consoles[$consoleIndex]['information'] = array();
}
if($modelId != $row['modelId']){
$modelIndex++;
$modelId = $row['modelId'];
//add the model to the console
$consoles[$consoleIndex]['information'][$modelIndex]['model'] = $row['modelName'];
//setup the title array
$consoles[$consoleIndex]['information'][$modelIndex]['title'] = array();
}
//add the game to the current console and model
$consoles[$consoleIndex]['information'][$modelIndex]['title'][] = array(
'game' => $row['gameName'],
'publisher' => $row['publisherName']
);
}
echo json_encode($consoles);
Since you are using php function to encode json , it will give you the json in its default format. what you have to do is create your own function using string manipulation to get desired result.