Nukhba Arshad Nukhba Arshad - 3 months ago 6
JSON Question

array is returning repetitive Json data

It's returning something like this:

[
{
"0": "1",
"1": "Udon House",
"2": "food",
"3": "31.5076701",
"4": "74.3544522",
"5": "a trip to the landa.",
"6": "images/udonHouse.jpg",
"place_id": "1",
"place_name": "Udon House",
"category": "food",
"lat": "31.5076701",
"lon": "74.3544522",
"description": "a trip to the landa.",
"db_image": "images/udonHouse.jpg"
},
{
"0": "5",
"1": "Lahore Meuseum",
"2": "attractions",
"3": "31.5681556",
"4": "74.3061492",
"5": "want to discover histroy?",
"6": "images/badshahi.jpg",
"place_id": "5",
"place_name": "Lahore Meuseum",
"category": "attractions",
"lat": "31.5681556",
"lon": "74.3061492",
"description": "want to discover histroy?",
"db_image": "images/badshahi.jpg"
}
]


this is my php code:

<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="tourist"; // Database name
$con = mysqli_connect("$host", "$username", "$password","$db_name")or die("cannot connect");

if($con){

mysqli_set_charset($con ,'utf8');

$user_id = $_POST['user_id'];

$qry =

("SELECT p.*
FROM
places p INNER JOIN
favorites f ON p.place_id = f.place_id INNER JOIN
user u ON u.id = f.user_id
WHERE
u.id = $user_id");

$query=mysqli_query($con ,$qry);

if (!$query) {
$message = 'Invalid query: ' . mysqli_error() . "\n";
$message .= 'Whole query: ' . $qry;
die($message);
}

$return_arr = array();


$num_rows = mysqli_num_rows($query);
if ($num_rows > 0) {
while ($r = mysqli_fetch_array($query)) {


header('Content-Type: application/json');

array_push($return_arr,$r);
}
echo json_encode($return_arr);
}
}

?>


Why is it returning the rows two times in an object ?I only want the data with names not with the numberings what am I doing wrong here?
Any suggestions or alternate solutions please?

Answer

By default, the mysqli_fetch_array function, uses MYSQLI_BOTH as its "result type".

You need to set the 2nd parameter to MYSQLI_ASSOC to have it only return the key names.

while ($r = mysqli_fetch_array($query, MYSQLI_ASSOC)){
    array_push($return_arr,$r);
}

P.S. header('Content-Type: application/json'); only needs to be called once, so take it out of the while loop.

Comments