Home > Backend Development > PHP Tutorial > How to Encode MySQL Query Results as JSON in PHP?

How to Encode MySQL Query Results as JSON in PHP?

Susan Sarandon
Release: 2024-12-25 15:16:11
Original
267 people have browsed it

How to Encode MySQL Query Results as JSON in PHP?

Encode MySQL Results to JSON

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);
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template