php实现的pdo公共类定义与用法示例


Posted in PHP onJuly 19, 2017

本文实例讲述了php实现的pdo公共类定义与用法。分享给大家供大家参考,具体如下:

db.class.php :

<?php
class db extends \PDO {
  private static $_instance = null;
  protected $dbName = '';
  protected $dsn;
  protected $dbh;
  public function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset='utf8') {
    try {
      $this->dsn = 'mysql:host=' . $dbHost . ';dbname=' . $dbName;
      $this->dbh = new \PDO($this->dsn, $dbUser, $dbPasswd);
      $this->dbh->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
      $this->dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
      $this->dbh->exec('SET character_set_connection='.$dbCharset.';SET character_set_client='.$dbCharset.';SET character_set_results='.$dbCharset);
    } catch (Exception $e) {
      $this->outputError($e->getMessage()); 
    }
  }
  public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset='utf8') {
    if (self::$_instance === null) {
      self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
    }
    return self::$_instance;
  }
  public function fetchAll($sql, $params = array()) {
    try {
      $stm = $this->dbh->prepare($sql);
      if ($stm && $stm->execute($params)) {
        return $stm->fetchAll(\PDO::FETCH_ASSOC);
      }
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function fetchOne($sql, $params = array()) {
    try {
      $result = false;
      $stm = $this->dbh->prepare($sql);
      if ($stm && $stm->execute($params)) {
        $result = $stm->fetch(\PDO::FETCH_ASSOC);
      }
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function fetchColumn($sql, $params = array()) {
    $result = '';
    try {
      $stm = $this->dbh->prepare($sql);
      if ($stm && $stm->execute($params)) {
        $result = $stm->fetchColumn();
      }
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function insert($table, $params = array(), $returnLastId = true) {
    $_implode_field = '';
    $fields = array_keys($params);
    $_implode_field = implode(',', $fields);
    $_implode_value = '';
    foreach ($fields as $value) {
      $_implode_value .= ':'. $value.',';
    }
    $_implode_value = trim($_implode_value, ',');
    $sql = 'INSERT INTO ' . $table . '(' . $_implode_field . ') VALUES ('.$_implode_value.')';
    try {
      $stm = $this->dbh->prepare($sql);
      $result = $stm->execute($params);
      if ( $returnLastId ) {
        $result = $this->dbh->lastInsertId();
      }
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function update($table, $params = array(), $where = null) {
    $_implode_field = '';
    $_implode_field_arr = array();
    if ( empty($where) ) {
      return false;
    }
    $fields = array_keys($params);
    foreach ($fields as $key) {
      $_implode_field_arr[] = $key . '=' . ':'.$key;
    }
    $_implode_field = implode(',', $_implode_field_arr);
    $sql = 'UPDATE ' . $table . ' SET ' . $_implode_field . ' WHERE ' . $where;
    try {
      $stm = $this->dbh->prepare($sql);
      $result = $stm->execute($params);
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function delete($sql, $params = array()) {
    try {
      $stm = $this->dbh->prepare($sql);
      $result = $stm->execute($params);
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  public function exec($sql, $params = array()) {
    try {
      $stm = $this->dbh->prepare($sql);
      $result = $stm->execute($params);
      return $result;
    } catch (Exception $e) {
      $this->outputError($e->getMessage());
    }
  }
  private function outputError($strErrMsg) {
    throw new Exception("MySQL Error: " . $strErrMsg);
  }
  public function __destruct() {
    $this->dbh = null;
  }
}

实例:

<?php
require_once './db.class.php';
$pdo = db::getInstance('127.0.0.1', 'root', '111111', 'php_cms');
$sql = "select id, title1 from cms_wz where id = :id limit 1";
$parame = array('id' => 12,);
$res = $pdo->fetchOne($sql, $parame);
var_dump($res);
$sql = 'SELECT * FROM cms_link';
$result = $db->fetchAll($sql);
print_r($result);
//查询记录数量
$sql = 'SELECT COUNT(*) FROM cms_link';
$count = $db->fetchColumn($sql);
echo $count;
$data = array(
  'siteid' => 1,
  'linktype' => 1,
  'name' => 'google',
  'url' => 'http://www.google.com',
  'listorder' => 0,
  'elite' => 0,
  'passed' => 1,
  'addtime' => time()
  );
$lastInsertId = $db->insert('cms_link', $data);
echo $lastInsertId;
//用 try
 try {
     $result = $pdo->insert('news', $essay);
   } catch (Exception $e) {
     error_log($e->getMessage());
     error_log($e->getMessage() . ' in ' . __FILE__ . ' on line ' . __LINE__);
     saveLog('url文章 : ' . $essay['link'] . '  数据插入失败<br>');
     continue;
   }
$data = array(
  'siteid' => 1,
  'linktype' => 1,
  'name' => 'google',
  'url' => 'http://www.google.com',
  'listorder' => 0,
  'elite' => 0,
  'passed' => 1,
  'addtime' => time()
  );
$db->insert('cms_link', $data);
$sql = 'DELETE FROM cms_link WHERE linkid=4';
$result = $db->delete($sql);
var_dump($result);

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

PHP 相关文章推荐
通过PHP的内置函数,通过DES算法对数据加密和解密
Jun 21 PHP
PHP多例模式介绍
Jun 24 PHP
PHP判断指定时间段的2个方法
Mar 14 PHP
PHP 面向对象程序设计(oop)学习笔记 (五) - PHP 命名空间
Jun 12 PHP
Linux中为php配置伪静态
Dec 17 PHP
PHP获取QQ达人QQ信息的方法
Mar 05 PHP
ThinkPHP 3.2 版本升级了哪些内容
Mar 05 PHP
php通过分类列表产生分类树数组的方法
Apr 20 PHP
CodeIgniter 完美解决URL含有中文字符串
May 13 PHP
PHP使用FFmpeg获取视频播放总时长与码率等信息
Sep 13 PHP
PHP+Apache环境中如何隐藏Apache版本
Nov 24 PHP
JS中彻底删除JSON对象组成的数组中的元素
Sep 22 PHP
PHP多进程编程实例详解
Jul 19 #PHP
PHP preg_match实现正则表达式匹配功能【输出是否匹配及匹配值】
Jul 19 #PHP
php实现生成code128条形码的方法详解
Jul 19 #PHP
php-beanstalkd消息队列类实例分享
Jul 19 #PHP
php+ajax实现异步上传文件或图片功能
Jul 18 #PHP
Joomla框架实现字符串截取的方法示例
Jul 18 #PHP
PHP新特性详解之命名空间、性状与生成器
Jul 18 #PHP
You might like
PHP错误提示的关闭方法详解
2013/06/23 PHP
php使用gzip压缩传输js和css文件的方法
2015/07/29 PHP
使用PHP+AJAX让WordPress动态加载文章的教程
2015/12/11 PHP
Thinkphp5框架使用validate实现验证功能的方法
2019/08/27 PHP
表单提交时自动复制内容到剪贴板的js代码
2007/03/16 Javascript
List Installed Hot Fixes
2007/06/12 Javascript
基于Asp.net与Javascript控制的日期控件
2010/05/22 Javascript
JavaScript中使用构造函数实现继承的代码
2010/08/12 Javascript
javascript学习笔记(三) String 字符串类型介绍
2012/06/19 Javascript
js实现的标题栏新消息闪烁提示效果
2014/06/06 Javascript
jquery实现鼠标经过显示下划线的渐变下拉菜单效果代码
2015/08/24 Javascript
Bootstrap项目实战之首页内容介绍(全)
2016/04/25 Javascript
浅析JavaScript 箭头函数 generator Date JSON
2016/05/23 Javascript
JavaScript高仿支付宝倒计时页面及代码实现
2016/10/21 Javascript
Vue.js基础指令实例讲解(各种数据绑定、表单渲染大总结)
2017/07/03 Javascript
详解无限滚动插件vue-infinite-scroll源码解析
2019/05/12 Javascript
js实现纯前端压缩图片
2020/11/16 Javascript
[01:43]倾听DOTA2英雄之声 魅惑魔女国服配音鉴赏
2013/06/06 DOTA
python实现SMTP邮件发送功能
2020/06/16 Python
Flask框架的学习指南之用户登录管理
2016/11/20 Python
如何基于python操作json文件获取内容
2019/12/24 Python
python numpy数组复制使用实例解析
2020/01/10 Python
Python3实现打印任意宽度的菱形代码
2020/04/12 Python
关于jupyter打开之后不能直接跳转到浏览器的解决方式
2020/04/13 Python
Python flask框架端口失效解决方案
2020/06/04 Python
解决pytorch 交叉熵损失输出为负数的问题
2020/07/07 Python
Django中Aggregation聚合的基本使用方法
2020/07/09 Python
Python使用sys.exc_info()方法获取异常信息
2020/07/23 Python
集团公司党的群众路线教育实践活动工作总结
2014/03/03 职场文书
一年级学生评语大全
2014/04/21 职场文书
公司节能减排倡议书
2014/05/14 职场文书
合作协议书范文
2014/08/20 职场文书
体育教师个人工作总结
2015/02/09 职场文书
关于召开会议的通知
2015/04/15 职场文书
MySQL中CURRENT_TIMESTAMP的使用方式
2021/11/27 MySQL
Vue Element plus使用方法梳理
2022/12/24 Vue.js