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 相关文章推荐
echo, print, printf 和 sprintf 区别
Dec 06 PHP
Windows下XDebug 手工配置与使用说明
Jul 11 PHP
ThinkPHP3.0略缩图不能保存到子目录的解决方法
Sep 30 PHP
php的POSIX 函数以及进程测试的深入分析
Jun 03 PHP
基于simple_html_dom的使用小结
Jul 01 PHP
PHP变量内存分配问题记录整理
Nov 27 PHP
PHP 字符串长度判断效率更高的方法
Mar 02 PHP
PHP获取浏览器信息类和客户端地理位置的2个方法
Apr 24 PHP
php专用数组排序类ArraySortUtil用法实例
Apr 03 PHP
php curl 上传文件代码实例
Apr 27 PHP
Yii2实现跨mysql数据库关联查询排序功能代码
Feb 10 PHP
thinkphp Apache配置重启Apache1 restart 出错解决办法
Feb 15 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
松下Panasonic RF-B65电路分析
2021/03/02 无线电
随时给自己贴的图片加文字的php代码
2007/03/08 PHP
php模板之Phpbean的目录结构
2008/01/10 PHP
PHP使用SOAP调用.net的WebService数据
2013/11/12 PHP
php中3种方法删除字符串中间的空格
2014/03/10 PHP
如何写php守护进程(Daemon)
2015/12/30 PHP
php实现xml与json之间的相互转换功能实例
2016/07/07 PHP
Windows平台实现PHP连接SQL Server2008的方法
2017/07/26 PHP
Prototype1.6 JS 官方下载地址
2007/11/30 Javascript
简单的Jquery遮罩层代码实例
2013/11/14 Javascript
原生js仿jq判断当前浏览器是否为ie,精确到ie6~8
2014/08/30 Javascript
node.js中的http.response.getHeader方法使用说明
2014/12/14 Javascript
如何编写高质量JS代码
2014/12/28 Javascript
理解JavaScript的变量的入门教程
2015/07/07 Javascript
14款经典网页图片和文字特效的jQuery插件-前端开发必备
2015/08/25 Javascript
node.js入门实例helloworld详解
2015/12/23 Javascript
微信小程序实战之上拉(分页加载)效果(2)
2017/04/17 Javascript
Javascript中的async awai的用法
2017/05/17 Javascript
移动端效果之IndexList详解
2017/10/20 Javascript
python 与GO中操作slice,list的方式实例代码
2017/03/20 Python
python 通过字符串调用对象属性或方法的实例讲解
2018/04/21 Python
python实现傅里叶级数展开的实现
2018/07/21 Python
python实现字符串和字典的转换
2018/09/29 Python
Python OpenCV利用笔记本摄像头实现人脸检测
2020/08/20 Python
keras的ImageDataGenerator和flow()的用法说明
2020/07/03 Python
Python 解析简单的XML数据
2020/07/24 Python
方太官方网上商城:销售方太抽油烟机、燃气灶、消毒柜等
2017/01/17 全球购物
美国珠宝店:Helzberg Diamonds
2018/10/24 全球购物
英国婴儿及儿童产品商店:TigerParrot
2019/03/04 全球购物
说出你对remoting 和webservice的理解和应用
2014/06/08 面试题
小学教师自我鉴定
2013/11/07 职场文书
大学本科毕业生求职信范文
2013/12/18 职场文书
心理健康日活动总结
2014/05/08 职场文书
2015年度信用社工作总结
2015/05/04 职场文书
nginx配置proxy_pass中url末尾带/与不带/的区别详解
2021/03/31 Servers
浅谈Redis跟MySQL的双写问题解决方案
2022/02/24 Redis