Home  >  Article  >  Backend Development  >  How to query results in php and return json array

How to query results in php and return json array

PHPz
PHPzOriginal
2023-04-18 10:17:50843browse

In the process of web development, we often need to perform database operations and queries through PHP. For some data that needs to be displayed on the front end, we usually convert the query results into JSON format to facilitate parsing and display on the front end. In this article, we will introduce how to query database data through PHP and convert the results into a JSON array and return it.

1. Query database data

First, we need to connect to the database through PHP and execute query statements to obtain the data we need. The following is a simple sample code:

query('SELECT id, name, age FROM users');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

In the above code, we use PDO to connect to the database and execute a query statement to obtain the id, name and age of all users. The $data variable stores the query results.

2. Convert to JSON array

Next, we need to convert the query results into an array in JSON format. PHP provides a very convenient function json_encode() that can convert an array into a JSON format string. For the data we need to return, we only need to convert it into a JSON string, set the Content-Type header through the header() function, tell the browser that the returned data is JSON data, and finally convert the JSON string through the echo() function. Just output. The sample code is as follows:

query('SELECT id, name, age FROM users');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 转换成JSON格式并输出
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data);

?>

Through the above code, we have successfully converted the query results into JSON format and successfully returned it to the browser.

Summary:

In Web development, converting database query results into an array in JSON format is a very common operation. Through the json_encode() function provided by PHP, we can easily convert an array into a JSON format string, and tell the browser that we are returning JSON data by setting the Content-Type header. The above is the content introduced in this article, I hope it can be helpful to everyone.

The above is the detailed content of How to query results in php and return json array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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