Reputation: 2129
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?
Upvotes: 1
Views: 62
Reputation: 509
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.
Upvotes: 2
Reputation: 3449
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.
Upvotes: 0
Reputation:
For JSON you would proably want to do:
while ($event = mysqli_fetch_array($result, MYSQL_ASSOC)) {
Upvotes: 0
Reputation: 7005
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
Upvotes: 1