热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PHP的PDO常用类库实例分析

这篇文章主要介绍了PHP的PDO常用类库,结合实例形式分析了PDO类库常见的连接,初始化及增删改查等操作技巧,需要的朋友可以参考下
本文实例讲述了PHP的PDO常用类库。分享给大家供大家参考,具体如下:

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

<&#63;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;
  }
}
&#63;>

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

<&#63;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=='' &#63; '' : ' 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}=&#63;");
      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=='' &#63; '' : "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=='') &#63; '*' : $fields;
      $cOndition= $cOndition=='' &#63; '' : " WHERE ". $condition ;
      $order = $order=='' &#63; '' : " ORDER BY ". $order;
      $limit = $limit=='' &#63; '' : " 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 '&#63;';
    for ($i=0; $i<$count; $i++) {
      $str .= '&#63;,';
    }
    return rtrim($str, ',');
  }
  /**
   * 错误提示
   * @param string $fun
   * @return string
   */
  private function getError($fun, $line) {
    return __CLASS__ . '->' . $fun . '() line'. $line .' ERROR!';
  }
  /**
   * 处理表名
   * @param string $tName
   * @return string
   */
  private function formatTabName($tName) {
    return '`' . trim($tName, '`') . '`';
  }
  /**
   * 析构方法
   */
  public function __destruct() {
    $this->_db = null;
  }
}

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php curl用法总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

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

推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文由编程笔记小编整理,介绍了PHP中的MySQL函数库及其常用函数,包括mysql_connect、mysql_error、mysql_select_db、mysql_query、mysql_affected_row、mysql_close等。希望对读者有一定的参考价值。 ... [详细]
  • 推荐一个ASP的内容管理框架(ASP Nuke)的优势和适用场景
    本文推荐了一个ASP的内容管理框架ASP Nuke,并介绍了其主要功能和特点。ASP Nuke支持文章新闻管理、投票、论坛等主要内容,并可以自定义模块。最新版本为0.8,虽然目前仍处于Alpha状态,但作者表示会继续更新完善。文章还分析了使用ASP的原因,包括ASP相对较小、易于部署和较简单等优势,适用于建立门户、网站的组织和小公司等场景。 ... [详细]
  • 本文介绍了如何在MySQL中将零值替换为先前的非零值的方法,包括使用内联查询和更新查询。同时还提供了选择正确值的方法。 ... [详细]
  • 在数据分析工作中,我们通常会遇到这样的问题,一个业务部门由若干业务组构成,需要筛选出每个业务组里业绩前N名的业务员。这其实是一个分组排序的 ... [详细]
  • Oracle Database 10g许可授予信息及高级功能详解
    本文介绍了Oracle Database 10g许可授予信息及其中的高级功能,包括数据库优化数据包、SQL访问指导、SQL优化指导、SQL优化集和重组对象。同时提供了详细说明,指导用户在Oracle Database 10g中如何使用这些功能。 ... [详细]
  • Metasploit攻击渗透实践
    本文介绍了Metasploit攻击渗透实践的内容和要求,包括主动攻击、针对浏览器和客户端的攻击,以及成功应用辅助模块的实践过程。其中涉及使用Hydra在不知道密码的情况下攻击metsploit2靶机获取密码,以及攻击浏览器中的tomcat服务的具体步骤。同时还讲解了爆破密码的方法和设置攻击目标主机的相关参数。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 本文介绍了Oracle数据库中tnsnames.ora文件的作用和配置方法。tnsnames.ora文件在数据库启动过程中会被读取,用于解析LOCAL_LISTENER,并且与侦听无关。文章还提供了配置LOCAL_LISTENER和1522端口的示例,并展示了listener.ora文件的内容。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • Oracle分析函数first_value()和last_value()的用法及原理
    本文介绍了Oracle分析函数first_value()和last_value()的用法和原理,以及在查询销售记录日期和部门中的应用。通过示例和解释,详细说明了first_value()和last_value()的功能和不同之处。同时,对于last_value()的结果出现不一样的情况进行了解释,并提供了理解last_value()默认统计范围的方法。该文对于使用Oracle分析函数的开发人员和数据库管理员具有参考价值。 ... [详细]
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • 解决VS写C#项目导入MySQL数据源报错“You have a usable connection already”问题的正确方法
    本文介绍了在VS写C#项目导入MySQL数据源时出现报错“You have a usable connection already”的问题,并给出了正确的解决方法。详细描述了问题的出现情况和报错信息,并提供了解决该问题的步骤和注意事项。 ... [详细]
author-avatar
欠你的情意
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有