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

How to query mysql in php and return json

藏色散人
藏色散人Original
2021-07-13 10:06:542876browse

php查询mysql并返回json的方法:首先创建一个PHP示例文件;然后通过mysqli_connect连接数据库;最后通过“decodeUnicode($json);”打印编码后的json字符串即可。

How to query mysql in php and return json

本文操作环境:Windows7系统、PHP7.1版,DELL G3电脑

php怎么查询mysql并返回json?

php读取MySQL数据并返回json数据

<?php
//设置编码格式
header("Content-type:application/json;charset=utf-8");   
$servername = "localhost";  
$username = "root";  
$password = "root";  
$dbname = "test";  
class User {
public $id;
public $name;
public $age;
public $sex;
}
//汉字转码
function decodeUnicode($str){
  return preg_replace_callback(&#39;/\\\\u([0-9a-f]{4})/i&#39;,
    create_function(
      &#39;$matches&#39;,
      &#39;return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");&#39;
    ),
    $str);
}
$data = array();
// 创建连接  
$con =mysqli_connect($servername, $username, $password, $dbname);  
// 检测连接  
$sql = "SELECT * FROM `user` WHERE 1";  
$result = mysqli_query($con,$sql);  
if($result){
while ($row=mysqli_fetch_array($result,MYSQL_ASSOC)){ 
    $user = new User();
$user->id = $row["id"];
$user->name = $row["name"];
$user->age = $row["age"];
$user->sex = $row["sex"];
$data[]=$user;
}
//打印编码后的json字符串
    $json = json_encode($data);
    echo decodeUnicode($json);
}else{
echo "查询失败";
}
mysqli_close($con);
?>

 

推荐学习:《PHP视频教程

The above is the detailed content of How to query mysql in php and return json. 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