user3480127
user3480127

Reputation: 3

JSON Encoding of an array

I am trying to fetch results from the database into an array and then encoding that array into a json string but it does not echo any results. Can anybody figure out why?

$result=mysql_query($sql,$conn);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $unique_array[] = array('id'=>$row['id'], 'name'=>$row['name'],'province'=>$row['province']);
}

echo(json_encode($unique_array));      

Upvotes: 0

Views: 51

Answers (1)

Krycke
Krycke

Reputation: 3186

If the encoding fails, the function will return FALSE, and nothing will be echoed.

You can check errors with: json_last_error() and find the meaning here: http://php.net/manual/en/function.json-last-error.php

or for humans with this: json_last_error_msg();

$encoded_array = json_encode($unique_array);
if( json_last_error() ) {
    echo(json_last_error_msg());
    var_dump($unique_array);
}
else {
    echo($encoded_array);
}

Upvotes: 2

Related Questions