This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 5 years ago.
I have a PHP script where it fetches all records from a table and encodes it to JSON. The table has a total of 246 records. echo count(); returns 246 as well.
The problem is, whenever I use json_encode, it doesn't display the values from the array at all, all I see is a blank page. But if I reduce the number of records to 13 instead of 246, it works and it displays the encoded JSON result. I have also tried to increase the memory_limit at my php.ini file to 4095M, but no avail.
$result = mysqli_query($con, "SELECT * FROM cities");
if (mysqli_num_rows($result) > 0) {
$response["cities"] = array();
$city = array();
while($row = mysqli_fetch_assoc($result)) {
$city[] = $row;
array_push($response["cities"], $city);
}
$response["success"] = 1;
echo json_encode($response);
}
Try below and you'll get to know what is happening exactly:
$json = json_encode($response);
if ($json)
echo $json;
else
echo json_last_error_msg();
json_last_error_msg() - Returns the error string of the last json_encode() or json_decode() call
Array "city" is expanding for each call and you are pushing the complete array on each iteration in loop .
Try :
while($row = mysqli_fetch_assoc($result)) {
array_push($response["cities"], $row);
}
It should work
Remove $response array push $row into $cities array. After pushing all city set the city and response in json_encode(); function like this echo json_encode(array("cities"=>$cities, "success"=>1));
if (mysqli_num_rows($result) > 0) {
$cities = array();
while($row = mysqli_fetch_assoc($result)) {
array_push($cities, $row);
}
echo json_encode(array("cities"=>$cities, "success"=>1));
}
Related
This question already has answers here:
mysqli query results to show all rows
(4 answers)
Sql array only showing first result
(4 answers)
Closed 5 years ago.
I have write these kind of codes multiple times and it always worked great but now that I am on a different system it shows only 1 result.
the query is simple
$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DATABASE = 'db_test';
$con = mysqli_connect($HOST,$USERNAME,$PASSWORD,$DATABASE);
$sql = "SELECT * FROM test ";
$res = mysqli_query($con,$sql);
$res_array = mysqli_fetch_assoc($res);
echo json_encode($res_array);
mysqli_free_result($res);
mysqli_close($con);
I wonder if there is any settings that I have to change before running the app
Seriously, it's all over the docs:
mysqli_fetch_assoc Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
Note "the fetched row" part.
You need to do put your gathering in a cycle
$rows = [];
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row
}
json_encode($rows);
This line $res_array = mysqli_fetch_assoc($res); will only fetch one record.
You need to loop over result-set object and get all data from that.So use while() loop like below
$res_array =[];
while($row = mysqli_fetch_assoc($res)){
$res_array[] = $row;
}
Reference:-
mysqli_fetch_assoc()
Replace this line
$res_array = mysqli_fetch_assoc($res);
with
while ($row = mysqli_fetch_assoc($res)) {
$res_array[] = $row;
}
This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
What I am trying to do is get the values of the $r variable (returns some vehicle id values) to display on the page. However, it returns the following error.
Recoverable fatal error: Object of class mysqli_result could not be
converted to string in
C:\xampp\htdocs\SAMADHI\system\module\reservation\controller\reservationcontroller.php
on line 166
The problem is on the echo $r statement. I tried echo '$r' but then it shows nothing even though it displays the the message 'vehicle available'.
if ($nor > 0) {
$r = $objs->searchVehicle($vhandover, $vreturn, $seatcap);
if ($r) {
$msg = "Vehicle available";
$status = 1;
echo $r;
} else {
$msg = "Something is not right!";
$status = 0;
}
}
What am I doing wrong here and how can I correct it?
Let me assume, your vehicle table have following column - id, name, type. When your query executes, $r holds an associative array with search result-
$r = [ ['id'=>1, 'name'=>"toyota", 'type'=> "regular"], ....]
This is not any String. So if you want to echo any of the column value you need to mention it like -
echo $r['name'];
But if your query returns multiple results then, you need to put the echo inside a foreach loop.
foreach($r as $row) {
echo $row['name'];
}
UPDATE
If the above code doesn't work for you then try the following-
while($row = $r->fetch_assoc()) {
echo $row['id'];
}
UPDATE: 2
You can use fetch_array($r) -
while ($row = fetch_array($r)) {
echo $row['name'];
}
Hope that clears your concept!
I have a mysql database of countries, 250 in total, which in want to give over to an Android app. I know i have to use php in between to parse the result into JSON. This is it:
<?php
require_once('connection.php');
$response = array();
$resultarray = array();
$result = mysqli_query($con, "SELECT * FROM countries");
if (!empty($result)) {
// check for empty result
while ($row=mysqli_fetch_assoc($result)) {
print $row;
$resultarray = mysqli_fetch_array($result);
$Laender = array();
$Countries[de] = $resultarray["de"];
$response["Countries"] = array();
array_push($response["Countries"], $Countries);
echo json_encode($response);
}
}
?>
I ran the script in my browser and it displays correctly, except that half the countries are missing. There are only 125 countries displayed. Where have they vanished to?
Both functions mysqli_fetch_assoc and mysqli_fetch_array do the same - they fetch next record.
So, in your while you fetch first record with mysqli_fetch_assoc and then immediately fetch second record with mysqli_fetch_array. So, the first record is lost. And this happens on every iteration, so half of your records are lost.
Get rid of mysqli_fetch_array call:
$response["Countries"] = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($response["Countries"], $row["de"]);
}
echo json_encode($response);
I'm trying to get, in result, one JSON string from a database of mine but the database returns multiple rows of data, that when JSON encoded, don't fit together with proper formatting.
My current PHP code
$conn = [omitted];
$sql = [omitted];
$result = $conn->query($sql); //this query has been proven to work
if ($result->num_rows > 0) {
$rows = [];
while($row = $result->fetch_assoc()) {
$row[] = array_merge($row,$rows);
}
echo json_encode($rows);
} else {
echo "0";
}
But this code echos the $rows array before it's been merged with the $row arrays.
Current Result:
[]
Wanted Result:
[{"id":"1","team_name":"[omitted]","has_finished":"0"},{"id":"2","team_name":"[omitted]","has_finished":"0"},{"id":"3","team_name":"[omitted]","has_finished":"0"},{"id":"4","team_name":"[omitted]","has_finished":"0"},{"id":"5","team_name":"[omitted]","has_finished":"0"},{"id":"6","team_name":"[omitted]","has_finished":"0"},{"id":"7","team_name":"[omitted]","has_finished":"0"}]
You are never assigning any data into your $rows array. To assign each row into the array you want this for your loop.
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
I have two different queries which I have to append in same array in form of JSON..
Here is my code from 1st query...
while($row = mysqli_fetch_array($res)) {
array_push($result,array('name'=>$row[0],'photo'=>$row[1],'rollno'=>$row[2],'id'=>$row[3]));
}
Here is my second query push similar as first one.. number of rows is always same as above query
array_push($result,array('status'=>'$status');
After that I'm encoding them like this
echo json_encode(array("result"=>$result));
Here is what I am getting
{"result":[{"name":"Abhishek Singh","photo":"http:\/\/onsitesupport.info\/diary\/photos\/student\/26.png","rollno":"1","id":"26"},
{"status":"status"}]
But I want to result like this
{"result":[{"name":"Abhishek Singh","photo":"http:\/\/onsitesupport.info\/diary\/photos\/student\/26.png","rollno":"1","id":"26","status":"status"}]
I mean status will merge into my every node... how can I achieve this..?
Try the below to add status field to each array:
while($row = mysqli_fetch_array($res)){
array_push($result,array('name'=>$row[0],'photo'=>$row[1],'rollno'=>$row[2],'id'=>$row[3]));
}
$res_row = 0;
while($row2 = mysqli_fetch_array($res2)){
$status = $row2[0]; // status value here
$result[$res_row]['status']=$status;
$res_row++;
}
echo json_encode(array("result"=>$result));
Try this please, using temporary arrays that are merged after all your queries are complete:
// Query 1
while($row = mysqli_fetch_array($res)){
$tmpResults[] = $row;
}
// Query 2
$tmpResult2 = array('status'=>'$status');
// Merge Everything
$final = array_merge($tmpResults, $tmpResult2);
// Encode
$json = json_encode($final, TRUE);
Good luck