How to convert php database query array results into json format

PHPz
Release: 2023-03-28 15:06:01
Original
1432 people have browsed it

PHP is a widely used server-side scripting language used for web development and is often used to read data from databases. When we process data obtained from the database, we will most likely need to convert the data into JSON format and display it on the front-end page.

In PHP, the process of converting the query array to JSON format is very simple and can be achieved using PHP's built-in json_encode() function. The following is a sample code to convert the query array into JSON format:

<?php

// 连接数据库
$conn = mysqli_connect("localhost", "username", "password", "database");

// 定义查询语句
$sql = "SELECT * FROM users";

// 执行查询
$result = mysqli_query($conn, $sql);

// 将查询结果转换为数组
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row;
}

// 将数组转换为JSON字符串
$json = json_encode($rows);

// 输出JSON结果
echo $json;

?>
Copy after login

In the above code, we first connect to the database and then execute a SELECT statement to get the data from the database. We use the mysqli_fetch_assoc() function to convert each row in the result set into an associative array and store these arrays in an array called $rows. Finally, we use the json_encode() function to convert this array into a JSON-formatted string.

In this way, we can send this JSON string to the front end, process and display it through JavaScript.

To summarize, converting a query array to JSON format in PHP is very simple, just use the json_encode() function. Through this method, we can easily display the data obtained from the database on the front end and achieve a better user experience.

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

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template