Home > Article > Backend Development > Query database and return json data instance implemented by thinkPHP5
This article mainly introduces the function of querying the database and returning json data implemented by thinkPHP5, and analyzes the simple operation skills of thinkPHP5 database query and json format data. Friends in need can refer to it
This article describes the example of thinkPHP5 The implementation queries the database and returns json data. Share it with everyone for your reference, the details are as follows:
TP5 implements querying the database and returning json data (returning json data function instance)
Return results:
Copy code The code is as follows:
{ "code":0, "msg":"\u6570\u636e\u8fd4\u56de\u6210\u529f", "count":1000, "data":[{"id":617, "title":"\u5317\u4eac\u7406\u5de5\u5927\u5b66", "flid":1, "pid":0,"uid":1, "price":0, "admin_name":null, "time":"2017-09-22 16:17:16"}, { "id":618,"title":"\u5357\u5f00\u5927\u5b66", "flid":1,"pid":0,"uid":1,"price":0,"admin_name":null, "time":"2017-09-22 16:17:28"}]}
1. Write the formatted json function to the public file common.php. The common.php file path is: application/common.php. All files can be referenced.
function json($code,$msg="",$count,$data=array()){ $result=array( 'code'=>$code, 'msg'=>$msg, 'count'=>$count, 'data'=>$data ); //输出json echo json_encode($result); exit; }
2. Query data Control method Main.php
application\admin\controller\Main.php
<?php namespace app\admin\controller; use think\Controller; use think\Validate; use think\Request; //use think\Db; class Main extends controller { public function index() { return $this -> fetch(); } //学校列表 public function school() { $rs=db('school')->select(); $rs1=json(0,'数据返回成功',1000,$rs); dump($rs1);die;//打印出来 return $this -> fetch(); }
Related recommendations:
Introduction to the method of implementing paging function in thinkphp5
The above is the detailed content of Query database and return json data instance implemented by thinkPHP5. For more information, please follow other related articles on the PHP Chinese website!