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速度全攻略
Oct 09 PHP
php shell超强免杀、减少体积工具实现代码
Oct 16 PHP
Php中使用Select 查询语句的实例
Feb 19 PHP
免费的ip数据库淘宝IP地址库简介和PHP调用实例
Apr 08 PHP
php 过滤英文标点符号及过滤中文标点符号代码
Jun 12 PHP
php导入excel文件到mysql数据库的方法
Jan 14 PHP
typecho插件编写教程(六):调用接口
May 28 PHP
Laravel 5.4重新登录实现跳转到登录前页面的原理和方法
Jul 13 PHP
在Laravel5.6中使用Swoole的协程数据库查询
Jun 15 PHP
vmware linux系统安装最新的php7图解
Apr 14 PHP
PHP实现微信提现功能(微信商城)
Nov 21 PHP
PHP safe_mode开启对于PHP系统函数有什么影响
Nov 10 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
也谈截取首页新闻 - 范例
2006/10/09 PHP
简单的页面缓冲技术
2006/10/09 PHP
php 数据库字段复用的基本原理与示例
2011/07/22 PHP
PHP使用mysql_fetch_row查询获得数据行列表的方法
2015/03/18 PHP
php批量删除操作(数据访问)
2017/05/23 PHP
PHP mysqli事务操作常用方法分析
2017/07/22 PHP
PHP结合Vue实现滚动底部加载效果
2017/12/17 PHP
Javascript SHA-1:Secure Hash Algorithm
2006/12/20 Javascript
理解Javascript_06_理解对象的创建过程
2010/10/15 Javascript
Jquery实现的tab效果可以指定默认显示第几页
2013/10/16 Javascript
js数组的操作指南
2014/12/28 Javascript
JavaScript精炼之构造函数 Constructor及Constructor属性详解
2015/11/05 Javascript
JavaScript中的splice方法用法详解
2016/07/20 Javascript
node.js + socket.io 实现点对点随机匹配聊天
2017/06/30 Javascript
Bootstrap弹出框之自定义悬停框标题、内容和样式示例代码
2017/07/11 Javascript
JQuery实现table中tr上移下移的示例(超简单)
2018/01/08 jQuery
Vue实现按钮旋转和移动位置的实例代码
2018/08/09 Javascript
js实现删除li标签一行内容
2019/04/16 Javascript
ES6知识点整理之Proxy的应用实例详解
2019/04/16 Javascript
基于js实现数组相邻元素上移下移
2020/05/19 Javascript
Python 列表理解及使用方法
2017/10/27 Python
Python探索之SocketServer详解
2017/10/28 Python
python实点云分割k-means(sklearn)详解
2020/05/28 Python
Python中Selenium模块的使用详解
2020/10/09 Python
使用HTML5 Canvas为图片填充颜色和纹理的教程
2016/03/21 HTML / CSS
美国著名手表网站:Timepiece
2017/11/15 全球购物
芬兰设计商店美国:Finnish Design Shop US
2019/03/25 全球购物
什么是TCP/IP
2014/07/27 面试题
介绍一下Python中webbrowser的用法
2013/05/07 面试题
应届大学生求职信
2013/12/01 职场文书
社会实践的活动方案
2014/08/22 职场文书
红色旅游心得体会
2014/09/03 职场文书
2015年推广普通话演讲稿
2015/03/20 职场文书
导游词之岳阳楼
2019/09/25 职场文书
详解CSS中的特指度和层叠问题
2021/07/15 HTML / CSS
mysql如何查询连续记录
2022/05/11 MySQL