thinkPHP5實現的查詢資料庫並返回json資料執行個體

來源:互聯網
上載者:User
這篇文章主要介紹了thinkPHP5實現的查詢資料庫並返回json資料功能,分析了thinkPHP5資料庫查詢及json格式資料簡單操作技巧,需要的朋友可以參考下

本文執行個體講述了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

<?phpnamespace 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();  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.