How to encode json with multiple rows? - php

Before I begin, I have looked through other examples and Q&A's on multiple platforms but none of them seem to solve my problem. I am trying to return multiple rows from MySQL via a json. However, I have been unable to. The code below shows my attempt.
I get my responses via Postman. The first while returns only the last entry in the database, and the do-while returns all entries but doesn't encode the json properly, as the json outputs syntax error but the html part shows all entries.
<?php
$dashboard_content_token = $_REQUEST["dashboard_content_token"];
$token = "g4";
require(cc_scripts/connect.php);
$sql = "SELECT * FROM `dashboard_content`";
$check = strcmp("$token", "$dashboard_content_token");
$statement = mysqli_query($con, $sql);
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
while ($rows = mysqli_fetch_assoc($statement)) {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
$result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
echo json_encode($result);
}
// do {
// $news_id = $rows['news_id'];
// $image_url = $rows['image_url'];
// $news_title = $rows['news_title'];
// $news_description = $rows['news_description'];
// $news_article = $rows['news_article'];
// $result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
// echo json_encode($result);
// } while ($rows = mysqli_fetch_assoc($statement));
mysqli_free_result($statement);
}
}
?>

This should work. You'll want to use the do...while statement otherwise the first result is skipped.
<?php
$dashboard_content_token = $_REQUEST["dashboard_content_token"];
$token = "g4";
require(cc_scripts/connect.php);
$sql = "SELECT * FROM `dashboard_content`";
$check = strcmp("$token", "$dashboard_content_token");
$statement = mysqli_query($con, $sql);
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
do {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
$result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
} while ($rows = mysqli_fetch_assoc($statement));
mysqli_free_result($statement);
echo json_encode($result);
}
}
?>
The key is to put all of you results into an array and then just do one json_encode(). When you call json_encode() multiple times, your API will return invalid json.

In your while loop,
$result['dashboard content: '] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
just over-writes the same "dashboard content" entry in the $result array every time you run the loop. This is why you only see the last entry.
Doing json_encode() within the loop makes no sense as well, because you'll just output multiple, disconnected individual JSON objects, which are not part of an array or coherent structure. This doesn't make for a valid JSON response.
It's not abundantly clear exactly what output structure you're hoping for, but this might give you either a solution, or at least a shove in the right direction:
$statement = mysqli_query($con, $sql);
$result = array("dashboard_content" => array()); //create an associative array with a property called "dashboard_content", which is an array. (json_encode will convert an associative array to a JSON object)
if (check) {
$rows = mysqli_fetch_assoc($statement);
if (!$rows) {
echo "No results!";
} else {
while ($rows = mysqli_fetch_assoc($statement)) {
$news_id = $rows['news_id'];
$image_url = $rows['image_url'];
$news_title = $rows['news_title'];
$news_description = $rows['news_description'];
$news_article = $rows['news_article'];
//append the current data to a new entry in the "dashboard_content" array
$result["dashboard_content"][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article);
}
}
//now, output the whole completed result to one single, coherent, valid JSON array.
echo json_encode($result);
You should end up with some JSON like this:
{
"dashboard_content": [
{
"news_id": 1,
"image_url": "abc",
"news_title": "xyz",
//...etc
},
{
"news_id": 2,
"image_url": "def",
"news_title": "pqr",
//...etc
},
//...etc
]
}

Related

How to repeat fuction in php?

Is it possible to repeat a function when it has finished. For Example: I have a function for export mysql to json file with a limit of 100 data. if it is successful create a json file with 100 data. Then it will repeat the same function to create json file 100 more data (no duplicate data) until the data runs out.
my code for generate json file :
$results = $db->SELECT()
->FROM( array( 'MM'=>'M_MEMBER'),
array( 'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS'
)
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT(100)
->QUERY()->FETCHALL();
if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
$counter = formatNbr($counterFile);
$data = array();
foreach ($results as $key=>$row) {
$data[$key] = $row;
$data[$key]['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$out = array_values($data);
$jsonAr = json_encode($out);
$json = substr($jsonAr, 1, -1);
$jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
$file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
$createJson = file_put_contents($file, $jsonData);
if($createJson){
echo "Create Json File Success In :".$file;
}else{
echo "Create Json Failed";
}
}
the code can only generate a json file once, how can it be repeated after generating a successful json file
note: I added a flag for each successful data generated json file
You can extract your codes to a function and use the function in the loop.
Example:
function exporter($limit = 100)
{
$results = $db->SELECT()
->FROM( array( 'MM'=>'M_MEMBER'),
array( 'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS'
)
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT($limit)
->QUERY()->FETCHALL();
if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
$counter = formatNbr($counterFile);
$data = array();
foreach ($results as $key=>$row) {
$data[$key] = $row;
$data[$key]['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$out = array_values($data);
$jsonAr = json_encode($out);
$json = substr($jsonAr, 1, -1);
$jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
$file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
$createJson = file_put_contents($file, $jsonData);
if($createJson) {
echo "Create Json File Success In :".$file;
} else {
echo "Create Json Failed";
}
}
$numberOfRows = 10000; # use the count query here
$limit = 100;
while($numberOfRows > 0) {
exporter($limit);
$numberOfRows -= $limit;
}
Also, you can call your function in your function recursively (https://www.w3schools.blog/php-recursive-functions)
Putting the existing code in a loop seems like the obvious answer here.
do {
$results = $db
->SELECT()
->FROM(
['MM'=>'M_MEMBER'],
[
'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS',
]
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT(100)
->QUERY()
->FETCHALL();
if (count($results) === 0) {
break;
}
$data = [];
foreach ($results as $row) {
$row['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$data[] = $row;
//
// this is UNSAFE and inefficient, use a prepared statement if possible
//
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$json = json_encode($out);
$filename = sprintf(
"%sdataMember_%s_%s.json",
$store_path_pos,
date("Y-m-d"),
formatNbr($counterFile)
);
if ($json && file_put_contents($filename, $json)) {
echo "Create Json File Success In $file";
} else {
echo "Create Json Failed";
}
} while (true);
I fixed a few inefficiencies in your code; I have no idea what DB library you're using but as a rule you should never inject variables into an SQL query. It's likely safe in this context, but if your library allows you should prepare the statement outside the loop and execute it inside the loop for better performance.

I have a question about JSON PHP Multi Values

I want to select the database more values (I already did) and be converted to JSON
I tried all
php
$a = $_GET['name'];
header('Content-Type: application/json');
echo '{"results":[';
$selectSearch = "SELECT * from `users` WHERE `name` LIKE '".$a["term"]."%'";
$rezultatul = $db->query($selectSearch);
if ($rezultatul->num_rows > 0) {
while($row = $rezultatul->fetch_assoc()) {
$name = $row["name"];
$arr = array('id' => $row["id"], 'text' => $row["name"], 'level' => $row["Level"]);
echo json_encode($arr);
}
}
echo ']}';
And he looks like this:
{"results":[{"id":"1","text":"Pompiliu","level":"7"}
{"id":"11","text":"Pompiliu1","level":"100"}]}
But between the two must be like that
{"id":"1","text":"Pompiliu","level":"7"},
{"id":"11","text":"Pompiliu1","level":"100"}
And when there will be 3 results
{"id":"1","text":"Pompiliu","level":"7"},
{"id":"11","text":"Pompiliu1","level":"100"},
{"id":"12","text":"Pompiliu2","level":"100"}
Add to the array with [] and then json_encode.
Don't try and build json strings on your own.
if ($rezultatul->num_rows > 0) {
while($row = $rezultatul->fetch_assoc()) {
$name = $row["name"];
$arr[] = array('id' => $row["id"], 'text' => $row["name"], 'level' => $row["Level"]);
}
}
echo json_encode(["results" => $arr]);

How to make a JSON output like this?

My desired output
{"rowcount":4
[{"provider_id":"1","provider_name":"Crecent Computers","sub_name":["Hardware","Software","Networks"]}],[{"provider_id":"4","provider_name":"Testing Co. LLC","sub_name":["Hardware","Software","Networks"]}],[{"provider_id":"41","provider_name":"Itiology","sub_name":["Hardware","Software","Networks","All IT Services"]}],[{"provider_id":"42","provider_name":"ITiology","sub_name":["Hardware","Software","Networks","All IT Services","Website Design "]}]}
My desired output end
My current JSON output
{"rowcount":4,"0":[{"provider_id":"1","provider_name":"Crecent Computers","sub_name":["Hardware","Software","Networks"]}],"1":[{"provider_id":"4","provider_name":"Testing Co. LLC","sub_name":["Hardware","Software","Networks"]}],"2":[{"provider_id":"41","provider_name":"Itiology","sub_name":["Hardware","Software","Networks","All IT Services"]}],"3":[{"provider_id":"42","provider_name":"ITiology","sub_name":["Hardware","Software","Networks","All IT Services","Website Design "]}]}
JSON Output end
PHP CODE
$result = mysqli_query($con, "select * from service_provider where servicecategory_id = '1'");
if ($counter = mysqli_query($con, "select * from service_provider where servicecategory_id = '1'"))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($counter);
// Free result set
mysqli_free_result($counter);
}
$data_points = array();
$subcatArray = array();
$data_points["rowcount"] = $rowcount;
while($row = mysqli_fetch_assoc($result))
{
$subcatresult = mysqli_query($con, "SELECT sub_name, price FROM sub_services WHERE provider_id = " . $row['provider_id']);
while($subcatrow = mysqli_fetch_assoc( $subcatresult))
{
$subcatArray[] = $subcatrow['sub_name'];
unset($subcatrow);
$subcatrow = array();
}
$data_points[][] = [
'provider_id' => $row['provider_id'],
'provider_name' => $row['provider_name'],
'sub_name' => $subcatArray
];
// array_push("totalRow",$data_points, $point);
}
echo json_encode($data_points);
PHP CODE END
you desired output json is an invalid json. you can check this json out valid or not in the http://jsonviewer.stack.hu. json or xml has it's own patterns.
So i found out that my desired output is invalid. Sorry I'm new to PHP.
I removed this line
$data_points["rowcount"] = $rowcount;
and made this
$data_points[][] = [
'provider_id' => $row['provider_id'],
'provider_name' => $row['provider_name'],
'sub_name' => $subcatArray
];
into this
$data_points["Rows"][] = [
'provider_id' => $row['provider_id'],
'provider_name' => $row['provider_name'],
'sub_name' => $subcatArray
];
I got the output pretty much close to what i need. Thanks guys!

Encode nested JSON array in php

I want to send nested JSON array.Which contain following format.
${"posts":[{
"abc":"123",
"xyz":"123",
"pro":[{
"name":"Brinjal",
"qty":"500 gms"
},
{
"name":"Brinjal",
"qty":"500 gms"
}]
}]
}
Here is my php code:
$rows = $stmt->fetchAll();
if ($rows) {
$order["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["order_id"] = $row["order_id"];
$post["order_totalamount"] = $row["order_totalamount"];
$post["address"] = $row["address"];
$post["pincode"] = $row["pincode"];
$post["delivery_timeslot"] = $row["delivery_timeslot"];
$post["order_date"] = $row["order_date"];
$query1= "query";
$rows1 = $stmt->fetchAll();
if ($rows1) {
foreach ($rows1 as $row1) {
$query2= "query";
$rows2 = $stmt->fetchAll();
$post["product"] = array();
if ($rows2) {
$products = array();
foreach ($rows2 as $row2) {
$products["product_name"]=$row2["product_name"];
$products["prod_qty"] = $row2["product_minquantity"];
}
array_push($post["product"],$products);
echo json_encode($products);
}
}
}
array_push($order["posts"], $post);
}
echo json_encode($order);
}
From above code I got result:
$ {"posts":
[{
"order_id":"18",
"order_totalamount":"40",
"address":"2, Chetan Society, Vadodara",
"pincode":"390023",
"delivery_timeslot":"Zone wise delivery",
"order_date":"2016-03-18 17:50:53",
"product":[{"product_name":"Brinjal","prod_qty":"500 gms"}]
}]
}
But my actual product array is:
${"product_name":"Banana","prod_qty":"1 Kg"}{"product_name":"Brinjal","prod_qty":"500 gms"}
Kindly help out. I am stuck on it. tried a lot but did not get success.
In
foreach ($rows2 as $row2) {
$products["product_name"]=$row2["product_name"];
$products["prod_qty"] = $row2["product_minquantity"];
}
You overwrite $products["product_name"]and $products["prod_qty"] with the values of the last $row2.
The line {"product_name":"Banana","prod_qty":"1 Kg"}{"product_name":"Brinjal","prod_qty":"500 gms"} actually consists of two echo's:
{"product_name":"Banana","prod_qty":"1 Kg"}
{"product_name":"Brinjal","prod_qty":"500 gms"}
But you don't see the difference. I suggest echoing a string in-between them or use something like var_dump() to see how many values you're echoing.
You should do something like:
for ($i = 0; $i < count($rows2); $i++) {
$products[$i]["product_name"]=$rows2[$i]["product_name"];
$products[$i]["prod_qty"] = $rows2[$i]["product_minquantity"];
}
This will result in: [{"product_name":"Banana","prod_qty":"1 Kg"},{"product_name":"Brinjal","prod_qty":"500 gms"}]
FYI $array[] = has the same rsults as array_push(), but had less overhead of calling array_push().
EDIT:
Below a complete example since it doesn't seem to workout for you:
//Demo $order
$order = array (
'posts' =>
array (
0 =>
array (
'order_id' => '18',
'order_totalamount' => '40',
'address' => '2, Chetan Society, Vadodara',
'pincode' => '390023',
'delivery_timeslot' => 'Zone wise delivery',
'order_date' => '2016-03-18 17:50:53',
),
),
);
//Demo $rows2
$rows2 = array(
array(
'product_name' => 'banana',
'product_minquantity' => '1 Kg'
),
array(
'product_name' => 'Brinjal',
'product_minquantity' => '500 gms'
)
);
$post['product'] = array();
if ($rows2) {
$products = array();
for ($i = 0; $i < count($rows2); $i++) {
$products[$i]['product_name'] = $rows2[$i]['product_name'];
$products[$i]['prod_qty'] = $rows2[$i]['product_minquantity'];
}
$post['product'] = $products;
echo json_encode($products); //[{"product_name":"banana","prod_qty":"1 Kg"},{"product_name":"Brinjal","prod_qty":"500 gms"}]
}
//$order['posts'][] = $post;
$order['posts'][0] = $order['posts'][0] + $post;
//In this example I only have 1 item in $order['posts'] so I know to add to key 0.
//In your case you need to know which key of $rows1 you need to do the adding.
//Change the foreach loop of $rows to a for loop as well so you can define your own keynames ($i).
echo '<br>==================================================================<br>';
echo json_encode($order);
/*
{
"posts":[
{
"order_id":"18",
"order_totalamount":"40",
"address":"2, Chetan Society, Vadodara",
"pincode":"390023",
"delivery_timeslot":"Zone wise delivery",
"order_date":"2016-03-18 17:50:53",
"product":[
{
"product_name":"banana",
"prod_qty":"1 Kg"
},
{
"product_name":"Brinjal",
"prod_qty":"500 gms"
}
]
}
]
}
*/

Pulling data from MySQL into json array

I'm trying to pull data from my database using json in php. I have a few elements I need to specific then to post them on a page.
I want to "fetch" the data from mysql and return it to a json_encode. How can I do this using the SELECT method. Some had used PDO methods and other have used mysql_assoc, which confuses me.
For instance,
I have rows of: 'id' , 'title' , 'start', 'backgroundColor'...etc. along with a default value for all of them. ($array[] = "someValue = default")
I want it to export like so:
array(
'id' => 1,
'title' => "someTitle",
'start' => "2012-04-16",
'backgroundColor' => "blue",
'someValue' = > "default",
...
), ....
));
If anyone could help me with this with the best detail, I'd be awesome!
If you wanted to do this with PDO then here is an example:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=DBNAME", $username, $password);
$sql = "SELECT `id`, `title`, `time`, `start`, `backgroundColor`
FROM my_table";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
$return = [];
foreach ($result as $row) {
$return[] = [
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start'].' '.$row['time'],
'backgroundColor' => $row['backgroundColor']
];
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
You don't "fetch to a json array".
You fetch your database results into a PHP array, then convert that php array, AFTER THE FETCHING IS COMPLETED, to a json string.
e.g.
$data = array();
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
echo json_encode($data);
You can get the result from mysql,then format it to json
$array = array();
while($row = mysqli_fetch_array($result))
{
array_push($array,$row);
}
$json_array = json_encode($array);
Please check for SELECT methods here
In general it would look like this
$data = array(); // result variable
$i=0
$query = "SELECT id,title,start,backgroundColor FROM my_table"; // query with SELECT
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){ // iterate over results
$data['item'][$i]['id'] = $row['id']; // rest similarly
...
...
$i++;
}
header('Content-type: application/json'); // display result JSON format
echo json_encode(array(
'success' => true,
'data' => $data // this is your data variable
));

Categories