Encoding MySQL Query Results as JSON Data
Retrieving and manipulating data from a MySQL database is a common task in web development. To present this data in a structured format suitable for communication over the internet, JSON (JavaScript Object Notation) encoding is often employed. The json_encode() function in PHP provides a straightforward way to convert MySQL query results into JSON strings.
Using json_encode() with MySQL Query Results
To encode MySQL query results as JSON data, follow these steps:
Alternative Method using mysqli_fetch_all()
In modern versions of PHP, you can use the mysqli_fetch_all() function to retrieve all rows from a query as an array in one operation. This simplifies the process by eliminating the need for iteration:
$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);
Note:
The above is the detailed content of How Can I Encode MySQL Query Results as JSON Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!