1

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);
}
jamieaguinaldo
  • 129
  • 1
  • 2
  • 13

3 Answers3

2

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

Amit Merchant
  • 1,045
  • 6
  • 21
0

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

milan kumar
  • 226
  • 2
  • 16
0

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));
}
Pankaj Makwana
  • 3,030
  • 6
  • 31
  • 47