I have a question about JSON PHP Multi Values - php

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

Related

How to encode json with multiple rows?

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
]
}

How to json encode a single object as a json objects array using PHP

For two objects:
{"publications":[{"nom":"toto","id":"2029","userid":"22","publication":"bla bla bla","time":"2017-02-20 00:00:00","avatar":{}},{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}]}
For One object:
{"publications":{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}}
i want to have always a json array as a return no matter how the number of objects.
PHP Code:
$result = $conn->query($sql);
$json = new SimpleXMLElement('<xml/>');
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$mydata = $json->addChild('publications');
$mydata->addChild('nom',$row['nom']);
$mydata->addChild('id',$row['id']);
$mydata->addChild('userid',$row['userid']);
/*echo(utf8_encode($row['publication']));*/
$mydata->addChild('publication',utf8_encode($row['publication']));
$mydata->addChild('time',$row['time']);
$mydata->addChild('avatar',$row['avatar']);
}
echo( json_encode ($json));
} else {
echo "0";
}
Well you are not using XML for anything else but convert it to JSON, so there is no need for XML. Use array
$result = $conn->query($sql);
$json = ['publications' => []];
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$json['publications'][] = [
'nom' => $row['nom'],
'id' => $row['id'],
'userid' => $row['userid'],
'publication' => $row['publication'],
'time' => $row['time'],
'avatar' => $row['avatar']
];
}
echo json_encode($json);
}
else
{
echo "0";
}
It's a particluar behaviour of SimpleXML.
If you have one child in xml - you will have an object in json, if you have more than one child - you will get array of objects. So, I advise you to rewrite your code using simple arrays instead of xml-approach:
$result = $conn->query($sql);
$json = []; // just array
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// add new item
$json[] = $row;
// or more specifically
$json[] = [
'nom' => $row['nom'],
'id' => $row['id'],
// more fields that you need
];
}
}
echo json_encode(['publications' => $json]);

Display multiple data row and display json data

I need to display multiple data row and display json data. Here is my code:
<?php
$dinner_food_category=$_GET['DinnerFoodCategory'];
$conn = mysqli_connect("localhost","taig9_gen_user","GenAdmin1/Pass");
if($conn) {
$select_database = mysqli_select_db($conn,"taig9_genumy");
$select_query = "SELECT food_id,food_name,serving_type,serving_type_amount,singal_unit_weight FROM food_details WHERE category_id IN ('VEG00','VGB00','SUP00','CAK00')";
$result = mysqli_query($conn, $select_query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$foods_id=$row['food_id'];
$foods_name=$row['food_name'];
$foods_type=$row['serving_type'];
$foods_type_amount=$row['serving_type_amount'];
$singal_unit_weights=$row['singal_unit_weight'];
}
$data = array("FoodId" => $foods_id,"FoodNames" => $foods_name,"FoodType" => $foods_type,"FoodAmount" => $foods_type_amount,"SingalUnitWeight"=> $singal_unit_weights);
}
echo stripslashes(json_encode($data));
}
?>
On each iteration of while you food_ variables are overwritten, and after while loop is over - you have value for the last row only. To avoid this you should add variables to $data inside a while loop with [] notation:
while ($row = mysqli_fetch_assoc($result)) {
$data[] = array(
"FoodId" => $row['food_id'];
"FoodNames" => $row['food_name'];
"FoodType" => $row['serving_type'];
"FoodAmount" => $row['serving_type_amount'];
"SingalUnitWeight" => $row['singal_unit_weight'];
);
}
// using `stripslashes` is useless
echo json_encode($data);
if (mysqli_num_rows($result) > 0) {
$data = [];
foreach ($result as $row) {
$foods_id=$row['food_id'];
$foods_name=$row['food_name'];
$foods_type=$row['serving_type'];
$foods_type_amount=$row['serving_type_amount'];
$singal_unit_weights=$row['singal_unit_weight'];
$data[] = ["FoodId" => $foods_id,"FoodNames" => $foods_name,"FoodType" => $foods_type,"FoodAmount" => $foods_type_amount,"SingalUnitWeight"=> $singal_unit_weights];
}
echo stripslashes(json_encode($data));
}

Get specific JSON data from sql query using PHP

I would like to say thank you for reading this question.
And my question is. I have this php code with sql query:
mysql_connect($mysql_server, $mysql_login, $mysql_password);
mysql_select_db($mysql_database);
$req = "SELECT name, elements "
."FROM lwzax_zoo_item "
."WHERE application_id = '2' AND elements LIKE '%".$_REQUEST['term']."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = array('label' => $row['name'], 'desc' => $row['elements']);
}
$json = json_encode($results);
echo $json;
And output is:
[
{
"label":"0146T",
"desc":" {\n\t\"cec36dd6-ffde-494d-b25c-8e58bff84e22\": {\n\t\t\"0\": {\n\t\t\t\"value\": \"Ccta W\\/Wo Dye\"\n\t\t}\n\t}\n}"
},
{
"label":"64653",
"desc":" {\n\t\"cec36dd6-ffde-494d-b25c-8e58bff84e22\": {\n\t\t\"0\": {\n\t\t\t\"value\": \"Chemodenervation Eccrine Glands Oth Area Per Day\"\n\t\t}\n\t}\n}"
}
]
But I need only label data and value data...so it should look like:
[
{
"label":"0146T",
"desc":"Ccta W\\/Wo Dye"
},
{
"label":"64653",
"desc":"Chemodenervation Eccrine Glands Oth Area Per Day"
}
]
Could you please help me?
Thank you very much for help
UPDATE: Deleted $b = json_decode($row['desc'], true); as it wasn't used, just a junk from all my attempts to succeed.
You're decoding the JSON and assigning it to $b, but you're not doing anything with that variable. Use:
$results[] = array('label' => $row['name'],
'desc' => $b['cec36dd6-ffde-494d-b25c-8e58bff84e22'][0]['value']);
Also, you need to give a second argument to json_decode, so it will return an associative array rather than an object.
$b = json_decode($row['elements'], true);
OK, well, first things first, initialize your array OUTSIDE your loop.
while($row = mysql_fetch_array($query))
{
$b = json_decode($row['elements']);
$results[] = array('label' => $row['name'], 'desc' => $row['elements']);
}
Then you should probably do this:
$results = array();
while($row = mysql_fetch_array($query))
{
$b = json_decode($row['elements']);
array_push($results, array('label' => $row['name'], 'desc' => json_decode($row['elements'], true));
}
The at the end
$json = json_encode($results);
echo $json;
See if that helps.

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