How to parse json array from mysql? - php

I have this data but I can't parse it in the way I want. this is what I get:
{
"navigations": {
"title": "Facebook",
"link": "https://facebook.com",
"behavior": "EXTERNAL"
}
}
And what I expect to see:
{
"navigations": [
{
"title": "Facebook",
"url": "https://facebook.com",
"behavior": "INAPP"
},
{
"title": "Youtube",
"url": "https//youtube.com",
"behavior": "INAPP"
}
]
}
I have more results in my database but not more than 12 result so, i want to fetch data in the format i expect. I tried to do it using fetch_array but no success.
This is my PHP code:
$query_update_navigations = $db->prepare("SELECT title, link, behavior FROM navigation_tabs WHERE secret_api_key=?");
$query_update_navigations->bind_param("s", $_SESSION['secret_api_key']);
$query_update_navigations->execute();
$rows = array();
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'] = $rows1;
}
$store_path = '../apis/navigation_tabs/';
$file_name = $_SESSION['secret_api_key'] . '.json';
$sign_constants = json_encode($rows);
file_put_contents($store_path . $file_name, $sign_constants);
I searched for an answer but nothing solved my issue :(

You need to push the row onto the array, not overwrite it each time.
$rows = array('navigations' => []);
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'][] = $rows1;
}

Related

Generate JSON response on server with JsonArray and single fields

I am trying to build a JSON response from my server side, but it is not working as expected.
It is probably something simple but, I am not so good at PHP...
The basic expected response is a JSON with a single JsonArray and some other fields, for that, the relevant piece of code is shown here:
Sample of expected JSON response:
{
"pageNr": 2
"totalPages":28
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
Basic PHP code used to generate desired JSON (among sql query and other things):
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = ['pageNr' => $page];
$response = ['totalPages' => $totalPages];
$response = ['products' => $res2];
Response that this code is generating on Postman:
{
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
So, for some reason the JSON response is not accepting more fields pageNrand totalPages.
What is wrong here?.
Each assignment overwrites your array. You need to update it instead:
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = [];
$response['pageNr'] = $page;
$response['totalPages'] = $totalPages;
$response['products'] = $res2;
Try;
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response .= ['pageNr' => $page];
$response .= ['totalPages' => $totalPages];
$response .= ['products' => $res2];

empty the old value of $array[] in php

i am trying to remove the old value of an array i searched over the internet i just found the method unset() using this solution but my case it seems different some how here is my full code
<?php
header('Content-type: application/json; charset=utf-8');
$link = mysqli_connect("localhost","root","");
mysqli_query($link,"SET NAMES UTF8");
$db= mysqli_select_db($link,"Mirsa") or die("Cannot select Database.");
if (isset($_GET['Product_ID']) ){
$productId;
$Menu_ID =$_GET['Product_ID'];
$query = "SELECT
mirsaProductId,mirsaProductCode,mirsaProductDescription,
mirsaProductPcsInCartoon,mirsaProductWeight,mirsaProductVolume,
mirsaProductCodeBType,mirsaProductCodeCType,FK_mirsaCategoryId
from mirsaProduct WHERE FK_mirsaCategoryId='$Menu_ID'";
$result = mysqli_query($link,$query) or die(mysql_error($link));
$response["Products"] = array();
$products = array();
while ($row = mysqli_fetch_array($result)) {
$image[]=array()
$products["mirsaProductId"] = $row["mirsaProductId"];
$products["mirsaProductCode"] = $row["mirsaProductCode"];
$products["mirsaProductDescription"] = $row["mirsaProductDescription"];
$products["mirsaProductPcsInCartoon"] = $row["mirsaProductPcsInCartoon"];
$products["mirsaProductWeight"] = $row["mirsaProductWeight"];
$products["mirsaProductVolume"] = $row["mirsaProductVolume"];
$products["mirsaProductCodeBType"] = $row["mirsaProductCodeBType"];
$products["mirsaProductCodeCType"] = $row["mirsaProductCodeCType"];
$productId = $row["mirsaProductId"];
$query2 = "SELECT mirsaProductUrlImage FROM mirsaProduct,mirsaProductImages
WHERE FK_mirsaProductId = '$productId' GROUP BY mirsaProductUrlImage";
$result2=mysqli_query($link, $query2);
while ($row2 = mysqli_fetch_array($result2))
{
$image [] = $row2["mirsaProductUrlImage"];
$products["mirsaProductUrlImage"]=$image;
}
array_push($response["Products"], $products);
}
die(json_encode($response));
}
// echoing JSON response
else {
// no products found
$response["success"] = 0;
$response["message"] = "No Products";
die(json_encode($response));
}
?>
i am getting a response of this way
{
ProductId: "1",
ProductCode: "118.023",
ProductDescription: "NEM OVAL (Transparent)",
ProductPcsInCartoon: "10",
ProductWeight: "7.55 - 8.05(KG)",
ProductVolume: "0.104(m3)",
ProductCodeBType: "NA",
ProductCodeCType: "NA",
ProductUrlImage: [
"1.png",
"2.png"
]
},
{
ProductId: "2",
ProductCode: "118.024",
ProductDescription: "NEM OVAL (Opac)",
ProductPcsInCartoon: "10",
ProductWeight: "7.55 - 8.05(KG)",
ProductVolume: "7.55 - 8.05(KG)",
ProductCodeBType: "NA",
ProductCodeCType: "NA",
ProductUrlImage: [
"1.png",
"2.png"
]
the second JSON object is not containing these 2 url of image it takes the old value of the $image[] so i need to reinitialised or empty his value in a way i need your help guys you are always our support
I am going to take a stab. Since you never really initialize $image to be an array. Do you actually intend for:
$image[] = array()
to be:
$image = array();
That would cause the $image array to be reset each time through the first while loop.

Grouping JSON output according to specific mysql column

I have a mysql table (name:"messages") that has three columns as below:
messageID, fromUserID, content
I wish to have a json output using php script like following format; I need to seprate messages of each user (fromUserID column).
JSONOutput:
{
"newCount":"x",
"messages":
[
{
"fromUserID":"x",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"y",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
},
{
"fromUserID":"z",
"messagesArray":
[
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"},
{"messageID":"x","content":"xxx"}
]
}
]
}
My PHP Script:
$query = mysqli_query($con,"SELECT * FROM messages ORDER BY fromUserID");
$outputArray = array();
$outputArray['hasNew'] = mysqli_num_rows($query);
$messagesArray = array();
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray['MessagesArray'][] = $MSGArray;
}
$outputArray['Messages'][] = $messagesArray;
}
echo json_encode($outputArray);
But with above script I give a wrong result as below:
{
"hasNew":6,
"Messages":
[
{
"fromUserID":"24",
"MessagesArray":
[
{"messageID":"4","content":"test"},
{"messageID":"3","content":"test"},
{"messageID":"6","content":"test"},
{"messageID":"5","content":"test"},
{"messageID":"1","content":"test"},
{"messageID":"2","content":"test"}
]
}
]
}
My PHP Script just using last fromUserID value to grouping messages !!!
Please let me know where I'm wrong ...
Try it
if($query)
{
while($row = mysqli_fetch_assoc($query))
{
$MSGArray = array();
$messagesArray[$row['fromUserID']]['fromUserID'] = $row['fromUserID'];
$MSGArray['messageID'] = $row['messageID'];
$MSGArray['content'] = $row['content'];
$messagesArray[$row['fromUserID']]['MessagesArray'][] = $MSGArray;
}
foreach($messagesArray as $value) {
$outputArray['Messages'][] = $value;
}
}

Pass new php array key into json

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);

Why I can't return a proper json structure?

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.

Categories