0

When I use PHP to do a simple query on a MySQL database, the object being returned holds duplicate values.

This is the PHP code where I query the database:

$query = 'SELECT * FROM names';
$result = mysqli_query($connection, $query);

$data = array();
while ($row = mysqli_fetch_array($result)) {
    array_push($data, $row);
}

echo json_encode($data);

The returning JSON object (being outputted by the Chrome console through Javascript) is as follows:

[{"0": "1", "id": "1", "1": "Jeff", "name": "Jeff"},
 {"0": "2", "id": "2", "1": "Andrew", "name": "Andrew"}]

Each value is listed twice: once as its correct column name and once as its column name's index. Does anyone know why this is happening?

1
  • can you please print_r($row); inside your while? Commented Oct 12, 2015 at 18:46

1 Answer 1

4

mysqli_fetch_array() returns both a numerical and asssociative array of the resultset. You need to use mysql_fetch_assoc() to get just the associative array.

while ($row = mysqli_fetch_assoc($result)) {
    array_push($data, $row);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.