侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

PHP的PDO常用类库实例分析

php  /  管理员 发布于 7年前   211

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

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

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 数据库操作类

_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'. $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程序设计有所帮助。

您可能感兴趣的文章:

  • 全新的PDO数据库操作类php版(仅适用Mysql)
  • PHP实现PDO的mysql数据库操作类
  • php基于PDO实现功能强大的MYSQL封装类实例
  • PHP用PDO如何封装简单易用的DB类详解
  • PHP基于单例模式编写PDO类的方法
  • PHP基于pdo的数据库操作类【可支持mysql、sqlserver及oracle】
  • PHP封装的PDO数据库操作类实例
  • PHP基于PDO实现的SQLite操作类【包含增删改查及事务等操作】
  • PHP封装的数据库模型Model类完整示例【基于PDO】
  • php封装的pdo数据库操作工具类与用法示例


  • 上一条:
    PHP+Ajax实现无刷新分页实例详解(附demo源码下载)
    下一条:
    PHP安全下载文件的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客