1

I'm iOS developer and for finishing prototype I need simple php code which could return data from particular table as JSON. Here is a code I developed:

<?php
    $connection = mysqli_connect($db_host, $db_user, $db_pass, $db_database) or die(mysql_error());

    $query = "select * from Events" or die("Error in the consult.." . mysqli_error($connection));
    $result = $connection->query($query);
    $events = array();

    while ($event = $result->fetch_array(MYSQLI_ASSOC)) {       

        $events[] = $event; 
    }

    echo json_encode($events);

    $result->free();
    $connection->close();
?>

The problem is that it duplicates data fields. Here is a result I receive:

[
   {
      "0":"1",
      "id":"1",
      "1":"Some title",
      "title":"Some title"
   }
]

In database I have one record only.

How to solve the following problem?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Serge
  • 2,031
  • 3
  • 33
  • 56

4 Answers4

2

Use associative array, will definately work...!

while ($event = mysqli_fetch_assoc($result)) {

    $events[] = $event; 
}

And You used header('Content-Type: application/json'); - its good, but also try by removing it as well.

  • Thanks. It works well. Since I use object oriented style I updated code in next way: (see edited topic) – Serge May 02 '14 at 14:14
1

http://us2.php.net/mysqli_fetch_array

"Fetch a result row as an associative, a numeric array, or both"

resulttype parameter: This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.

It would appear you are using BOTH. Switch to ASSOC or NUM. ASSOC is usually easier.

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

Jessica
  • 7,075
  • 28
  • 39
0

For JSON you would proably want to do:

while ($event = mysqli_fetch_array($result, MYSQL_ASSOC)) {

0

you can see this OT then you can use mysqli_fetch_assoc to fix the error, since the one you are using right now returns also an array, that is why you are getting duplicated data.

Community
  • 1
  • 1
Jorge Y. C. Rodriguez
  • 3,394
  • 5
  • 38
  • 61