tp5实现数据接口

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

  1. 数据接口(model层)
<?php
/**
 * 数据接口文件
 */

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层)
<?php
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条数据
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值