0

I'm trying to get an entire table from mysqli and return it JSON encoded like this:

$result = $db->query('select * from categories');

$categories = array();
while ($row = $result->fetch_object()) {
    // echo json_encode($row); // Returns the row in JSON.
    $categories[] = array('ID' => $row->ID, 'name' => $row->name);
}

echo count($categories); // Returns 28, the amount of categories on the DB
echo json_encode($categories); // returns ""                            

But when I apply json_encode on the entire array, it returns nothing.

jotik
  • 17,044
  • 13
  • 58
  • 123
troyz
  • 1,345
  • 2
  • 11
  • 19
  • 6
    Take a look at this question http://stackoverflow.com/questions/1972006/json-encode-is-returning-null – nu11p01n73R May 16 '16 at 08:22
  • 1
    plesae do a `print_r($categories)` and update your question with the output – Alex Andrei May 16 '16 at 08:23
  • Do you have special characters in name or id? – Daniel Dudas May 16 '16 at 08:23
  • 1
    @AlexAndrei or better `var_export($categories)` because of `false` and `""` values is not visible in print_r – Nikita U. May 16 '16 at 08:25
  • 1
    try use `json_last_error()` and `json_last_error_msg` to see if there any errors – Nikita U. May 16 '16 at 08:26
  • @troyz ***If $categories has a complex structure (perhaps with many layers of nesting),*** you may want to ***take advantage of*** the extra arguments accepted by the json_encode Function especially ***the 3rd parameter ($depth).*** – Poiz May 16 '16 at 08:43

0 Answers0