To output MySQL query results in JSON format, there are two preferred methods: the json_encode() function and the mysqli_fetch_all() function.
Using the json_encode() Function:
To apply the json_encode() function effectively, you need to first fetch the MySQL results into an array. This involves iterating through the result set and populating individual elements of an array using the mysqli_fetch_assoc() function. Subsequently, you can encode the entire array using json_encode() and output the result as a JSON string.
Utilizing the mysqli_fetch_all() Function:
Modern versions of PHP offer an alternative approach with the mysqli_fetch_all() function. It allows you to retrieve the entire result set into an array in a single operation. You can specify the array format using the MYSQLI_ASSOC constant to obtain an associative array where keys match the column names. Once the result set is in the array, you can apply json_encode() to generate the JSON output.
Code Examples:
The above is the detailed content of How Can I Encode MySQL Query Results as JSON Using PHP?. For more information, please follow other related articles on the PHP Chinese website!