在MySQL中获取行并返回JSON

I have the following SQL statement. "SELECT * FROM table"

Than I do: echo json_encode(mysqli_fetch_all($query));

Which gives me a json like this:

[
  [
    "32",
    "John",
    "12346",
    "email@gmail.com",
  ]
]

This is all fine, but it's missing the field names.

How could I get a JSON like this:

[
  [
    "id" : "32",
    "name" : "John",
    "phone" : "12346",
    "email" : "email@gmail.com",
  ]
]

Thanks!

it seems you get only numeric indizes. try fetching your data as associative array:

echo json_encode(mysqli_fetch_all($query, MYSQLI_ASSOC));

see also the manual

try echo json_encode(mysqli_fetch_all($query, MYSQLI_ASSOC));

Docu: http://php.net/manual/en/mysqli-result.fetch-assoc.php

PS: More sophisticated would be to use ORM helper like http://propelorm.org ... saves you a lot of headaches and helps to build maintainable code.