PHP invalid JSON encoding - php

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.

Related

php array to json sting conversion

Hi every one i am pretty new to programming and my worry is as follows.
I have the following php code where students' averages are calculated and the result filled in an asssociative array. This array should later on be converted to json format.
require_once("functions.inc"); // all my functions are here
$conn = mysqli_connect(DBHOST,DBUSER,DBPASS,DB); // connects to my database
if (!$conn) {
error_log("Cannot connect to MySQL: " .$mysqli->connect_error);
return false;
}
$query = "SELECT distinct exam.student_matricule from exam join student on exam.student_matricule=student.student_matricule where student.class_id=3"; //
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$average=student_average(3,$studentmatricule,1); // this function call calculates students' averages
$stud_averages[$studentmatricule]=$average; //associative array that has **$studentmatricule** as key and **$average** as value
}
foreach($stud_averages as $student => $av)
{
$data=array('student_matricule'=>"$student",'average'=>"$av");
print json_encode($data);
}
My worry now is, print json_encode($data) prints
{"student_matricule":"17A002NA","average":"12.52"}{"student_matricule":"17A001NA","average":"10.53"}{"student_matricule":"17A003NA","average":"12.69"}
But i want something like
[{"student_matricule":"17A002NA","average":"12.52"},{"student_matricule":"17A001NA","average":"10.53"},{"student_matricule":"17A003NA","average":"12.69"}]
Please what should i do?
Thanks in advance!
You're printing single dimensional Array inside loop so it is printing as a JSON
If you want it as a JSON array you need to store it in a multidimensional array like this
$data = [];
foreach($stud_averages as $student => $av)
{
$data[]=array('student_matricule'=>"$student",'average'=>"$av");
}
print json_encode($data); // It prints JSON Array
You are printing every array seperately in foreach loop. You need to add every loop data in a array that defined outside the loop. You can try like this :
$res = array();
foreach($stud_averages as $student => $av)
{
$data=array('student_matricule'=>"$student",'average'=>"$av");
array_push($res, $data);
}
print json_encode($res);
you can also try like this
$data = [];
$std = array();
foreach($stud_averages as $student => $av)
{
$std['student_matricule']= "$student";
$std['average'] ="$av";
}
array_push($data,$std);
print json_encode($data); // It prints JSON Array

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

Custom JSON array using PHP and MySQL

I use PHP to encode json data from my MySQL table, the output comes like this
[
{
"Copra_Crushed_MT": "2306.01851",
"Oil_Extracted_MT": "1454.9442"
},
{
"Copra_Crushed_MT": "1234",
"Oil_Extracted_MT": "5678"
},
{
"Copra_Crushed_MT": "1907",
"Oil_Extracted_MT": "4605"
}
]
But i want the structure to be this way, how should i proceed to get this
[
[2306.01851,1454.9442],
[1234,5678],
[1907,4605]
]
my PHP code used to encode JSON
private function productionhourlys(){
if($this->get_request_method() != "GET"){
$this->response('',406);
}
$query="SELECT distinct c.Copra_Crushed_MT, c.Oil_Extracted_MT FROM productionhourlys c order by c.productionhourlyNumber desc";
$r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);
if($r->num_rows > 0){
$result = array();
while($row = $r->fetch_assoc()){
$result[] = $row;
}
$this->response($this->json($result), 200); // send user details
}
$this->response('',204); // If no records "No Content" status
}
private function json($data){
if(is_array($data)){
return json_encode($data);
}
}
Put array_values around your row:
$result[] = array_values($row);
(array_values docs)
Alternatively (and probably the better way) - You can use mysqli_result::fetch_row instead of fetch_assoc
while($row = $r->fetch_row()) {
(fetch_row docs)
json_encode in php will automatically turn associative arrays into json object (the curly brace syntax). You can use array values to remove keys and then json_encode will turn the arrays into JSON arrays (the square bracket syntax).

PHP Array not being delivered

I have some data in a database column called "gcmregid".
I access this data by calling:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
while ($row = mysql_fetch_array($r)) {
$result = array(
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
Correct me if I'm wrong, but this should deliver an array, due to result = array?
I took this logic from here: Getting Resource id #3 Error in MySql
.Then I thaught using a loop would be helpful, such as:
$userCount = $db->getUserCount(); // counting said table
$registation_ids = array(); // again create array
for($i=0; $i < $userCount; $i++)
{
$gcmRegId = $db->getGCMRegID($selUsers[$i]);
$row = mysql_fetch_assoc($gcmRegId);
//Add RegIds retrieved from DB to $registration_ids
array_push($registation_ids, $row['gcmregid']); // this creates an array consisting of gcmregid s ?
}
It doesn't work either.
Any input would be really appreciated right now...
Thanks
I'm not sure what's going wrong, but if the problem is that it's returning a single item: that's because you keep making a new array with every iteration, discarding the old one. If you want to collect all the rows, make a new array outside of the loop and then add the results to it:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
$result = array();
while ($row = mysql_fetch_array($r)) {
$result[] = array (
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
You should consider working more on how you name your functions. If you are trying to get gcmregid, the method should not say getAllUsers. Anyway, did you try the following:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$row = mysql_fetch_array($query_result);
return $result[0]['gcmregid'];
}
OR if you are trying to get all gcmregid in one shot:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$i=0;
while ($row = mysql_fetch_array($query_result)){
$result[$i++] = $row['gcmregid'];
}
return $result;
}

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

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";
}

Categories