php从数据库读取数据,并以json格式返回数据的方法
php中,从数据库读取数据,并以json格式返回数据。具体方法如下:
第一步,定义相关变量
$servername = "localhost"; $username = "root"; $password = "root"; $mysqlname = "datatest"; $json = ''; $data = array(); class User { public $id; public $fname; public $lname; public $email; public $password; }
第二步,链接数据库,代码如下:
// 创建连接 $conn = mysqli_connect($servername, $username, $password, $mysqlname);
第三步,定义查询语句,并执行,代码如下:
$sql = "SELECT * FROM userinfo"; $result = $conn->query($sql);
第四步,获取查询出来的数据,并将其放在事先声明的类中,最后以json格式输出。
代码如下:
if($result){ //echo "查询成功"; while ($row = mysqli_fetch_array($result,MYSQL_ASSOC)) { $user = new User(); $user->id = $row["id"]; $user->fname = $row["fname"]; $user->lname = $row["lname"]; $user->email = $row["email"]; $user->password = $row["password"]; $data[]=$user; } $json = json_encode($data);//把数据转换为JSON数据. echo "{".'"user"'.":".$json."}"; }else{ echo "查询失败"; }
相关推荐
lbyd0 2020-11-17
sushuanglei 2020-11-12
腾讯soso团队 2020-11-06
gaobudong 2020-11-04
yangkang 2020-11-09
85477104 2020-11-17
KANSYOUKYOU 2020-11-16
wushengyong 2020-10-28
lizhengjava 2020-11-13
星月情缘 2020-11-13
huangxiaoyun00 2020-11-13
luyong0 2020-11-08
Apsaravod 2020-11-05
PeterChangyb 2020-11-05
wwwjun 2020-11-02
gyunwh 2020-11-02
EchoYY 2020-10-31
dingyahui 2020-10-30