Home > Backend Development > PHP Tutorial > Query database and return json data instance implemented by thinkPHP5

Query database and return json data instance implemented by thinkPHP5

不言
Release: 2023-03-25 11:30:02
Original
6330 people have browsed it

This article mainly introduces the function of querying the database and returning json data implemented by thinkPHP5, and analyzes the simple operation skills of thinkPHP5 database query and json format data. Friends in need can refer to it

This article describes the example of thinkPHP5 The implementation queries the database and returns json data. Share it with everyone for your reference, the details are as follows:

TP5 implements querying the database and returning json data (returning json data function instance)

Return results:

Copy code The code is as follows:

{
"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"}]}
Copy after login

1. Write the formatted json function to the public file common.php. The common.php file path 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
  );
  //输出json
  echo json_encode($result);
  exit;
}
Copy after login

2. Query data Control method 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(&#39;school&#39;)->select();
    $rs1=json(0,&#39;数据返回成功&#39;,1000,$rs);
    dump($rs1);die;//打印出来
    return $this -> fetch();
  }
Copy after login

Related recommendations:

Introduction to the method of implementing paging function in thinkphp5

The above is the detailed content of Query database and return json data instance implemented by thinkPHP5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template