A-A+

PHP的PDO常用类库实例分析

2019年10月09日 我爱编程 暂无评论

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

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

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

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

  1. <?php
  2. /**
  3. * 数据库操作类库
  4. * author Lee.
  5. * Last modify $Date: 2012-1-19 13:59;04 $
  6. */
  7. class M {
  8.   private $_db//数据库句柄
  9.   public $_sql//SQL语句
  10.   /**
  11.    * 构造方法
  12.    */
  13.   public function __construct() {
  14.     $this->_db = Db::getDB();
  15.   }
  16.   /**
  17.    * 数据库添加操作
  18.    * @param string $tName 表名
  19.    * @param array $field 字段数组
  20.    * @param array $val 值数组
  21.    * @param bool $is_lastInsertId 是否返回添加ID
  22.    * @return int 默认返回成功与否,$is_lastInsertId 为true,返回添加ID
  23.    */
  24.   public function insert($tName$fields$vals$is_lastInsertId=FALSE) {
  25.     try {
  26.       if (!is_array($fields) || !is_array($vals))
  27.         exit($this->getError(__FUNCTION____LINE__));
  28.       $fields = $this->formatArr($fields);
  29.       $vals = $this->formatArr($vals, false);
  30.       $tName = $this->formatTabName($tName);
  31.       $this->_sql = "INSERT INTO {$tName} ({$fields}) VALUES ({$vals})";
  32.       if (!$is_lastInsertId) {
  33.         $row = $this->_db->exec($this->_sql);
  34.         return $row;
  35.       } else {
  36.         $this->_db->exec($this->_sql);
  37.         $lastId = (int)$this->_db->lastInsertId();
  38.         return $lastId;
  39.       }
  40.     } catch (PDOException $e) {
  41.       exit($e->getMessage());
  42.     }
  43.   }
  44.   /**
  45.    * 数据库修改操作
  46.    * @param string $tName 表名
  47.    * @param array $field 字段数组
  48.    * @param array $val 值数组
  49.    * @param string $condition 条件
  50.    * @return int 受影响的行数
  51.    */
  52.   public function update($tName$fieldVal$condition) {
  53.     try {
  54.       if (!is_array($fieldVal) || !is_string($tName) || !is_string($condition))
  55.         exit($this->getError(__FUNCTION____LINE__));
  56.       $tName = $this->formatTabName($tName);
  57.       $upStr = '';
  58.       foreach ($fieldVal as $k=>$v) {
  59.         $upStr .= '`'.$k . '`=' . '\'' . $v . '\'' . ',';
  60.       }
  61.       $upStr = rtrim($upStr',');
  62.       $this->_sql = "UPDATE {$tName} SET {$upStr} WHERE {$condition}";
  63.       $row = $this->_db->exec($this->_sql);
  64.       return $row;
  65.     } catch (PDOException $e) {
  66.       exit($e->getMessage());
  67.     }
  68.   }
  69.   /**
  70.    * 数据库删除操作(注:必须添加 where 条件)
  71.    * @param string $tName 表名
  72.    * @param string $condition 条件
  73.    * @return int 受影响的行数
  74.    */
  75.   public function del($tName$condition) {
  76.     try {
  77.       if (!is_string($tName) || !is_string($condition))
  78.         exit($this->getError(__FUNCTION____LINE__));
  79.       $tName$this->formatTabName($tName);
  80.       $this->_sql = "DELETE FROM {$tName} WHERE {$condition}";
  81.       $row = $this->_db->exec($this->_sql);
  82.       return $row;
  83.     } catch (PDOException $e) {
  84.       exit($e->getMessage());
  85.     }
  86.   }
  87.   /**
  88.    * 返回表总个数
  89.    * @param string $tName 表名
  90.    * @param string $condition 条件
  91.    * @return int
  92.    */
  93.   public function total($tName$condition='') {
  94.     try {
  95.       if (!is_string($tName))
  96.         exit($this->getError(__FUNCTION____LINE__));
  97.       $tName = $this->formatTabName($tName);
  98.       $this->_sql = "SELECT COUNT(*) AS total FROM {$tName}" .
  99.       ($condition=='' ? '' : ' WHERE ' . $condition);
  100.       $re = $this->_db->query($this->_sql);
  101.       foreach ($re as $v) {
  102.         $total = $v['total'];
  103.       }
  104.       return (int)$total;
  105.     } catch (PDOException $e) {
  106.       exit($e->getMessage());
  107.     }
  108.   }
  109.   /**
  110.    * 数据库删除多条数据
  111.    * @param string $tName 表名
  112.    * @param string $field 依赖字段
  113.    * @param array $ids 删除数组
  114.    * @return int 受影响的行数
  115.    */
  116.   public function delMulti($tName$field$ids) {
  117.     try {
  118.       if (!is_string($tName) || !is_array($ids))
  119.         exit($this->getError(__FUNCTION____LINE__));
  120.       $delStr = '';
  121.       $tName = $this->formatTabName($tName);
  122.       $field = $this->formatTabName($field);
  123.       foreach ($ids as $v) {
  124.         $delStr .= $v . ',';
  125.       }
  126.       $delStr = rtrim($delStr',');
  127.       $this->_sql = "DELETE FROM {$tName} WHERE {$field} IN ({$delStr})";
  128.       $row = $this->_db->exec($this->_sql);
  129.       return $row;
  130.     } catch (PDOException $e) {
  131.       exit($e->getMessage());
  132.     }
  133.   }
  134.   /**
  135.    * 获取表格的最后主键(注:针对 INT 类型)
  136.    * @param string $tName 表名
  137.    * @return int
  138.    */
  139.   public function insertId($tName) {
  140.     try {
  141.       if (!is_string($tName))
  142.         exit($this->getError(__FUNCTION____LINE__));
  143.       $this->_sql = "SHOW TABLE STATUS LIKE '{$tName}'";
  144.       $result = $this->_db->query($this->_sql);
  145.       $insert_id = 0;
  146.       foreach ($result as $v) {
  147.         $insert_id = $v['Auto_increment'];
  148.       }
  149.       return (int)$insert_id;
  150.     } catch (PDOException $e) {
  151.       exit($e->getMessage());
  152.     }
  153.   }
  154.   /**
  155.    * 检查数据是否已经存在(依赖条件)
  156.    * @param string $tName 表名
  157.    * @param string $field 依赖的字段
  158.    * @return bool
  159.    */
  160.   public function exists($tName$condition) {
  161.     try {
  162.       if (!is_string($tName) || !is_string($condition))
  163.         exit($this->getError(__FUNCTION____LINE__));
  164.       $tName = $this->formatTabName($tName);
  165.       $this->_sql = "SELECT COUNT(*) AS total FROM {$tName} WHERE {$condition}";
  166.       $result = $this->_db->query($this->_sql);
  167.       foreach ($result as $v) {
  168.          $b = $v['total'];
  169.       }
  170.       if ($b) {
  171.         return true;
  172.       } else {
  173.         return false;
  174.       }
  175.     } catch (PDOException $e) {
  176.       exit($e->getMessage());
  177.     }
  178.   }
  179.   /**
  180.    * 检查数据是否已经存在(依赖 INT 主键)
  181.    * @param string $tName 表名
  182.    * @param string $primary 主键
  183.    * @param int $id 主键值
  184.    * @return bool
  185.    */
  186.   public function existsByPK($tName$primary$id) {
  187.     try {
  188.       if (!is_string($tName) || !is_string($primary)
  189.       || !is_int($id))
  190.         exit($this->getError(__FUNCTION____LINE__));
  191.       $tName = $this->formatTabName($tName);
  192.       $this->_sql = "SELECT COUNT(*) AS total FROM {$tName} WHERE {$primary} = "$id;
  193.       $result = $this->_db->query($this->_sql);
  194.       foreach ($result as $v) {
  195.          $b = $v['total'];
  196.       }
  197.       if ($b) {
  198.         return true;
  199.       } else {
  200.         return false;
  201.       }
  202.     } catch (PDOException $e) {
  203.       exit($e->getMessage());
  204.     }
  205.   }
  206.   /**
  207.    * 预处理删除(注:针对主键为 INT 类型,推荐使用)
  208.    * @param string $tName 表名
  209.    * @param string $primary 主键字段
  210.    * @param int or array or string $ids 如果是删除一条为 INT,多条为 array,删除一个范围为 string
  211.    * @return int 返回受影响的行数
  212.    */
  213.   public function delByPK($tName$primary$ids$mult=FALSE) {
  214.     try {
  215.       if (!is_string($tName) || !is_string($primary)
  216.       || (!is_int($ids) && !is_array($ids) && !is_string($ids))
  217.       || !is_bool($mult)) exit($this->getError(__FUNCTION____LINE__));
  218.       $tName = $this->formatTabName($tName);
  219.       $stmt = $this->_db->prepare("DELETE FROM {$tName} WHERE {$primary}=?");
  220.       if (!$mult) {
  221.         $stmt->bindParam(1, $ids);
  222.         $row = $stmt->execute();
  223.       } else {
  224.         if (is_array($ids)) {
  225.           $row = 0;
  226.           foreach ($ids as $v) {
  227.             $stmt->bindParam(1, $v);
  228.             if ($stmt->execute()) {
  229.               $row++;
  230.             }
  231.           }
  232.         } elseif (is_string($ids)) {
  233.           if (!strpos($ids'-'))
  234.             exit($this->getError(__FUNCTION____LINE__));
  235.           $split = explode('-'$ids);
  236.           if (count($split)!=2 || $split[0]>$split[1])
  237.             exit($this->getError(__FUNCTION____LINE__));
  238.           $i = null;
  239.           $count = $split[1]-$split[0]+1;
  240.           for ($i=0; $i<$count$i++) {
  241.             $idArr[$i] = $split[0]++;
  242.           }
  243.           $idStr = '';
  244.           foreach ($idArr as $id) {
  245.             $idStr .= $id . ',';
  246.           }
  247.           $idStr = rtrim($idStr',');
  248.           $this->_sql ="DELETE FROM {$tName} WHERE {$primary} in ({$idStr})";
  249.           $row = $this->_db->exec($this->_sql);
  250.         }
  251.       }
  252.       return $row;
  253.     } catch (PDOException $e) {
  254.       exit($e->getMessage());
  255.     }
  256.   }
  257.   /**
  258.    * 返回单个字段数据或单条记录
  259.    * @param string $tName 表名
  260.    * @param string $condition 条件
  261.    * @param string or array $fields 返回的字段,默认是*
  262.    * @return string || array
  263.    */
  264.   public function getRow($tName$condition=''$fields="*") {
  265.     try {
  266.       if (!is_string($tName) || !is_string($condition)
  267.       || !is_string($fields) || emptyempty($fields))
  268.          exit($this->getError(__FUNCTION____LINE__));
  269.       $tName = $this->formatTabName($tName);
  270.       $this->_sql = "SELECT {$fields} FROM {$tName} ";
  271.       $this->_sql .= ($condition=='' ? '' : "WHERE {$condition}") . " LIMIT 1";
  272.       $sth = $this->_db->prepare($this->_sql);
  273.       $sth->execute();
  274.       $result = $sth->fetch(PDO::FETCH_ASSOC);
  275.       if ($fields === '*') {
  276.         return $result;
  277.       } else {
  278.         return $result[$fields];
  279.       }
  280.     } catch (PDOException $e) {
  281.       exit($e->getMessage());
  282.     }
  283.   }
  284.   /**
  285.    * 返回多条数据
  286.    * @param string $tName 表名
  287.    * @param string $fields 返回字段,默认为*
  288.    * @param string $condition 条件
  289.    * @param string $order 排序
  290.    * @param string $limit 显示个数
  291.    * @return PDOStatement
  292.    */
  293.   public function getAll($tName$fields='*'$condition=''$order=''$limit='') {
  294.     try {
  295.       if (!is_string($tName) || !is_string($fields)
  296.       || !is_string($condition) || !is_string($order)
  297.       || !is_string($limit))
  298.         exit($this->getError(__FUNCTION____LINE__));
  299.       $tName = $this->formatTabName($tName);
  300.       $fields = ($fields=='*' || $fields=='') ? '*' : $fields;
  301.       $condition = $condition=='' ? '' : " WHERE "$condition ;
  302.       $order = $order=='' ? '' : " ORDER BY "$order;
  303.       $limit = $limit=='' ? '' : " LIMIT "$limit;
  304.       $this->_sql = "SELECT {$fields} FROM {$tName} {$condition} {$order} {$limit}";
  305.       $sth = $this->_db->prepare($this->_sql);
  306.       $sth->execute();
  307.       $result = $sth->fetchAll(PDO::FETCH_ASSOC);
  308.       return $result;
  309.     } catch (PDOException $e) {
  310.       exit($e->getMessage());
  311.     }
  312.   }
  313.   /**
  314.    * 格式化数组(表结构和值)
  315.    * @param array $field
  316.    * @param bool $isField
  317.    * @return string
  318.    */
  319.   private function formatArr($field$isField=TRUE) {
  320.     if (!is_array($field)) exit($this->getError(__FUNCTION____LINE__));
  321.     $fields = '';
  322.     if ($isField) {
  323.       foreach ($field as $v) {
  324.         $fields .= '`'.$v.'`,';
  325.       }
  326.     } else {
  327.       foreach ($field as $v) {
  328.         $fields .= '\''.$v.'\''.',';
  329.       }
  330.     }
  331.     $fields = rtrim($fields',');
  332.     return $fields;
  333.   }
  334.   /**
  335.    * 格式化问号
  336.    * @param int $count 数量
  337.    * @return string 返回格式化后的字符串
  338.    */
  339.   private function formatMark($count) {
  340.     $str = '';
  341.     if (!is_int($count)) exit($this->getError(__FUNCTION____LINE__));
  342.     if ($count==1) return '?';
  343.     for ($i=0; $i<$count$i++) {
  344.       $str .= '?,';
  345.     }
  346.     return rtrim($str',');
  347.   }
  348.   /**
  349.    * 错误提示
  350.    * @param string $fun
  351.    * @return string
  352.    */
  353.   private function getError($fun$line) {
  354.     return __CLASS__ . '->' . $fun . '() line<font color="red">'$line .'</font> ERROR!';
  355.   }
  356.   /**
  357.    * 处理表名
  358.    * @param string $tName
  359.    * @return string
  360.    */
  361.   private function formatTabName($tName) {
  362.     return '`' . trim($tName'`') . '`';
  363.   }
  364.   /**
  365.    * 析构方法
  366.    */
  367.   public function __destruct() {
  368.     $this->_db = null;
  369.   }
  370. }

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录