JSON encode MySQL results

ghz 1years ago ⋅ 1221 views

Question

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?


Answer

$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](https://stackoverflow.com/questions/7318191/enable-json- encode-in-php)

Modern PHP versions support mysqli_fetch_all() function that will get your array in one go

$result = mysqli_query($conn, "SELECT ...");
$rows = mysqli_fetch_all($result); // list arrays with values only in rows
// or
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC); // assoc arrays in rows

print json_encode($rows);