The thinkPHP5 implementation queries the database and returns an json data instance
- 2021-08-10 07:14:03
- OfStack
This article illustrates the implementation of thinkPHP5 to query the database and return json data. Share it for your reference, as follows:
TP5 Implementation Query Database Returns json Data (Returns json Data Function Instance)
Return results:
{"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 file path of common. php 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
);
// Output json
echo json_encode($result);
exit;
}
2. Query data control mode 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();
}
// School list
public function school()
{
$rs=db('school')->select();
$rs1=json(0,' Data returned successfully ',1000,$rs);
dump($rs1);die;// Print it out
return $this -> fetch();
}
PS: Here we recommend several practical json online tools for your reference:
Online JSON code verification, verification, beautification and formatting tools:
http://tools.ofstack.com/code/json
JSON Online Formatting Tool:
http://tools.ofstack.com/code/jsonformat
On-line XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson
json code online formatting/beautification/compression/editing/conversion tool:
http://tools.ofstack.com/code/jsoncodeformat
For more readers interested in PHP related contents, please check the topics of this site: Summary of json Format Data Operation Skills in PHP, Introduction Tutorial of ThinkPHP, Summary of thinkPHP Template Operation Skills, Summary of ThinkPHP Common Methods, Introduction Tutorial of codeigniter, Advanced Tutorial of CI (CodeIgniter) Framework, Introduction Tutorial of Zend FrameWork Framework and Summary of PHP Template Technology.
I hope this article is helpful to PHP programming based on ThinkPHP framework.