How to JSON encode MySQL results with PHP?

Spread the love

Sometimes, we want to JSON encode MySQL results with PHP.

In this article, we’ll look at how to JSON encode MySQL results with PHP.

How to JSON encode MySQL results with PHP?

To JSON encode MySQL results with PHP, we can call json_encode on the return rows.

For instance, we write

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

to call mysqli_query with the $conn connection object and the SQL select string.

Then we use a while loop to get the rows with mysqli_fetch_assoc and put the returned row $r into $rows.

And then we call json_encode with $rows to convert the array into a JSON string.

Conclusion

To JSON encode MySQL results with PHP, we can call json_encode on the return rows.

Leave a Reply

Your email address will not be published.