pass variables not in database row through json array - php

I have a bit of code I would like to pass through my json array that is not contained in the database $row. So i tried to set a custom variable and that didn't work. Is there a way to do this so the below content gets sent through with the array?
Here is what I tried
PHP
if ($photo_numff == 1) {
$streamitem_uploadimage_count =" Uploaded new image";
} else if($photo_numff > 1) {
$streamitem_uploadimage_count =" Uploaded ".$photo_numff." new images";
} else {
}
JSON array
$rowcount = mysqli_num_rows($result);
$json = array(
'posts' => array(),
'count' => $rowcount
);
while ($row = mysqli_fetch_array($result)) {
$posts[] = array(
//Post information and ids
'streamitem_id' => $row['streamitem_id'], // post id
'streamitem_uploadimage_count' => $streamitem_uploadimage_count,
);
$rowcount++;
}
$json['posts'] = $posts;
echo json_encode($json);
I can then take this through my ajax "+response['streamitem_uploadimage_count']+"
I have also tried array_push($json['posts'], array( 'streamitem_uploadimage_count' => $streamitem_uploadimage_count, ) );but doesn't work

I have now got this working by adding
'streamitem_uploadimage_count' => $streamitem_uploadimage_count
within the $Json array also.

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

Change JSON format php

I have this php code that i need to change the JSON format i get the data from a mysql db:
// Retrieve data from database
$sql="SELECT nombre FROM deudores ORDER BY fecha ASC LIMIT 10";
$result=mysqli_query($con, $sql);
$emparray = array();
// Start looping rows in mysql database.
while($rows=mysqli_fetch_assoc($result)){
$emparray[] = $rows;
// close while loop
}
//print_r($emparray);
//echo json_encode($emparray);
$output = array(
'c2array' => true,
'size' => array(
0 => count($emparray),
1 => 1,
2 => 1
),
'data' => array()
);
$x = 0;
foreach ($emparray as $value) {
$output['data'][$x] = array();
$output['data'][$x][0] = array();
$output['data'][$x][0][0] = $value;
$x++;
}
echo json_encode($output);
That code print this JSON:
{"c2array":true,"size":[7,1,1],"data":[[[{"nombre":"test"}]],[[{"nombre":"Oscar"}]],[[{"nombre":"Oscar"}]],[[{"nombre":"test"}]],[[{"nombre":"test"}]],[[{"nombre":"oscar"}]],[[{"nombre":"Oscar"}]]]}
but i need the JSON to look like this:
{"c2array":true,"size":[7,1,1],"data":[[[test]],[[Oscar]],[[Oscar]],[[test]],[[test]],[[oscar]],[[Oscar]]]}
How can i achive this?
Thanks in advance!
Use mysql_fetch_row() instead of mysql_fetch_assoc.
while($rows=mysqli_fetch_row($result)){
$emparray[] = $rows;
// close while loop
}
And just set $emparray as value for $output['data']. No need extra work!
$output['data'] = $emparray;
This should make the output like this :
{"c2array":true,"size":[7,1,1],"data":[["test"],["Oscar"],["Oscar"],["test"],["test"],["oscar"],["Oscar"]]}

Add Additional Objects in JSON

I am currently using a JSON encoded array to display the title in my database for an auto-suggest feature.
It looks something like this:
<?php
require_once('./includes/config.php');
require_once('./includes/skins.php');
mysql_connect($conf['host'], $conf['user'], $conf['pass']);
mysql_select_db($conf['name']);
$query2012 = sprintf("SELECT * FROM imdb WHERE poster !='posters/noposter.jpg' ORDER BY RAND() DESC LIMIT %d;", 8);
$result = mysql_query($query2012);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['title'] = $row['title'];
$row_array['year'] = $row['year'];
$row_array['poster'] = $row['poster'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
This returns:
[{"title":"The Woman","year":"2011","poster":"posters\/tt1714208.jpg"},{"title":"DeadHeads","year":"2011","poster":"posters\/tt1273207.jpg"},{"title":"The Innkeepers","year":"2011","poster":"posters\/tt1594562.jpg"},{"title":"John Carter","year":"2012","poster":"posters\/tt0401729.jpg"},{"title":"American Reunion","year":"2012","poster":"posters\/tt1605630.jpg"},{"title":"The Avengers","year":"2012","poster":"posters\/tt0848228.jpg"},{"title":"Chronicle","year":"2012","poster":"posters\/tt1706593.jpg"},{"title":"Big Miracle","year":"2012","poster":"posters\/tt1430615.jpg"}]
First, how would I manually add an additional object to this output? For example, let's say I wanted to add: {"status":"ok","message":"Success","data":
{"status":"ok","message":"Success","data":[{"title":"The Woman","year":"2011","poster":"posters\/tt1714208.jpg"},{"title":"DeadHeads","year":"2011","poster":"posters\/tt1273207.jpg"},{"title":"The Innkeepers","year":"2011","poster":"posters\/tt1594562.jpg"},{"title":"John Carter","year":"2012","poster":"posters\/tt0401729.jpg"},{"title":"American Reunion","year":"2012","poster":"posters\/tt1605630.jpg"},{"title":"The Avengers","year":"2012","poster":"posters\/tt0848228.jpg"},{"title":"Chronicle","year":"2012","poster":"posters\/tt1706593.jpg"},{"title":"Big Miracle","year":"2012","poster":"posters\/tt1430615.jpg"}]}
and if mysql record not found show json output
{"status":"error","message":"No Reord found"}
how i can add this ?
You can add this to your $json_response array before encoding (json_encode() by modifying it structute:
$json_response = array(
'data' => $json_response,
'status' => 'ok',
'message' => 'Successs'
);
You can also modify appending data to your final result variable so while you define your $json_response array add subarray:
$json_response = array('data' => array());
and in while loop add index data:
array_push($json_response['data'], $row_array);
And after loop you can easily append your status and message by:
$json_response['status'] = 'ok';
$json_response['message'] = 'Success';
To add error just check if the data array is empty. For first solution:
if (empty($json_response)) {
$json_response = array(
'status' => 'error',
'message' => 'No Reord found'
);
} else {
// here append success message
}
In second case just change a if condition to:
if (empty($json_response['data']))

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

json not giving back the proper result from database array

I am getting back two rows from my query, I tested it in phpadmin.
In firebug I can only see the data from one row.
What could be wrong that I don't see?
$data = mysql_fetch_assoc($r);
}
}
header('Content-type: application/json');
$output = array(
"check" => $check,
"users" => $data,
"testnumberoffrows" => $number
);
echo json_encode($output);
in the ajaxfunction
if( data.check ){
var user = data.users;
console.log(user);
thanks, Richard
mysql_fetch_assoc() fetches only one row. You need to loop until it returns FALSE, building up an output array.
Something like this:
while (($row = mysql_fetch_assoc($r)) !== FALSE) {
$data[] = $row;
}
Please try
$got=array();
while ($row = mysql_fetch_array($r)) {
array_push($got, $row);
}
mysql_free_result($r);
header('Content-type: application/json');
$output = array(
"check" => $check,
"users" => $data,
"testnumberoffrows" => $number
);
echo json_encode($output);

Categories