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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It works well. Since I use object oriented style I updated code in next way: (see edited topic)
1

https://www.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.

https://www.php.net/manual/en/mysqli-result.fetch-assoc.php

Comments

0

For JSON you would proably want to do:

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

Comments

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.

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.