1

I am trying to echo a json-encoded array which consist of an array but i dont know it is not letting me print that thing. Here's my code:

<?php

include_once('confi.php');
header('Content-type: application/json');

if ($_SERVER['REQUEST_METHOD'] == "POST")
{
    $lastRecord = isset($_POST['lastRecordID']) ? 
                      mysql_real_escape_string($_POST['lastRecordID']) : "";

    $queryForTotalRec = mysql_query("SELECT customer_id FROM `WebServiceTesting`.`sapphire` ORDER BY customer_id DESC LIMIT 1");
    $total_rec = mysql_fetch_row($queryForTotalRec);

    if($total_rec){
        $queryForAllRecords = "SELECT * FROM `WebServiceTesting`.`sapphire` WHERE customer_ID BETWEEN %d AND %d";
       $get_all_recs = mysql_query(sprintf($queryForAllRecords, $lastRecord, $total_rec[0]));

        $json = array();
        while($row = mysql_fetch_assoc($get_all_recs)){

          $json[] = array("Status" => 1, "NewRecord" => $row);
        }

        print_r($json);
        echo json_encode($json);
   }else{
    $json = array("status" => 0, "Error_Message" => mysql_error());
          echo json_encode($json);
    }
}else{

    $json = array("status" => 0, "Error_Message" => "Request Method not correct");
      echo json_encode($json);

}
@mysql_close($conn);

Errors: Malformed JSON: Unexpected 'A' sometimes 'I'

When i am deleting the print_r line iam getting: No response received When i am printing the count of $json array iam getting a count of 153 but NO OTHER output.

Things i've tried:

i read in some solutions to similar problems that u need to use array_values() for e.g:

 echo json_encode(array_values($json));

same response: 'No response received'

I've also tried putting echo $json inside loop which I know that is conceptually wrong but still and got expected error 'Syntax error'

Also, i tried echoing through foreach no luck Syntax error but i can see output in raw but cannot validate the json.

Just for the info on print_r this is the response:

Array (
 [0] => Array ( 
     [Status] => 1 [NewRecord] => Array ( 
                   [customer_id] => 1241 
                   [firstName] => Katy 
                   [lastName] => Lest
                   [email] => klest@yahoo.com [phone] => 787012425
                                         )
               )
 [1] => Array ( 
      [Status] => 1 [NewRecord] => Array ( 
                    [customer_id] => 1242 
                    [firstName] => Hanah 
                    [lastName] => Morrisn 
                    [email] => road@gmail.com
                    [phone] => 144221275  )
              )
 [2] => Array (
       [Status] => 1 [NewRecord] => Array ( 
                    [customer_id] => 1243 
                    [firstName] => James 
                    [lastName] => McGrath
                    [email] => rosamcgrath@hotmail.com
                    [phone] => 79684312  )
             ) 
)

Just found a sort of answer to this i am still looking for a reason if anyone can help in that please. The number of Records i was pulling were 150+ so i just tried with 50 records at a time and it worked perfectly. Anyone know how can i actually allocate more memory to my array so that it can hold all the required data at once only ?

I have also tried by giving accurate index as well i thought that array goes out of memory but this even not working:

 $json = new SplFixedArray($difference);

Your assistance would be very much appreciated.

MQ.
  • 365
  • 6
  • 28
  • Try with `exit` after `echo`. – Sougata Bose Feb 29 '16 at 12:11
  • no luck mate, the same error 'no response received'. – MQ. Feb 29 '16 at 12:20
  • Note: The `mysql_*` functions are deprecated, they have been removed from PHP 7, your code will stop working when you upgrade to that version. You should not write new code using them, use [`mysqli_*` or PDO](http://php.net/manual/en/mysqlinfo.api.choosing.php) instead. – Gerald Schneider Feb 29 '16 at 13:05
  • @GeraldSchneider sure i'll, actually i am working on php after a long time even at that time i was beginner so just due to familiarity with syntax i am doing this. – MQ. Feb 29 '16 at 13:09

2 Answers2

4

Stab into the dark: some of your database rows contain non-ASCII characters (e.g. ü, é and such). Your database connection is set to latin1, so the data is not UTF-8 encoded. json_encode requires UTF-8 encoded data. If you fetch enough rows, there will be rows with such non-UTF-8 data in there, and json_encode fails. With few enough rows you happen to not hit those problematic rows.

Test this by outputting echo json_last_error_msg(); after json_encode.

Set your database connection to UTF-8. See here how to do so: UTF-8 all the way through

The reason why your browser complains about invalid JSON when you include a print_r is simple: because then PHP outputs a lot of garbage which isn't JSON, which the browser can't decode as JSON.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
  • its like very awkward situation right now, if i am echoing json encoded array with 50 entries the output is perfect but as soon as i try to exceed the limit of array it starts showing message 'no response received'. Which is currently beyond my understanding. – MQ. Mar 01 '16 at 09:22
  • And I tried to clarify what's happening in my answer...!? Is there anything more I can clarify? – deceze Mar 01 '16 at 09:23
  • O o o, i think you have pointed the exact. I have got the same error as well let me check. Great Great – MQ. Mar 01 '16 at 09:31
  • Thanks a ton for pointing me in the right direction @deceze !! – MQ. Mar 01 '16 at 09:42
-2

Simply Use json_decode() you will get the result you need..

   $array = json_decode($json, true);
   echo "<pre>"; print_r($array);

Array
(
    [0] => Array
        (
            [Status] => 1
            [NewRecord] => Array
                (
                    [fname] => xyz
                    [lname] => abc
                    [gender] => male
                )

        )

    [1] => Array
        (
            [Status] => 1
            [NewRecord] => Array
                (
                    [fname] => 123
                    [lname] => 456
                    [gender] => male
                )

        )

    [2] => Array
        (
            [Status] => 1
            [NewRecord] => Array
                (
                    [fname] => demo
                    [lname] => vvv
                    [gender] => female
                )

        )

)
Manjeet Barnala
  • 2,975
  • 1
  • 10
  • 20