Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON encode MySQL results

Tags:

json

php

mysql

How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?

like image 780
Trick Jarrett Avatar asked Dec 20 '08 19:12

Trick Jarrett


3 Answers

$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.

like image 132
Paolo Bergantino Avatar answered Nov 02 '22 22:11

Paolo Bergantino


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);
like image 42
ddavtian Avatar answered Nov 02 '22 23:11

ddavtian


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.

like image 27
Hugh Bothwell Avatar answered Nov 02 '22 21:11

Hugh Bothwell