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 array that we get from mysqli_fetch_assoc
.
For instance, we write
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while ($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
to make the query with mysqli_query
.
Then we run a while loop that calls mysqli_fetch_assoc
to fetch the results as associative arrays and put them into $rows
.
Then we call json_encode
with $rows
to return the rows as a JSON string.
Conclusion
To JSON encode MySQL results with PHP, we can call json_encode
on the array that we get from mysqli_fetch_assoc
.