How to use the PHP json_encode() function with MySQL query results?
The json_encode function converts a PHP value to a JSON string. To use it with MySQL results, you first need to cast the results into a PHP array.
Iterate Through Rows:
$res = mysqli_query($conn, 'SELECT * FROM table_name'); $array = []; while ($row = mysqli_fetch_assoc($res)) { $array[] = $row; } echo json_encode($array);
This method iterates over each row of the result set and appends the row as an associative array to the $array. Finally, the json_encode() function is applied to the entire array.
Entire Results Object:
$res = mysqli_query($conn, 'SELECT * FROM table_name'); $json = json_encode(mysqli_fetch_all($res)); echo $json;
Modern PHP versions (>= 5.3) support the mysqli_fetch_all() function which directly retrieves all rows as an array. The MYSQLI_ASSOC flag ensures the array is associative. The json_encode() function can then be applied to the entire array.
The above is the detailed content of How to Encode MySQL Query Results as JSON in PHP?. For more information, please follow other related articles on the PHP Chinese website!