0

I have the following PHP which gathers data from the DB and places each row into an array which it then places in a final array which is returned to the JavaScript:

$active = /*some SQL statement*/
$result = mysqli_query($GLOBALS['con'], $active);

$data = array();

while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)){

    $value = array( 
        "id"=>$row["quest"],
        "received"=>$row["received"]
    );

    array_push($data, $value);
}

return json_encode($data);

I know that the SQL statement is working and that $value has values in it, but the array returned to the JavaScript page is always an empty string instead of a JSON object.

If I place my return statement inside my while loop, then the data is returned:

while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)){

    $value = array( 
        "id"=>$row["quest"],
        "received"=>$row["received"]
    );

    array_push($data, $value);
    return json_encode($data);

}

But obviously this does not return the data as I want it, after the loop has completed.

And if I change my return statement to:

return json_encode($data[1]);

Then the data is also returned.

Please help me figure this one out.

ALR
  • 441
  • 2
  • 7
  • 19
  • Is this a function?? If not use `echo` and not `return` – RiggsFolly Aug 04 '16 at 11:34
  • Would have been useful to add that to the code you provided – RiggsFolly Aug 04 '16 at 11:35
  • return json_encode($data); this line should be outside the while loop – Surace Aug 04 '16 at 11:35
  • Mixing mysqli with mysql at `MYSQL_ASSOC` – Saty Aug 04 '16 at 11:36
  • Also use `MYSQLI_ASSOC` and not `MYSQL_ASSOC` I am pretty sure this should be producing some sort of error message are you looking at php error log. Add [error reporting](http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php/845025#845025) to the top of your file(s) _while testing_ right after your opening PHP tag for example ` – RiggsFolly Aug 04 '16 at 11:37
  • But even this doesn't work: `$row = $result->fetch_assoc()` – ALR Aug 04 '16 at 11:45
  • The error report returns nothing unfortunately – ALR Aug 04 '16 at 11:48

2 Answers2

0

Try with below changed code

$active = /*some SQL statement*/
$result = mysqli_query($GLOBALS['con'], $active);

$data = array();

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
    $value = array( 
        "id"=>$row["quest"],
        "received"=>$row["received"]
    );
   $data[]=$value; // this is trick 
}

return json_encode($data);
Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42
0

try this:

while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)){

$value = array( 
    "id"=>$row["quest"],
    "received"=>$row["received"]
);

array_push($data, $value);

}

return json_encode($data);
Tharif
  • 13,794
  • 9
  • 55
  • 77
Faridul Khan
  • 1,741
  • 1
  • 16
  • 27