PHP的PDO常用类库实例分析


Posted in PHP onApril 07, 2016

本文实例讲述了PHP的PDO常用类库。分享给大家供大家参考,具体如下:

1、Db.class.php 连接数据库

<?php
// 连接数据库
class Db {
  static public function getDB() {
    try {
      $pdo = new PDO(DB_DSN, DB_USER, DB_PWD);
      $pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置抛出错误
      $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 设置当字符串为空转换为 SQL 的 NULL
      $pdo->query('SET NAMES utf8'); // 设置数据库编码
    } catch (PDOException $e) {
      exit('数据库连接错误,错误信息:'. $e->getMessage());
    }
    return $pdo;
  }
}
?>

2、Model.class.php 数据库操作类

<?php
/**
* 数据库操作类库
* author Lee.
* Last modify $Date: 2012-1-19 13:59;04 $
*/
class M {
  private $_db; //数据库句柄
  public $_sql; //SQL语句
  /**
   * 构造方法
   */
  public function __construct() {
    $this->_db = Db::getDB();
  }
  /**
   * 数据库添加操作
   * @param string $tName 表名
   * @param array $field 字段数组
   * @param array $val 值数组
   * @param bool $is_lastInsertId 是否返回添加ID
   * @return int 默认返回成功与否,$is_lastInsertId 为true,返回添加ID
   */
  public function insert($tName, $fields, $vals, $is_lastInsertId=FALSE) {
    try {
      if (!is_array($fields) || !is_array($vals))
        exit($this->getError(__FUNCTION__, __LINE__));
      $fields = $this->formatArr($fields);
      $vals = $this->formatArr($vals, false);
      $tName = $this->formatTabName($tName);
      $this->_sql = "INSERT INTO {$tName} ({$fields}) VALUES ({$vals})";
      if (!$is_lastInsertId) {
        $row = $this->_db->exec($this->_sql);
        return $row;
      } else {
        $this->_db->exec($this->_sql);
        $lastId = (int)$this->_db->lastInsertId();
        return $lastId;
      }
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 数据库修改操作
   * @param string $tName 表名
   * @param array $field 字段数组
   * @param array $val 值数组
   * @param string $condition 条件
   * @return int 受影响的行数
   */
  public function update($tName, $fieldVal, $condition) {
    try {
      if (!is_array($fieldVal) || !is_string($tName) || !is_string($condition))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $upStr = '';
      foreach ($fieldVal as $k=>$v) {
        $upStr .= '`'.$k . '`=' . '\'' . $v . '\'' . ',';
      }
      $upStr = rtrim($upStr, ',');
      $this->_sql = "UPDATE {$tName} SET {$upStr} WHERE {$condition}";
      $row = $this->_db->exec($this->_sql);
      return $row;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 数据库删除操作(注:必须添加 where 条件)
   * @param string $tName 表名
   * @param string $condition 条件
   * @return int 受影响的行数
   */
  public function del($tName, $condition) {
    try {
      if (!is_string($tName) || !is_string($condition))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName= $this->formatTabName($tName);
      $this->_sql = "DELETE FROM {$tName} WHERE {$condition}";
      $row = $this->_db->exec($this->_sql);
      return $row;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 返回表总个数
   * @param string $tName 表名
   * @param string $condition 条件
   * @return int
   */
  public function total($tName, $condition='') {
    try {
      if (!is_string($tName))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $this->_sql = "SELECT COUNT(*) AS total FROM {$tName}" .
      ($condition=='' ? '' : ' WHERE ' . $condition);
      $re = $this->_db->query($this->_sql);
      foreach ($re as $v) {
        $total = $v['total'];
      }
      return (int)$total;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 数据库删除多条数据
   * @param string $tName 表名
   * @param string $field 依赖字段
   * @param array $ids 删除数组
   * @return int 受影响的行数
   */
  public function delMulti($tName, $field, $ids) {
    try {
      if (!is_string($tName) || !is_array($ids))
        exit($this->getError(__FUNCTION__, __LINE__));
      $delStr = '';
      $tName = $this->formatTabName($tName);
      $field = $this->formatTabName($field);
      foreach ($ids as $v) {
        $delStr .= $v . ',';
      }
      $delStr = rtrim($delStr, ',');
      $this->_sql = "DELETE FROM {$tName} WHERE {$field} IN ({$delStr})";
      $row = $this->_db->exec($this->_sql);
      return $row;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 获取表格的最后主键(注:针对 INT 类型)
   * @param string $tName 表名
   * @return int
   */
  public function insertId($tName) {
    try {
      if (!is_string($tName))
        exit($this->getError(__FUNCTION__, __LINE__));
      $this->_sql = "SHOW TABLE STATUS LIKE '{$tName}'";
      $result = $this->_db->query($this->_sql);
      $insert_id = 0;
      foreach ($result as $v) {
        $insert_id = $v['Auto_increment'];
      }
      return (int)$insert_id;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 检查数据是否已经存在(依赖条件)
   * @param string $tName 表名
   * @param string $field 依赖的字段
   * @return bool
   */
  public function exists($tName, $condition) {
    try {
      if (!is_string($tName) || !is_string($condition))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $this->_sql = "SELECT COUNT(*) AS total FROM {$tName} WHERE {$condition}";
      $result = $this->_db->query($this->_sql);
      foreach ($result as $v) {
         $b = $v['total'];
      }
      if ($b) {
        return true;
      } else {
        return false;
      }
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 检查数据是否已经存在(依赖 INT 主键)
   * @param string $tName 表名
   * @param string $primary 主键
   * @param int $id 主键值
   * @return bool
   */
  public function existsByPK($tName, $primary, $id) {
    try {
      if (!is_string($tName) || !is_string($primary)
      || !is_int($id))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $this->_sql = "SELECT COUNT(*) AS total FROM {$tName} WHERE {$primary} = ". $id;
      $result = $this->_db->query($this->_sql);
      foreach ($result as $v) {
         $b = $v['total'];
      }
      if ($b) {
        return true;
      } else {
        return false;
      }
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 预处理删除(注:针对主键为 INT 类型,推荐使用)
   * @param string $tName 表名
   * @param string $primary 主键字段
   * @param int or array or string $ids 如果是删除一条为 INT,多条为 array,删除一个范围为 string
   * @return int 返回受影响的行数
   */
  public function delByPK($tName, $primary, $ids, $mult=FALSE) {
    try {
      if (!is_string($tName) || !is_string($primary)
      || (!is_int($ids) && !is_array($ids) && !is_string($ids))
      || !is_bool($mult)) exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $stmt = $this->_db->prepare("DELETE FROM {$tName} WHERE {$primary}=?");
      if (!$mult) {
        $stmt->bindParam(1, $ids);
        $row = $stmt->execute();
      } else {
        if (is_array($ids)) {
          $row = 0;
          foreach ($ids as $v) {
            $stmt->bindParam(1, $v);
            if ($stmt->execute()) {
              $row++;
            }
          }
        } elseif (is_string($ids)) {
          if (!strpos($ids, '-'))
            exit($this->getError(__FUNCTION__, __LINE__));
          $split = explode('-', $ids);
          if (count($split)!=2 || $split[0]>$split[1])
            exit($this->getError(__FUNCTION__, __LINE__));
          $i = null;
          $count = $split[1]-$split[0]+1;
          for ($i=0; $i<$count; $i++) {
            $idArr[$i] = $split[0]++;
          }
          $idStr = '';
          foreach ($idArr as $id) {
            $idStr .= $id . ',';
          }
          $idStr = rtrim($idStr, ',');
          $this->_sql ="DELETE FROM {$tName} WHERE {$primary} in ({$idStr})";
          $row = $this->_db->exec($this->_sql);
        }
      }
      return $row;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 返回单个字段数据或单条记录
   * @param string $tName 表名
   * @param string $condition 条件
   * @param string or array $fields 返回的字段,默认是*
   * @return string || array
   */
  public function getRow($tName, $condition='', $fields="*") {
    try {
      if (!is_string($tName) || !is_string($condition)
      || !is_string($fields) || empty($fields))
         exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $this->_sql = "SELECT {$fields} FROM {$tName} ";
      $this->_sql .= ($condition=='' ? '' : "WHERE {$condition}") . " LIMIT 1";
      $sth = $this->_db->prepare($this->_sql);
      $sth->execute();
      $result = $sth->fetch(PDO::FETCH_ASSOC);
      if ($fields === '*') {
        return $result;
      } else {
        return $result[$fields];
      }
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 返回多条数据
   * @param string $tName 表名
   * @param string $fields 返回字段,默认为*
   * @param string $condition 条件
   * @param string $order 排序
   * @param string $limit 显示个数
   * @return PDOStatement
   */
  public function getAll($tName, $fields='*', $condition='', $order='', $limit='') {
    try {
      if (!is_string($tName) || !is_string($fields)
      || !is_string($condition) || !is_string($order)
      || !is_string($limit))
        exit($this->getError(__FUNCTION__, __LINE__));
      $tName = $this->formatTabName($tName);
      $fields = ($fields=='*' || $fields=='') ? '*' : $fields;
      $condition = $condition=='' ? '' : " WHERE ". $condition ;
      $order = $order=='' ? '' : " ORDER BY ". $order;
      $limit = $limit=='' ? '' : " LIMIT ". $limit;
      $this->_sql = "SELECT {$fields} FROM {$tName} {$condition} {$order} {$limit}";
      $sth = $this->_db->prepare($this->_sql);
      $sth->execute();
      $result = $sth->fetchAll(PDO::FETCH_ASSOC);
      return $result;
    } catch (PDOException $e) {
      exit($e->getMessage());
    }
  }
  /**
   * 格式化数组(表结构和值)
   * @param array $field
   * @param bool $isField
   * @return string
   */
  private function formatArr($field, $isField=TRUE) {
    if (!is_array($field)) exit($this->getError(__FUNCTION__, __LINE__));
    $fields = '';
    if ($isField) {
      foreach ($field as $v) {
        $fields .= '`'.$v.'`,';
      }
    } else {
      foreach ($field as $v) {
        $fields .= '\''.$v.'\''.',';
      }
    }
    $fields = rtrim($fields, ',');
    return $fields;
  }
  /**
   * 格式化问号
   * @param int $count 数量
   * @return string 返回格式化后的字符串
   */
  private function formatMark($count) {
    $str = '';
    if (!is_int($count)) exit($this->getError(__FUNCTION__, __LINE__));
    if ($count==1) return '?';
    for ($i=0; $i<$count; $i++) {
      $str .= '?,';
    }
    return rtrim($str, ',');
  }
  /**
   * 错误提示
   * @param string $fun
   * @return string
   */
  private function getError($fun, $line) {
    return __CLASS__ . '->' . $fun . '() line<font color="red">'. $line .'</font> ERROR!';
  }
  /**
   * 处理表名
   * @param string $tName
   * @return string
   */
  private function formatTabName($tName) {
    return '`' . trim($tName, '`') . '`';
  }
  /**
   * 析构方法
   */
  public function __destruct() {
    $this->_db = null;
  }
}

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

PHP 相关文章推荐
解决dede生成静态页和动态页转换的一些问题,及火车采集入库生成动态的办法
Mar 29 PHP
php sprintf()函数让你的sql操作更安全
Jul 23 PHP
一个PHP的远程图片抓取函数分享
Sep 25 PHP
PHP针对常规模板引擎中与CSS/JSON冲突的解决方法
Aug 19 PHP
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 2611816 bytes)
Nov 08 PHP
php结合安卓客户端实现查询交互实例
May 05 PHP
win7安装php框架Yii的方法
Jan 25 PHP
thinkPHP删除前弹出确认框的简单实现方法
May 16 PHP
PHP使用php-resque库配合Redis实现MQ消息队列的教程
Jun 29 PHP
php操纵mysqli数据库的实现方法
Sep 18 PHP
简单谈谈 php 文件锁
Feb 19 PHP
yii框架结合charjs统计上一年与当前年数据的方法示例
Apr 04 PHP
PHP安全下载文件的方法
Apr 07 #PHP
php生成验证码,缩略图及水印图的类分享
Apr 07 #PHP
PHP使用token防止表单重复提交的方法
Apr 07 #PHP
PHP使用Mysqli类库实现完美分页效果的方法
Apr 07 #PHP
Linux下编译redis和phpredis的方法
Apr 07 #PHP
php 实现进制相互转换
Apr 07 #PHP
Linux(CentOS)下PHP扩展PDO编译安装的方法
Apr 07 #PHP
You might like
PHP 高级课程笔记 面向对象
2009/06/21 PHP
php中将一段数据存到一个txt文件中并显示其内容
2014/08/15 PHP
PHP操作MySQL的mysql_fetch_* 函数的常见用法教程
2015/12/25 PHP
ThinkPHP发送邮件示例代码
2016/10/08 PHP
Laravel 5.5官方推荐的Nginx配置学习教程
2017/10/06 PHP
php微信公众号开发之图片回复
2018/10/20 PHP
JavaScript 异步调用框架 (Part 4 - 链式调用)
2009/08/04 Javascript
用JavaScript将从数据库中读取出来的日期型格式化为想要的类型。
2009/08/15 Javascript
js中判断控件是否存在
2010/08/25 Javascript
用javascript关闭本窗口技巧小结
2014/09/05 Javascript
jQuery插件StickUp实现网页导航置顶
2015/04/12 Javascript
JavaScript的RequireJS库入门指南
2015/07/01 Javascript
JS文字球状放大效果代码分享
2015/08/19 Javascript
vue loadmore 组件滑动加载更多源码解析
2017/07/19 Javascript
jquery中done和then的区别(详解)
2017/12/19 jQuery
JavaScript实现的简单Tab点击切换功能示例
2018/07/06 Javascript
JavaScript常用事件介绍
2019/01/21 Javascript
详解JavaScript的变量
2019/04/04 Javascript
layui-select动态选中值的例子
2019/09/23 Javascript
js中script的上下放置区别,Dom的增删改创建操作实例分析
2019/12/16 Javascript
Vue+Node实现的商城用户管理功能示例
2019/12/23 Javascript
使用IronPython把Python脚本集成到.NET程序中的教程
2015/03/31 Python
Python中一般处理中文的几种方法
2019/03/06 Python
Python GUI编程完整示例
2019/04/04 Python
详解python执行shell脚本创建用户及相关操作
2019/04/11 Python
python新式类和经典类的区别实例分析
2020/03/23 Python
Python爬虫爬取杭州24时温度并展示操作示例
2020/03/27 Python
keras自定义回调函数查看训练的loss和accuracy方式
2020/05/23 Python
BISSELL官网:北美吸尘器第一品牌
2019/03/14 全球购物
致垒球运动员加油稿
2014/02/16 职场文书
80后婚前协议书范本
2014/10/24 职场文书
医院科室评语
2015/01/04 职场文书
挂靠协议书
2015/01/27 职场文书
房屋产权证明书
2015/06/19 职场文书
2016年庆“七一”主题党日活动总结
2016/04/05 职场文书
js基于div丝滑实现贝塞尔曲线
2022/09/23 Javascript