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

 更新时间:2017年07月19日 12:08:38   作者:3wlog  
这篇文章主要介绍了php实现的pdo公共类定义与用法,结合具体实例形式分析了php实现的pdo操作类定义及查询、插入等使用技巧,需要的朋友可以参考下

本文实例讲述了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基于pdo操作数据库技巧总结》、《php+Oracle数据库程序设计技巧总结》、《PHP+MongoDB数据库操作技巧大全》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

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

相关文章

  • PHP试题之RCEService正则回溯解答

    PHP试题之RCEService正则回溯解答

    这篇文章主要为大家介绍了PHP试题之RCEService正则回溯解答,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪
    2022-04-04
  • 用穿越火线快速入门php面向对象

    用穿越火线快速入门php面向对象

    php目前已经成为国内的主流web developer的首选开发语言,其强大的面向对象容易使初学者找不到思绪,一头雾水,借助此文希望对初学者有所帮助,假设Crossfire用php来开发
    2012-02-02
  • PHP COOKIE及时生效的方法介绍

    PHP COOKIE及时生效的方法介绍

    本篇文章主要是对PHP中COOKIE及时生效的方法进行了介绍,需要的朋友可以过来参考下,希望对大家有所帮助
    2014-02-02
  • phpmail类发送邮件函数代码

    phpmail类发送邮件函数代码

    前天要给网站做一个小功能,就是在用户留言的时候发邮件通知管理员。我们都知道在PHP里有一个mail函数,但是要求服务器要有邮件服务器的功能,比如简单的SMTP或者POP3。但是,如果我们的服务器没有这种功能,那么怎么办呢
    2012-02-02
  • PHP微信支付结果通知与回调策略分析

    PHP微信支付结果通知与回调策略分析

    这篇文章主要介绍了PHP微信支付结果通知与回调策略,结合实例形式分析了php微信支付结果的回调处理相关操作技巧,需要的朋友可以参考下
    2019-01-01
  • PHP+MySQL实现模糊查询员工信息功能示例

    PHP+MySQL实现模糊查询员工信息功能示例

    这篇文章主要介绍了PHP+MySQL实现模糊查询员工信息功能,结合实例形式分析了php连接mysql数据库及使用like语句进行模糊查询与显示相关操作技巧,需要的朋友可以参考下
    2018-06-06
  • php图片处理函数获取类型及扩展名实例

    php图片处理函数获取类型及扩展名实例

    这篇文章主要介绍了php图片处理函数获取类型及扩展名的方法,包括image2wbmp、image_type_to_extension、image_type_to_mime_type等函数的具体使用,具有不错的借鉴与学习价值,需要的朋友可以参考下
    2014-11-11
  • rephactor 优秀的PHP的重构工具

    rephactor 优秀的PHP的重构工具

    从PHP5开始,提供了强大的面向对象功能。使得PHP能够完全按设计模式编程。
    2011-06-06
  • PHP中的输出缓冲控制详解

    PHP中的输出缓冲控制详解

    这篇文章主要介绍了PHP中的输出缓冲控制的相关资料,帮助大家更好的理解和学习使用PHP,感兴趣的朋友可以了解下
    2021-04-04
  • php仿微信红包分配算法的实现方法

    php仿微信红包分配算法的实现方法

    这篇文章主要介绍了php仿微信红包分配算法的实现方法,涉及简单的php数学运算与字符串操作相关技巧,需要的朋友可以参考下
    2016-05-05

最新评论