0

I'm going to tell you that I'm not expert when it comes to JSON or anything like that. I use it a few times in my projects, but recently I'm using it quite a bit.

Anyway, I'm creating an Android app that sends HTTP post requests to my website. The PHP file retrieves data from a database and converts an array into JSON. Usually, I'll send some data along with the POST request. But because I'm just practising, I'm just displaying all users received from the database to JSON.

However, it's return some weird keys that I don't really want. Example:

[
  {
    0: "1",
    1: "User1",
    2: "userPassword1",
    id: "1",
    username: "User1",
    password: "userPassword1"
  },
  {
    0: "2",
    1: "user2",
    2: "userPassword2",
    id: "2",
    username: "user2",
    password: "userPassword2"
  }
]

It's showing 0, 1, 2, and then the field names. I only want the field names.

My PHP file:

<?php
require 'connection.php';

$rArray = array();

$query = $con->query("SELECT * FROM users");

while ($row = $query->fetch_array()) {
    $rArray[] = $row;
}

echo json_encode($rArray);
?>

How can I fix this?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Jonathon
  • 1,491
  • 2
  • 13
  • 21

2 Answers2

3

Have you tried fetch_assoc?

Something like this:

<?php
require 'connection.php';

$rArray = array();

$query = $con->query("SELECT * FROM users");

while ($row = $query->fetch_assoc()) {
    $rArray[] = $row;
}

echo json_encode($rArray);
?>

For more lesson about fetch_assoc vs. fetch_array you may refer to this thread.

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
jerome
  • 695
  • 6
  • 20
0

Fixed:

$query->fetch_assoc()
Zoe
  • 27,060
  • 21
  • 118
  • 148
Jonathon
  • 1,491
  • 2
  • 13
  • 21