Json wont response my array in php

59 views Asked by At

I am trying to fetch multiple rows from my database and then encode them with json so I can access them in my Android application. I've successfully encoded an object but I couldn't find a way to do the same with an array. My code looks like:

if ($tag == 'friends') {

    $id = $_POST['id'];

    $friends = $db->getMyFriends($id);
    if ($friends != false) {
        // friends found          
        $result[] = array();
            while($row = mysql_fetch_assoc($friends)){
                $response[ "error"] = FALSE;
                $result[] = array(
                $response["friends"]["unique_id"] = $row["unique_id"],
                $response["friends"]["name"] = $row["name"],
                $response["friends"]["email"] = $row["email"]);
            }

        echo json_encode($response);
    }

The code from getMyFriends($id) I have already tested and it works fine. It returns :

$result = mysql_fetch_array($result);
return $result;

When using a rest client passing the parameters: Tag: friends id: $id

this is the json response that I get: { "tag": "myfriends", "error": false } , but no actual database data.

If anyone knows what I'm doing wrong, I'd really appreciate it, I've been browsing the internet for hours now.

2

There are 2 answers

0
oscargilfc On BEST ANSWER

If getMyFriends already have a $result = mysql_fetch_array($result);you don't need to fetch again.

You could simply:

$friends = $db->getMyFriends($id);
echo json_encode($friends);

But that will only return one friend, if you want all remove $result = mysql_fetch_array($result); from getMyFriends and return the pure mysql_result, then do something like:

 $result = array();
 while($row = mysql_fetch_assoc($friends)){
    array_push($result,$row);
 }
 echo json_encode($result);
1
Ashok Neupaney On

I tried this and it worked.

if($tag=='friends'){ 
$id = $_REQUEST['id'];
$friends = $db->getMyFriends($id);
if ($friends != false) {
// friends found          
$result[] = array();
while($row = mysql_fetch_assoc($friends)){
    $response[ "error"] = FALSE;
    $result[] = array(
    $response["friends"]["unique_id"] = $row["id"],
    $response["friends"]["name"] = $row["name"],
    $response["friends"]["email"] = $row["email"]
    );
}

echo json_encode($result);
}
}