Trick Jarrett Trick Jarrett - 2 years ago 155
PHP Question

JSON encode MySQL results

How do I use the

function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?

Answer Source
$sth = mysqli_query("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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download