Home > Database > Mysql Tutorial > How to Efficiently Encode MySQL Query Results as JSON in PHP?

How to Efficiently Encode MySQL Query Results as JSON in PHP?

Susan Sarandon
Release: 2024-12-18 10:40:10
Original
958 people have browsed it

How to Efficiently Encode MySQL Query Results as JSON in PHP?

Json Encoding MySQL Result Sets

Query Execution and Retrieval

To retrieve data from a MySQL database and store it in a PHP variable, you can use mysqli_query():

$sth = mysqli_query($conn, "SELECT ...");
Copy after login

JSON Encoding of Results

To encode the query results in JSON format, you can use the json_encode() function. However, you need to iterate through the results and encode each row individually:

$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);
Copy after login

Requirements for JSON Encoding

Note that json_encode() requires PHP version 5.2 or higher and the "php-json" package. If not installed, PHP will attempt to automatically include it.

Alternative Approach with mysqli_fetch_all()

In modern PHP versions, you can use the mysqli_fetch_all() function to retrieve all the query results in an array at once:

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

Using mysqli_fetch_all() for JSON Encoding

The mysqli_fetch_all() function can simplify the JSON encoding process by creating the array of rows for you. Simply pass the results variable to json_encode(), and it will automatically convert the data into JSON format.

The above is the detailed content of How to Efficiently 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