Mephasm Vortex
Mephasm Vortex

Reputation: 45

json_encode in PHP is not returning any results

I have a PHP script that is retrieving some data from my database, and I want to encode it in json for processing in my Android app. I want the results to be like this:

{
    "part": [
        {
            "partNo": "value",
            "partName": "value",
            "shortDesc": "value",
            "longDesc": "value",
            "image": "value"
        },
        {
            "partNo": "value",
            "partName": "value",
            "shortDesc": "value",
            "longDesc": "value",
            "image": "value"
        }
    ],
    "success": 1
}

I am using the following PHP script.

// array for JSON response
$response = array();

// execute query based on specified user input
$result = mysql_query($sql) or die(mysql_error());

// check to see if results were found
if (mysql_num_rows($result) > 0) {
    //create a part array in $response to hold the part details
    $response['part'] = array();
    while ($row = mysql_fetch_array($result)) {
        //create an array for the part details
        $part = array();
        $part['partNo'] = $row['partNo'];
        $part['partName'] = $row['partName'];
        $part['shortDesc'] = $row['shortDesc'];
        $part['longDesc'] = $row['longDesc'];
        $part['image'] = "data:image/jpeg;base64,".base64_encode($row['image']);

        // put the array results for a single part in $response
        array_push($response['part'], $part);
    }
    // add the code for success to $response
    $response['code'] = 1;

    // and send it in json
    echo(json_encode($response));
    //print_r($response);
    //print_r(json_encode($response));
} else {
        //no results found
        $response['code'] = 0;
        $response['message'] = "No part found!";
        echo json_encode($response);
}

?>

I am not getting any response with echo (json_encode($response)); or print_r(json_encode($response));. But when I do print_r($response);, I am getting a response!

Array ( [part] => Array ( [0] => Array ( [partNo] => value [partName] => value [shortDesc] => value [longDesc] => value [image] => data:image/jpeg;base64,/9j/4QAYRXhpZgAAS.../9k= ) ) [code] => 1 )

Can anyone shed some light on this? Why is it not working with json_encode?

Upvotes: 1

Views: 487

Answers (1)

Arlind Hajredinaj
Arlind Hajredinaj

Reputation: 8519

Just use to return the $response in json format:

header('Content-type: application/json');
echo json_encode($response);

Upvotes: 1

Related Questions