Home >Backend Development >PHP Problem >How to convert php database query array results into json format
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; ?>
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!