本文實(shí)例講述了thinkPHP5實(shí)現(xiàn)的查詢數(shù)據(jù)庫并返回json數(shù)據(jù)。分享給大家供大家參考,具體如下:
TP5 實(shí)現(xiàn)查詢數(shù)據(jù)庫返回json數(shù)據(jù)(返回json數(shù)據(jù)函數(shù)實(shí)例)
返回結(jié)果:
一、把格式化json函數(shù)寫到公共文件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; }
二、查詢數(shù)據(jù) 控制方式 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(); } //學(xué)校列表 public function school() { $rs=db('school')->select(); $rs1=json(0,'數(shù)據(jù)返回成功',1000,$rs); dump($rs1);die;//打印出來 return $this -> fetch(); }
PS:這里再為大家推薦幾款比較實(shí)用的json在線工具供大家參考使用:
在線JSON代碼檢驗(yàn)、檢驗(yàn)、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.jb51.net/code/jsoncodeformat
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP中json格式數(shù)據(jù)操作技巧匯總》、《ThinkPHP入門教程》、《thinkPHP模板操作技巧總結(jié)》、《ThinkPHP常用方法總結(jié)》、《codeigniter入門教程》、《CI(CodeIgniter)框架進(jìn)階教程》、《Zend FrameWork框架入門教程》及《PHP模板技術(shù)總結(jié)》。
希望本文所述對大家基于ThinkPHP框架的PHP程序設(shè)計(jì)有所幫助。