JSON encode MySQL results JSON encode MySQL results json json

JSON encode MySQL results

$sth = mysqli_query($conn, "SELECT ...");$rows = array();while($r = mysqli_fetch_assoc($sth)) {    $rows[] = $r;}print json_encode($rows);

The function json_encode needs PHP >= 5.2 and the php-json package - as mentioned here

NOTE: mysql is deprecated as of PHP 5.5.0, use mysqli extension instead http://php.net/manual/en/migration55.deprecated.php.

Try this, this will create your object properly

 $result = mysql_query("SELECT ..."); $rows = array();   while($r = mysql_fetch_assoc($result)) {     $rows['object_name'][] = $r;   } print json_encode($rows);

http://www.php.net/mysql_query says "mysql_query() returns a resource".

http://www.php.net/json_encode says it can encode any value "except a resource".

You need to iterate through and collect the database results in an array, then json_encode the array.