Home > Backend Development > PHP Problem > How to convert mysql data into json format in php

How to convert mysql data into json format in php

王林
Release: 2023-02-24 19:04:01
Original
3693 people have browsed it

How to convert mysql data into json format in php

1. Connect to the database

header("content-Type: text/html; charset=utf-8");//字符编码设置  $servername = "localhost";  
$username = "root";  
$password = "123456";  
$dbname = "mydb";   
// 创建连接  
$conn =new mysql($servername, $username, $password, $dbname);  
// 检测连接  
if ($conn->connect_error) {  
    die("Connection failed: " . $conn->connect_error);  
}  
 //执行查询语句
$sql = "SELECT * FROM power WHERE DATE='2014-1-1'";  
$result = $conn->query($sql);
Copy after login

2. After executing the query statement in php, if you want to get each row of data, you need to Use mysqli_fetch_array and store it in array form, as shown in the following code example:

$arr = array();  
while($row = mysqli_fetch_array($result)) {  
    $count=count($row);
    for($i=0;$i<$count;$i++){  
        unset($row[$i]);//删除冗余数据  
    }   
    array_push($arr,$row);   
}
Copy after login

3. Since the row data obtained using the mysqli_fetch_array method is stored in array form, in addition to fields and value key-value pairs, By default, there will also be 0, 1, 2... subscripts. These redundancies must be removed, so use the unset method.

How to convert mysql data into json format in php

4. The data obtained at this time can be used in the code, but if you want to convert the query result data in the form of an array into json Format, you need to use the json_encode method, such as the code example below:

echo json_encode($arr,JSON_UNESCAPED_UNICODE);
Copy after login
Recommended tutorial: PHP video tutorial

The above is the detailed content of How to convert mysql data into json format in php. 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