PHP封装的数据库模型Model类完整示例【基于PDO】


Posted in PHP onMarch 14, 2019

本文实例讲述了PHP封装的数据库模型Model类。分享给大家供大家参考,具体如下:

<?php
    //引入配置文件
    include "../Config/config.php";
    class Model extends PDO
    {
        protected $tableName = "";//存储表名
        protected $sql = "";//存储最后执行的SQL语句
        protected $limit = "";//存储limit条件
        protected $order = "";//存储order排序条件
        protected $field = "*";//存储要查询的字段
        protected $where = "";//存储where条件
        protected $allFields = [];//存储当前表的所有字段
        /**
         * 构造方法 初始化
         * @param string $tableName 要操作的表名
         */
        public function __construct($tableName)
        {
            //连接数据库
            parent::__construct('mysql:host='.HOST.';dbname='.DB.';charset=utf8;port='.PORT,USER,PWD);
            //存储表名
            $this->tableName = PRE.$tableName;
            //获取当前数据表中有哪些字段
            $this->getFields();
        }
        /**
         * 获取当前表的所有字段
     * @return array 成功则返回一维数组字段
         */
        public function getFields()
        {
            //查看当前表结构
            $sql = "desc {$this->tableName}";
            $res = $this->query($sql);//返回pdo对象
          //var_dump($res);
            if ($res) {
                $arr = $res->fetchAll(2);
                //var_dump($arr);
                //从二维数组中取出指定下标的列
                $this->allFields =    array_column($arr,"Field");
                return $this->allFields;
            } else {
                die("表名错误");
            }
        }
        /**
         * 添加操作
         * @param array $data 要添加的数组
         * @return int 返回受影响行数
         */
        public function add($data)
        {
            //判断是否是数组
            if (!is_array($data)) {
                    return $this;
            }
            //判断是否全是非法字段
            if (empty($data)) {
                    die("非法字段");
            }
            //过滤非法字段
            foreach($data as $k => $v){
                if (!in_array($k,$this->allFields)) {
                    unset($data[$k]);
                }
            }
            //将数组中的键取出
            $keys = array_keys($data);
            //将数组中取出的键转为字符串拼接
            $key = implode(",",$keys);
            //将数组中的值转化为字符串拼接
            $value = implode("','",$data);
            //准备SQL语句
            $sql = "insert into {$this->tableName} ({$key}) values('{$value}')";
            $this->sql = $sql;
            //执行并发送SQL,返回受影响行数
            return (int)$this->exec($sql);
        }
        /**
         * 删除操作
         * @param string $id 要删除的id
         * @return int 返回受影响行数
         */
        public function delete($id="")
        {
            //判断id是否存在
            if (empty($id)) {
                $where = $this->where;
            }else{
                $where = "where id={$id}";
            }
            $sql = "delete from {$this->tableName} {$where}";
      $this->sql = $sql;
            //执行并发送SQL,返回受影响行数
            return (int)$this->exec($sql);
        }
    /**
     * 修改操作
     * @param array $data 要修改的数组
     * @return int 返回受影响行数
     */
    public function update($data)
    {
      //判断是否是数组
      if (!is_array($data)){
        return $this;
      }
      //判断是否全是非法字段
      if (empty($data)) {
        die('全是非法字段');
      }
      $str = "";
      //过滤非法字段
      foreach ($data as $k=>$v) {
        //字段为id时,判断id是否存在的
        if ($k == "id"){
          $this->where = "where id={$v}";
          unset($data[$k]);
          continue;
        }
        //若字段不为id,则过滤后再拼接成set字段
        if (in_array($k, $this->allFields)) {
          $str .= "{$k}='{$v}',";
        } else {
          unset($data[$k]);
        }
      }
      //判断是否传了条件
      if (empty($this->where)) {
        die('请传入修改条件');
      }
      //去除右边的,
      $str = rtrim($str, ',');
      $sql = "update {$this->tableName} set {$str} {$this->where}";
      //echo $sql;
      $this->sql = $sql;
      return (int)$this->exec($sql);
    }
    /**
     * 查询多条数据
     * @return array 成功返回二维数组,失败返回空数组
     */
        public function select()
    {
          $sql = "select {$this->field} from {$this->tableName} {$this->where} {$this->order} {$this->limit}";
      $this->sql = $sql;
      //执行SQL,结果集是一个对象
          $res = $this->query($sql);
          //判断是否查询成功,
      if ($res){
        //成功返回二维数组
        return $res->fetchAll(2);
      }
      //失败返回空数组
      return [];
    }
    /**
     * 查询一条数组
     * @param string $id 要查询的id
     * @return array 返回一条数据
     */
    public function find($id="")
    {
      //判断是否存在id
      if (empty($id)){
        $where = $this->where;
      }else{
        $where = "where id={$id}";
      }
          $sql = "select {$this->field} from {$this->tableName} {$where} {$this->order} limit 1";
      $this->sql = $sql;
      //执行sql,结果集为对象
      $res = $this->query($sql);
      //判断是否查询成功
      if ($res){
        //成功则返回一条数据(一维数组)
        $result = $res->fetchAll(2);
        return $result[0];
      }
      //失败返回空数组
      return [];
    }
    /**
     * 统计总数目
     * @return int 返回总数
     */
    public function count()
    {
      $sql = "select count(*) as total from {$this->tableName} {$this->where} limit 1";
      $this->sql = $sql;
      //执行SQL,结果集为对象
      $res = $this->query($sql);
      //处理结果集
      if ($res){
       $result = $res->fetchAll(2);
       //var_dump($result);
        return $result[0]["total"];
      }
      return 0;
    }
    /**
     * 设置要查询的字段信息
     * @param string $field 要查询的字段
     * @return object 返回自己,保证连贯操作
     */
    public function field($field)
    {
      //判断字段是否存在
      if (empty($filed)){
        return $this;
      }
      $this->field = $field;
      return $this;
    }
    /**
     * 获取最后执行的sql语句
     * @return string sql语句
     */
    public function _sql()
    {
      return $this->sql;
    }
    /**
     * where条件
     * @param string $where 要输入的where条件
     * @return object 返回自己,保证连贯操作
     */
    public function where($where)
    {
      $this->where = "where ".$where;
      return $this;
    }
    /**
     * order条件
     * @param string $order 要输入的order条件
     * @return object 返回自己,保证连贯操作
     */
    public function order($order)
    {
      $this->order = "order by ".$order;
      return $this;
    }
    /**
     * limit条件
     * @param string $limit 要输入的limit条件
     * @return object 返回自己,保证连贯操作
     */
    public function limit($limit)
    {
      $this->limit = "limit ".$limit;
      return $this;
    }
}

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
PHP HTML代码串截取代码
Dec 29 PHP
php5.3 废弃函数小结
May 16 PHP
PHP常用代码大全(新手入门必备)
Jun 29 PHP
PHP中文件缓存转内存缓存的方法
Dec 06 PHP
php对csv文件的读取,写入,输出下载操作详解
Aug 10 PHP
PHP执行Curl时报错提示CURL ERROR: Recv failure: Connection reset by peer的解决方法
Jun 26 PHP
PHP SPL标准库之SplFixedArray使用实例
May 12 PHP
简单解决新浪SAE无法上传文件的问题
May 13 PHP
Symfony2学习笔记之模板用法详解
Mar 17 PHP
PHP指定截取字符串中的中英文或数字字符的实例分享
Mar 18 PHP
分享php多功能图片处理类
May 15 PHP
PHP那些琐碎的知识点(整理)
May 20 PHP
PHP模型Model类封装数据库操作示例
Mar 14 #PHP
php中pcntl_fork创建子进程的方法实例
Mar 14 #PHP
PHP7内核之Reference详解
Mar 14 #PHP
掌握PHP垃圾回收机制详解
Mar 13 #PHP
浅谈php的TS和NTS的区别
Mar 13 #PHP
浅谈PHP各环境下的伪静态配置
Mar 13 #PHP
Laravel框架实现的使用smtp发送邮件功能示例
Mar 12 #PHP
You might like
php检测图片木马多进制编程实践
2013/04/11 PHP
基于MySQL到MongoDB简易对照表的详解
2013/06/03 PHP
PHP从FLV文件获取视频预览图的方法
2015/03/12 PHP
PHP构造二叉树算法示例
2017/06/21 PHP
Laravel 集成微信用户登录和绑定的实现
2019/12/27 PHP
为数据添加append,remove功能
2006/10/03 Javascript
jQuery移动和复制dom节点实用DOM操作案例
2012/12/17 Javascript
JS delegate与live浅析
2013/12/21 Javascript
解决js下referer兼容各大浏览器的方法
2014/11/03 Javascript
Bootstrap入门书籍之(三)栅格系统
2016/02/17 Javascript
微信小程序表单验证错误提示效果
2017/05/19 Javascript
javascript计算渐变颜色的实例
2017/09/22 Javascript
JS实现图片居中悬浮效果
2017/12/25 Javascript
利用npm 安装删除模块的方法
2018/05/15 Javascript
vue实现Excel文件的上传与下载功能的两种方式
2019/06/28 Javascript
微信小程序批量监听输入框对按钮样式进行控制的实现代码
2019/10/12 Javascript
原生js实现俄罗斯方块
2020/10/20 Javascript
[01:33:14]LGD vs VP Supermajor 败者组决赛 BO3 第二场 6.10
2018/07/04 DOTA
[55:44]OG vs NAVI 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
Python3导入CSV文件的实例(跟Python2有些许的不同)
2018/06/22 Python
Django contenttypes 框架详解(小结)
2018/08/13 Python
Python 实现文件读写、坐标寻址、查找替换功能
2019/09/11 Python
Python根据服务获取端口号的方法
2019/09/25 Python
python连接mysql数据库并读取数据的实现
2020/09/25 Python
巴西美妆购物网站:Kutiz Beauté
2019/03/13 全球购物
教师申诉制度
2014/01/29 职场文书
酒店管理专业毕业生求职自荐信
2014/04/28 职场文书
机电专业毕业生求职信
2014/07/01 职场文书
未婚证明书模板
2014/10/08 职场文书
四风问题专项整治工作情况报告
2014/10/28 职场文书
酒店圣诞节活动总结
2015/05/06 职场文书
民事答辩状格式范文
2015/05/21 职场文书
安全伴我行主题班会
2015/08/13 职场文书
Python带你从浅入深探究Tuple(基础篇)
2021/05/15 Python
在Oracle表中进行关键词搜索的过程
2022/06/10 Oracle
Redis实现短信验证码登录的示例代码
2022/06/14 Redis