本文实例讲述了thinkPHP5实现的查询数据库并返回json数据。分享给大家供大家参考,具体如下:
TP5 实现查询数据库返回json数据(返回json数据函数实例)
返回结果:
复制代码 代码如下:
{"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"}]}
一、把格式化json函数写到公共文件common.php中,common.php文件路径在:application/common.php 所有文件文件都可以引用
function json($code,$msg="",$count,$data=array()){ $result=array( 'code'=>$code, 'msg'=>$msg, 'count'=>$count, 'data'=>$data ); //输出json echo json_encode($result); exit; }
二、查询数据 控制方式 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(); }