0

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));      
7
  • 1
    Are you sure your getting data from database? Commented May 11, 2015 at 7:29
  • 3
    Add var_dump($unique_array); right before the echo(json_ , just in order to make sure that the while loop is running and populating that variable. Commented May 11, 2015 at 7:29
  • 3
    also stop using deprecated Mysql functionalities and switch to Mysqli or better PDO Commented May 11, 2015 at 7:32
  • json_encode returns true or false nothing will echo Commented May 11, 2015 at 7:35
  • @SunilPachlangia Wut? Commented May 11, 2015 at 7:36

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks alot! the error was "Malformed UTF-8 characters, possibly incorrectly encoded". Adding this line after setting the connection with database solved it: mysql_set_charset("utf8");
Glad to here it. It's usually not what you think is the problem at actually is the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.