Balázs Vincze Balázs Vincze - 1 month ago 8
JSON Question

Fetch rows in MySQL and return 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!

Answer

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