ThinkPHP5 implements database query and returns the json data instance, thinkphp5json
This example describes how thinkPHP5 queries a database and returns json data. We will share this with you for your reference. The details are as follows:
TP5: query the database and return json data (return the json data function instance)
Returned results:
Copy codeCode: {"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": "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 common. php public file. The path of the common. php file is: application/common. php. All file 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 ;}
Ii. Data Query control method 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, 'Data returned successfully', 1000, $ rs); dump ($ rs1); die; // print the return $ this-> fetch ();}
PS: Here are some useful json online tools for your reference:
Online JSON code verification, validation, beautification, and formatting tools:
Http://tools.jb51.net/code/json
JSONOnline formatting tool:
Http://tools.jb51.net/code/jsonformat
Online XML/JSON conversion tools:
Http://tools.jb51.net/code/xmljson
JsonCode Online formatting/beautification/compression/editing/conversion tools:
Http://tools.jb51.net/code/jsoncodeformat