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?
+4
A:
www.php.net/mysql_query says "mysql_query() returns a resource".
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.
Hugh Bothwell
2008-12-20 19:41:50
mysql_query does not return a result set. that's what mysql_fetch* is for.
Andy
2008-12-21 01:30:37
Um... yeah... that's what goes in the iterating, between mysql_query and json_encode. Good call, Watson.
Hugh Bothwell
2009-01-17 04:27:38
+8
A:
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Paolo Bergantino
2008-12-20 19:48:22
A:
The above will not work, in my experience, before you name the root-element in the array to something, I have not been able to access anything in the final json before that.
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows['root_name'] = $r;
}
print json_encode($rows);
That should do the trick!
Pär
Pär
2009-11-15 13:19:53