Home >Backend Development >PHP Problem >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);
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); }
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.
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);
Recommended 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!