封装thinkPHP的数据库访问类

Original 2019-03-02 00:48:55 513
abstract:<?phpnamespace Util;use think\Db;class SysDb{    //指定表名    public function table($table)    {        //清空上次查询条件        $this-&g
<?php
namespace Util;
use think\Db;
class SysDb{

   //指定表名
   public function table($table)
   {
       //清空上次查询条件
       $this->where = [];
       $this->field = '*';
       $this->order = '';
       $this->limit = 0;
       /***********************************/
       $this->table = $table;
       return $this;
   }

   //指定查询字段
   public function field($field = '*')
   {
       $this->field = $field;
       return $this;
   }

   //加载数量
   public function limit($limit)
   {
       $this->limit = $limit;
       return $this;
   }

   //排序
   public function order($order){
       $this->order = $order;
       return $this;
   }

   //指定查询条件
   public function where($where =[])
   {
       $this->where = $where;
       return $this;
   }

   //查询一条记录
   public function item(){
       return Db::name($this->table)
           ->field($this->field)
           ->where($this->where)
           ->find();
   }

   //返回多条数据
   public function lists()
   {
       $query = Db::name($this->table)
           ->field($this->field)
           ->where($this->where);
       $this->limit && $query = $query ->limit($this->limit);
       $this->order && $query = $query ->order($this->order);
       return $query->select();
   }

   //自定义索引
   public function cates($index)
   {
       $query = Db::name($this->table)
           ->field($this->field)
           ->where($this->where);
       $this->limit && $query = $query ->limit($this->limit);
       $this->order && $query = $query ->order($this->order);
       $lists = $query->select();
       if(!$lists)
       {
           return $lists;
       }

       $result = [];
       foreach ($lists as $key=>$value) {
           $result[$value['$index']] = $value;
       }

       return $result;
   }

   //分页
   public function pages($pageSize = 10)
   {
       $total = Db::name($this->name)
           ->where($this->where)
           ->count();
       $query = Db::name($this->table)
           ->field($this->field)
           ->where($this->where);
       $this->order && $query = $query ->order($this->order);
       $data = $query->pagenate($pageSize,$total);
       return array('total' => $total,'lists' => $data->item(),'pages' => $data->render());
   }


   //插入数据
   public function insert($data)
   {
       return Db::name($this->name)->insertGetId($data);
   }

   //批量插入
   public function insertAll($data){
       return Db::name($this->name)->insertAll($data);
   }


   //修改
   public function update($data)
   {
       return Db::name($this->name)->where($this->where)->update($data);
   }
}


Correcting teacher:查无此人Correction time:2019-03-02 09:15:11
Teacher's summary:完成的不错,多锻炼,防止数据库注入。继续加油

Release Notes

Popular Entries