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生成UTF8文件的方法
May 15 PHP
一个PHP的远程图片抓取函数分享
Sep 25 PHP
ThinkPHP3.1新特性之Action参数绑定
Jun 19 PHP
php实现的九九乘法口诀表简洁版
Jul 28 PHP
修改destoon会员公司的伪静态中的com目录的方法
Aug 21 PHP
PHP跨平台获取服务器IP地址自定义函数分享
Dec 29 PHP
PHP使用Pthread实现的多线程操作实例
Nov 14 PHP
PHP模板引擎Smarty自定义变量调解器用法
Apr 11 PHP
thinkphp3.2嵌入百度编辑器ueditor的实例代码
Jul 13 PHP
php判断电子邮件是否正确方法
Dec 04 PHP
php中file_get_contents()函数用法实例
Feb 21 PHP
详解PHP 二维数组排序保持键名不变
Mar 06 PHP
PHP实现的Redis多库选择功能单例类
Jul 27 #PHP
PHP策略模式定义与用法示例
Jul 27 #PHP
windows下的WAMP环境搭建图文教程(推荐)
Jul 27 #PHP
php表单文件iframe异步上传实例讲解
Jul 26 #PHP
php实现的统计字数函数定义与使用示例
Jul 26 #PHP
PHP SFTP实现上传下载功能
Jul 26 #PHP
Windows平台实现PHP连接SQL Server2008的方法
Jul 26 #PHP
You might like
按上下级层次关系输出内容的PHP代码
2010/07/17 PHP
基于PHP的cURL快速入门教程 (小偷采集程序)
2011/06/02 PHP
PHP CURL模拟登录新浪微博抓取页面内容 基于EaglePHP框架开发
2012/01/16 PHP
CodeIgniter生成静态页的方法
2016/05/17 PHP
php文件类型MIME对照表(比较全)
2016/10/07 PHP
PHP常用header头定义代码示例汇总
2020/08/29 PHP
js event事件的传递与冒泡处理
2009/12/06 Javascript
服务器端的JavaScript脚本 Node.js 使用入门
2012/03/07 Javascript
JavaScript中的运算符种类及其规则介绍
2013/09/26 Javascript
jQuery on方法传递参数示例
2014/12/09 Javascript
jQuery对html元素的取值与赋值实例详解
2015/12/18 Javascript
基于JS实现密码框(password)中显示文字提示功能代码
2016/05/27 Javascript
详解基于webpack搭建react运行环境
2017/06/01 Javascript
jQuery鼠标移动图片上实现放大效果
2017/06/25 jQuery
JS实现简单的选择题测评系统代码思路详解(demo)
2017/09/03 Javascript
基于vue2的canvas时钟倒计时组件步骤解析
2018/11/05 Javascript
Vue中watch、computed、updated三者的区别及用法
2020/07/27 Javascript
wxPython窗口中文乱码解决方法
2014/10/11 Python
Python 数据结构之旋转链表
2017/02/25 Python
python下os模块强大的重命名方法renames详解
2017/03/07 Python
Python 基础之字符串string详解及实例
2017/04/01 Python
python基于plotly实现画饼状图代码实例
2019/12/16 Python
Python图像处理库PIL的ImageEnhance模块使用介绍
2020/02/26 Python
python能否java成为主流语言吗
2020/06/22 Python
python 爬取百度文库并下载(免费文章限定)
2020/12/04 Python
CSS3常用的几种颜色渐变模式总结
2016/11/18 HTML / CSS
英国性感内衣和睡衣品牌:Bluebella
2018/01/26 全球购物
加拿大时装零售商:Influence U
2018/12/22 全球购物
报考公务员诚信承诺书
2014/08/29 职场文书
邓小平理论心得体会
2014/09/09 职场文书
2014年学习全国道德模范事迹思想汇报
2014/09/15 职场文书
代领报检证委托书范本
2014/10/11 职场文书
第28个世界无烟日活动总结
2015/02/10 职场文书
互联网的下一个风口:新的独角兽将诞生
2019/08/02 职场文书
python 进阶学习之python装饰器小结
2021/09/04 Python
MySQL 数据类型详情
2021/11/11 MySQL