PHP: can't encode json with multiple rows [duplicate] - php

This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 1 year ago.
I've spent a couple of hours looking through several the similar answers before posting my problem.
I'm retrieving data from a table in my database, and I want to encode it into a JSON. However, the output of json_encode() is only valid when the table has one single row. If there is more than one row, the test at http://jsonlint.com/ returns an error.
This is my query:
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
$rows['data'] = $r;
//echo result as json
echo json_encode($rows);
}
That gets me the following JSON:
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
When I run the test at http://jsonlint.com/, it returns this error:
Parse error on line 29:
..."No comment" }}{ "data": {
---------------------^
Expecting 'EOF', '}', ',', ']'
However, if I only use this first half of the JSON...
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
... or if I only test the second half...
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
... the same test will return "Valid JSON".
What I want is to be able to output in one single [valid] JSON every row in the table.
Any suggestion will be very much appreciated.

The problem is you're spitting out separate JSON for each row, as opposed to doing it all at once.
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
// $rows[] = $r; has the same effect, without the superfluous data attribute
$rows[] = array('data' => $r);
}
// now all the rows have been fetched, it can be encoded
echo json_encode($rows);
The minor change I've made is to store each row of the database as a new value in the $rows array. This means that when it's done, your $rows array contains all of the rows from your query, and thus you can get the correct result once it's finished.
The problem with your solution is that you're echoing valid JSON for one row of the database, but json_encode() doesn't know about all the other rows, so you're getting a succession of individual JSON objects, as opposed to a single one containing an array.

You need to change your PHP code into something like this:
$result = mysql_query($query);
$rows = array();
//retrieve every record and put it into an array that we can later turn into JSON
while($r = mysql_fetch_assoc($result)){
$rows[]['data'] = $r;
}
//echo result as json
echo json_encode($rows);

I think you should do
$rows = array();
while($r = mysql_fetch_assoc($result)){
$rows[]['data'] = $r;
}
echo json_encode($rows);
echo should be placed outside of the loop.

I was trying the same in my PHP, so I came whit this...
$find = mysql_query("SELECT Id,nombre, appaterno, apmaterno, semestre, seccion, carrera FROM Alumno");
//check that records exist
if(mysql_num_rows($find)>0) {
$response= array();
$response["success"] = 1;
while($line = mysql_fetch_assoc($find)){}
$response[] = $line; //This worked for me
}
echo json_encode($response);
} else {
//Return error
$response["success"] = 0;
$response["error"] = 1;
$response["error_msg"] = "Alumno could not be found";
echo json_encode($response);
}
And, in my Android Class...
if (Integer.parseInt(json.getString("success")) == 1) {
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
if (!value.equals(1)) {
JSONObject jsonArray = (JSONObject) value;
int id = jsonArray.getInt("Id");
if (!db.ExisteAlumo(id)) {
Log.e("DB EXISTE:","INN");
Alumno a = new Alumno();
int carrera=0;
a.setId_alumno(id);
a.setNombre(jsonArray.getString("nombre"));
a.setAp_paterno(jsonArray.getString("appaterno"));
a.setAp_materno(jsonArray.getString("apmaterno"));
a.setSemestre(Integer.valueOf(jsonArray.getString("semestre")));
a.setSeccion(jsonArray.getString("seccion"));
if(jsonArray.getString("carrera").equals("C"))
carrera=1;
if(jsonArray.getString("carrera").equals("E"))
carrera=2;
if(jsonArray.getString("carrera").equals("M"))
carrera=3;
if(jsonArray.getString("carrera").equals("S"))
carrera=4;
a.setCarrera(carrera);
db.addAlumno(a);
}
}
} catch (JSONException e) {
// Something went wrong!
}
}

I must have spent 15 hours on this issue. Every variation discussed above was tried. Finally I was able to get the 'standard solution' working. The issue, very oddly, appears to be this:
When the interval is set beyond 14 hours, json appears to be unable to parse it. There must be a limit to JSON.
$sql= "SELECT cpu_name, used, timestamp FROM tbl_cpu_use WHERE timestamp>(NOW() - INTERVAL 14 HOUR) ORDER BY id";
$result=mysql_query($sql);
if ($result){
$i=0;
$return =[];
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$rows[] = $row;
}
echo json_encode($rows);
}else{
echo "ERROR";
}

Related

PHP invalid JSON encoding

I'm trying to GET a JSON format back when I POST a specific ID to my database. As I get more than one result I have multiple rows, which I want to get back. I do get different arrays back, but it is not a valid JSON Format. Instead of
[{...},{...},{...}]
it comes back as
{...}{...}{...}
Therefore the [...] are missing and the arrays are not separated by commas.
My code is down below. The function "getUserBookingsKl" is defined in a different php.
//get user bookings
public function getUserBookingsKl($id) {
//sql command
$sql = "SELECT * FROM `***` WHERE `hf_id`=$id AND `alloc_to`>DATE(NOW()) AND NOT `confirmation`=0000-00-00 ORDER BY `alloc_from`";
//assign result we got from $sql to $result var
$result = $this->conn->query($sql);
// at least one result
if ($result !=null && (mysqli_num_rows($result) >= 1 ))
{
while ($row = $result->fetch_array())
{
$returArray[] = $row;
}
}
return $returArray;
}
...
...
foreach($userdb as $dataset)
{
$returnArray["group"] = $dataset["kf_id"];
$returnArray["from"] = $dataset["alloc_from"];
$returnArray["to"] = $dataset["alloc_to"];
echo json_encode($returnArray);
# return;
}
// Close connection after registration
$access->disconnect();
It looks like you're sequentially emitting the values, not pushing into an array. You need to make an array, push into it, then call json_encode on the resulting structure:
$final = [ ];
foreach ($userdb as $dataset)
{
$returnArray = [ ];
$returnArray["group"] = $dataset["kf_id"];
$returnArray["from"] = $dataset["alloc_from"];
$returnArray["to"] = $dataset["alloc_to"];
$final[] = $returnArray;
}
echo json_encode($final);
Note that it's important here to not use the same variable inside the loop each time through or you're just pushing the same array in multiple times.

PHP While loop for Select Query

Can anyone explain me how to get the final value assigned to variable after completing executing while loop?
In my below code I wanted to echo the response out of while loop after fetching all the values from the rows.
Because if I put echo out of while loop it only shows 1st record.
while ($row = oci_fetch_array($array)) {
$response = $row['0']->load();
echo $response;
}
You will get the last rows value into the $response.
Cause: Every time the loop executes will assign value into the variable. But as you echo it you can see all the values as output.
So what you really need to do is storing the values in an array...
$response = array();
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load();
}
print_r($response);
If you need further information about this , just let me know.
Since you are doing variable assignment and echo inside while loop, it will not serve your purpose.
You have to do it like below:-
$response = array(); // create an array
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load(); // assign each value to array
}
echo "<pre/>";print_r($response);// print the array
Note:- this array will have all the values now. You can manipulate it in your desired way.Thanks
while ($row = oci_fetch_array($array)) {
$response = $row['0']->load();
}
echo $response;
Try this:
$response = [];
while ($row = oci_fetch_array($array)) {
$response[] = $row['0']->load();
}
var_dump($response);

how to add extra element to array with array_push in PHP?

I am developing in PHP/MS SQL for getting JSON Response.
Code which I wrote is:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$array_res[] = $result; // add result to array
array_push($array_res, array('unidad' => $uni)); // add extra element
$jsonObj = json_encode($array_res); // encode JSON
}
echo $jsonObj;
exit();
This is what I want in result:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null,"unidad":1}]
but the result shows me this:
[{"idperiodo":"37","idgrupo":"1963","idhorario":"12832","unidades":null},{"unidad":1}]
You're fetching an object. Add $uni to $result first and then add to $array_res:
while( $result = sqlsrv_fetch_object($sql_Gpo_Carr)) {
$result->unidad = $uni;
$array_res[] = $result;
}
Also, you probably want the json_encode() after the loop not in the loop:
echo json_encode($array_res);

Sort json output by id

I'm creating an app that parses json feeds into a listactivity. I've read that new items are added at the bottom of a listview and this is the case in my app. I'm trying to remedy this by sorting the output of my json by id in descending order. Don't know if this will fix my problem or I need to remedy it in my java code. Part one of my question is, will changing the order of output from the database change the order in which the feeds are displayed in the app? If so, I've tried to modify my php script by following the examples on http://php.net/manual/en/function.usort.php but the order doesn't change. Part two, What am I doing wrong in the following php script?
<?php
require("config.inc.php");
$query_params=null;
//initial query
$query = "Select * FROM feeds";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["feed"] = array();
foreach ($rows as $row) {
$post = array();
$post["id"] = $row["id"];
$post["name"] = $row["name"];
$post["status"] = $row["status"];
//update our repsonse JSON data
array_push($response["feed"], $post);
}
function cmp($a, $b)
{
if ($a->id == $b->id) {
return 0;
}
return ($a->id > $b->id) ? -1 : 1;
}
$a = array();
usort($a, "cmp");
// echoing JSON response
echo json_encode($response, JSON_NUMERIC_CHECK);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
Looks like you are calling usort on an empty array, instead of the data that you actually want to sort.
Instead of
$a = array();
usort($a, "cmp");
Try
$a = $response['feed'];
usort($a, "cmp");
$response['feed'] = $a;
Blackbelt is right that you can't technically sort a JSON array, at least one with sequential indexes (which results in no indexes at all). In practice, though, when you iterate through the resulting object on the client side, it will be in the order it was defined, so sorting it server-side should not raise any issues.

mysql_query doesn't show all query

I want to show all distinct id_did in cc_did_use
function getdidbycc($cccard_from_sipcard){
$result = mysql_query("SELECT id_did from cc_did_use where id_cc_card='$cccard_from_sipcard'");
if ($row = mysql_fetch_array($result))
{
$text = $row['id_did'];
}
return $text;
}
I have two id_cc_card="31" and one that value has id_dd="14" and another one = "13"
but result just show first one.
How I can show both of them?
and after that I have another function
function get_did ($p){
$result = mysql_query("SELECT did FROM cc_did WHERE id ='$p'");
while ($row = mysql_fetch_array($result))
{
echo $row['id_did'].'<br/>';
}
}
when I run getdidbycc function , it returns two value , 13 and 14 ,
How I can get did numbers from this two values?
You are fetching result and checking in an if condition which will execute only once.
if ($row = mysql_fetch_array($result))
{
$text = $row['id_did'];
}
You have to fetch the result until there is value in the resultant array. So try with while loop like,
while($row = mysql_fetch_array($result)) // while there are records
{
$text[] = $row['id_did']; // store the result in array $text
}
return $text; // return the array
First of all try to use mysqli or pdo instead of mysql otherwise you will face issues in updated version of php
As per your code $text value is gets over write due to loop so use an array something like this
if ($row = mysql_fetch_array($result)) {
$text[] = $row['id_did'];
}
return $text;
or you can just return complete data as return $row;
if ($row = mysql_fetch_array($result))
{
$text = $row['id_did'];
}
change the above line to this
while($row = mysql_fetch_array($result))
{
echo $row['id_did'].'<br/>';
}
Use a while loop like that : http://php.net/manual/en/function.mysql-fetch-array.php
Mysql fetch array returns the current element only
if ($row = mysql_fetch_array($result))
{
$text[] = $row['id_did'];
}
return $text; // returns both

Categories