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 常用类整理
Dec 23 PHP
细谈php中SQL注入攻击与XSS攻击
Jun 10 PHP
PHP错误Allowed memory size of 67108864 bytes exhausted的3种解决办法
Jul 28 PHP
php随机抽奖实例分析
Mar 04 PHP
php一个解析字符串排列数组的方法
May 12 PHP
php打乱数组二维数组多维数组的简单实例
Jun 17 PHP
php无限级分类实现方法分析
Oct 19 PHP
浅谈PHP中如何实现Hook机制
Nov 14 PHP
PDO::exec讲解
Jan 28 PHP
php 使用expat方式解析xml文件操作示例
Nov 26 PHP
PHP pthreads v3在centos7平台下的安装与配置操作方法
Feb 21 PHP
PHP与Web页面的交互示例详解二
Aug 04 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者的疑难问答(1)
2006/10/09 PHP
php preg_match_all结合str_replace替换内容中所有img
2008/10/11 PHP
深入密码加salt原理的分析
2013/06/06 PHP
php校验表单检测字段是否为空的方法
2015/03/20 PHP
PHP限制HTML内容中图片必须是本站的方法
2015/06/16 PHP
php用户密码加密算法分析【Discuz加密算法】
2016/10/12 PHP
php获取微信共享收货地址的方法
2017/12/21 PHP
很可爱的输入框
2008/08/03 Javascript
JS操作XML实例总结(加载与解析XML文件、字符串)
2015/12/08 Javascript
AngularJs  unit-testing(单元测试)详解
2016/09/02 Javascript
easyui datagrid 表格中操作栏 按钮图标不显示的解决方法
2017/07/27 Javascript
jQuery实现对网页节点的增删改查功能示例
2017/09/18 jQuery
vue实现搜索过滤效果
2019/05/28 Javascript
jquery 遍历hash操作示例【基于ajax交互】
2019/10/12 jQuery
[00:37]DOTA2上海特级锦标赛 Secert 战队宣传片
2016/03/03 DOTA
c++生成dll使用python调用dll的方法
2014/01/20 Python
pygame学习笔记(3):运动速率、时间、事件、文字
2015/04/15 Python
在服务器端实现无间断部署Python应用的教程
2015/04/16 Python
总结Python编程中三条常用的技巧
2015/05/11 Python
Python中使用双下划线防止类属性被覆盖问题
2019/06/27 Python
python顺序执行多个py文件的方法
2019/06/29 Python
Python pygame绘制文字制作滚动文字过程解析
2019/12/12 Python
Python While循环语句实例演示及原理解析
2020/01/03 Python
pyecharts绘制中国2020肺炎疫情地图的实例代码
2020/02/12 Python
Python pip使用超时问题解决方案
2020/08/03 Python
英国最大的奢侈珠宝和手表网站:C W Sellors
2017/02/10 全球购物
英国在线花园中心:You Garden
2018/06/03 全球购物
巴西香水和化妆品购物网站:The Beauty Box
2019/09/03 全球购物
货代行业个人求职简历的自我评价
2013/10/22 职场文书
实习生求职自荐信
2014/02/07 职场文书
大学生简历求职信
2014/06/24 职场文书
高中综合实践活动总结
2014/07/07 职场文书
祖国在我心中演讲稿600字
2014/09/23 职场文书
走群众路线学习笔记
2014/11/06 职场文书
医学生自荐信范文
2015/03/05 职场文书
小学体育课教学反思
2016/02/16 职场文书