tp5实现数据接口

注:以下内容均已默认配置好数据库连接且所有表都在同一数据库中

  1. 数据接口(model层)

/**
 * 数据接口文件
 */

namespace app\db_interface\common;
use think\Db;

class Inface
{
     
    //根据表名查询该表总共拥有多少条数据
    public function dataCount($table){
     
        $res = Db::connect(config('interfaceDb'))->table($table)->count();
        return $res;
    }

    //根据表名分页查询100条数据
    public function getOneHundredData($page, $table){
     
        $list = Db::connect(config('interfaceDb'))->table($table)->page($page,100)->select();

        $arr = [];
        $arr['page'] = $page;
        $arr['table'] = $table;
        $arr['item'] = $list;

        return $arr;
    }

    //根据表名查询该表是否存在
    public function isExist($table){
     
        $isTable = Db::connect(config('interfaceDb'))->query('SHOW TABLES LIKE "'.$table.'";');
        if($isTable){
     
            //表存在
           return 1;
        }else{
     
            //表不存在
           return 0;
        }

    }

}
  1. . 数据展示(controllerl层)

namespace app\admin\controller;
use app\db_interface\common\Inface;
use think\Request;
class Index
{
     
    //   根据传入参数和页数每次 json格式展示100数据
    public function index()
    {
     
        $table = Request::instance()->param('table');
        $page = Request::instance()->param('page');
        if ($table == NULL){
     
            $error = ["status"=>0 , 'msg'=>'数据表未知'];
            exit(json_encode($error));
        }
        if ($page == NULL){
     
            $page = 1;
        }
        $inface = new Inface();
        $isTable = $inface->isExist($table);
        if (!$isTable){
     
            exit(json_encode(['status'=>0, 'msg'=>$table.'数据表不存在']));
        }
        $data = $inface->getOneHundredData($page,$table);
        print_r(json_encode($data));

    }
//    json格式展示数据表数据总量
    public function showCount(){
     
        $table = Request::instance()->param('table');
        if ($table == NULL){
     
            $error = ["status"=>0 , 'msg'=>'数据表未知'];
            exit(json_encode($error));
        }
        $inface = new Inface();
        $isTable = $inface->isExist($table);
        if (!$isTable){
     
            exit(json_encode(['status'=>0, 'msg'=>$table.'数据表不存在']));
        }
        $count = $inface->dataCount($table);
        $show = ['table'=>$table, 'count'=> $count];
        print_r( json_encode($show));
    }
}

说明:

  1. 输入:域名/入口文件/模块/index/showCount/table/表名
    eg: http://www.tp5.com/index.php/admin/index/showCount/table/comm_account
    即可查询该表的总数据条数
  2. 输入:域名/入口文件/模块/index/index/table/表名/page/页码
    eg: http://www.tp5.com/index.php/admin/index/index/table/comm_account/page/200
    即可查询该表的相应页数的的100条数据

你可能感兴趣的:(php,php)