Yaf框架封装的MySQL数据库操作示例


Posted in PHP onMarch 06, 2019

本文实例讲述了Yaf框架封装的MySQL数据库操作。分享给大家供大家参考,具体如下:

Yaf封装DB简单操作

介绍

因为Yaf是一个纯天然的MVC阔架,本人还在贝锐的时候就和主管一起用Yaf框架去重构了向日葵的网站端,到后面,Yaf也逐渐应用到了其他项目上,但是Yaf是没有带DB类库的,所以本人也共享下最近封装的代码!

代码

使用PDO封装MySQL操作

class Db_Mysql
{
  private $_options = array();
  private $db;
  private $statement;
  private $_fetchMode = 2;
  /**
   * 构造函数
   *
   * @param string $host
   * @param string $username
   * @param string $password
   * @param string $dbname
   * @param string $charset
   */
  private function __construct($host, $username, $password, $dbname, $charset)
  {
    //初始化数据连接
    try {
      $dns = 'mysql:dbname=' . $dbname . ';host=' . $host;
      $this->db = new PDO($dns, $username, $password, array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_AUTOCOMMIT => 1));
      $this->db->query('SET NAMES ' . $charset);
    } catch (PDOException $e) {
      echo header("Content-type: text/html; charset=utf-8");
      echo '<pre />';
      echo '<b>Connection failed:</b>' . $e->getMessage();
      die;
    }
  }
  /**
   * 调用初始化MYSQL连接
   *
   * @param string $config
   * @return Aomp_Db_Mysql
   */
  static public function getInstance($config = '')
  {
    $host = $config->host;
    $username = $config->username;
    $password = $config->password;
    $dbname = $config->dbname;
    $charset = $config->charset;
    $db = new self($host, $username, $password, $dbname, $charset);
    return $db;
  }
  /**
   * 获取多条数据
   *
   * @param string $sql
   * @param array $bind
   * @param string $fetchMode
   * @return multitype:
   */
  public function fetchAll($sql, $bind = array(), $fetchMode = null)
  {
    if($fetchMode === NULL){
      $fetchMode = $this->_fetchMode;
    }
    $stmt = $this->query($sql, $bind);
    $res = $stmt->fetchAll($fetchMode);
    return $res;
  }
  /**
   * 获取单条数据
   *
   * @param string $sql
   * @param array $bind
   * @param string $fetchMode
   * @return mixed
   */
  public function fetchRow($sql, array $bind = array(), $fetchMode = null)
  {
    if ($fetchMode === null) {
      $fetchMode = $this->_fetchMode;
    }
    $stmt = $this->query($sql, $bind);
    $result = $stmt->fetch($fetchMode);
    return $result;
  }
  /**
   * 获取统计或者ID
   *
   * @param string $sql
   * @param array $bind
   * @return string
   */
  public function fetchOne($sql, array $bind = array())
  {
    $stmt = $this->query($sql, $bind);
    $res = $stmt->fetchColumn(0);
    return $res;
  }
  /**
   * 增加
   *
   * @param string $table
   * @param array $bind
   * @return number
   */
  public function insert($table, array $bind)
  {
    $cols = array();
    $vals = array();
    foreach ($bind as $k => $v) {
      $cols[] = '`' . $k . '`';
      $vals[] = ':' . $k;
      unset($bind[$k]);
      $bind[':' . $k] = $v;
    }
    $sql = 'INSERT INTO '
      . $table
      . ' (' . implode(',', $cols) . ') '
      . 'VALUES (' . implode(',', $vals) . ')';
    $stmt = $this->query($sql, $bind);
    $res = $stmt->rowCount();
    return $res;
  }
  /**
   * 删除
   *
   * @param string $table
   * @param string $where
   * @return boolean
   */
  public function delete($table, $where = '')
  {
    $where = $this->_whereExpr($where);
    $sql = 'DELETE FROM '
      . $table
      . ($where ? ' WHERE ' .$where : '');
    $stmt = $this->query($sql);
    $res = $stmt->rowCount();
    return $res;
  }
  /**
   * 修改
   *
   * @param string $table
   * @param array $bind
   * @param string $where
   * @return boolean
   */
  public function update($table, array $bind, $where = '')
  {
    $set = array();
    foreach ($bind as $k => $v) {
      $bind[':' . $k] = $v;
      $v = ':' . $k;
      $set[] = $k . ' = ' . $v;
      unset($bind[$k]);
    }
    $where = $this->_whereExpr($where);
    $sql = 'UPDATE '
      . $table
      . ' SET ' . implode(',', $set)
      . (($where) ? ' WHERE ' . $where : '');
    $stmt = $this->query($sql, $bind);
    $res = $stmt->rowCount();
    return $res;
  }
  /**
   * 获取新增ID
   *
   * @param string $tableName
   * @param string $primaryKey
   * @return string
   */
  public function lastInsertId()
  {
    return (string) $this->db->lastInsertId();
  }
  public function query($sql, $bind = array())
  {
    if(!is_array($bind)){
      $bind = array($bind);
    }
    $stmt = $this->prepare($sql);
    $stmt->execute($bind);
    $stmt->setFetchMode($this->_fetchMode);
    return $stmt;
  }
  public function prepare($sql = '')
  {
    if(empty($sql)){
      return false;
    }
    $this->statement = $this->db->prepare($sql);
    return $this->statement;
  }
  public function execute($param = '')
  {
    if(is_array($param)){
      try {
        return $this->statement->execute($param);
      } catch (Exception $e) {
        return $e->getMessage();
      }
    }else {
      try {
        return $this->statement->execute();
      } catch (Exception $e) {
        return $e->getMessage();
      }
    }
  }
  /**
   *
   * @param string $where
   * @return null|string
   */
  protected function _whereExpr($where)
  {
    if(empty($where)){
      return $where;
    }
    if(!is_array($where)){
      $where = array($where);
    }
    $where = implode(' AND ', $where);
    return $where;
  }
  /**
   * 关闭数据库操作
   */
  public function close()
  {
    $this->_db = null;
  }
}

配置

db.type = 'mysql'
db.host = '127.0.0.1'
db.username = 'root'
db.password = '123456'
db.dbname = 'test'
db.charset = 'UTF8'

调用方法

class TestController extends Yaf_Controller_Abstract
{
  public function indexAction()
  {
    $config = Yaf_Application::app()->getConfig()->db;
    $db = Db_Mysql::getInstance($config);
    $row = $db->fetchOne('select count(*) from `user`');
    print_r($row);die;
  }
}

结果

Yaf框架封装的MySQL数据库操作示例

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

PHP 相关文章推荐
风格模板初级不完全修改教程
Oct 09 PHP
PHP 基本语法格式
Dec 15 PHP
php笔记之:数据类型与常量的使用分析
May 14 PHP
PHP引用(&amp;)各种使用方法实例详解
Mar 20 PHP
PHP中一些可以替代正则表达式函数的字符串操作函数
Nov 17 PHP
phpmyadmin提示The mbstring extension is missing的解决方法
Dec 17 PHP
laravel安装zend opcache加速器教程
Mar 02 PHP
Yii列表定义与使用分页方法小结(3种方法)
Jul 15 PHP
php-fpm开启状态统计的方法详解
Jun 23 PHP
利用PHP判断是否是连乘数字串的方法示例
Jul 03 PHP
thinkphp5实现无限级分类
Feb 18 PHP
Laravel如何实现适合Api的异常处理响应格式
Jun 14 PHP
PHP实现的敏感词过滤方法示例
Mar 06 #PHP
详解PHP 二维数组排序保持键名不变
Mar 06 #PHP
PHP获取ttf格式文件字体名的方法示例
Mar 06 #PHP
php ajax confirm 删除实例详解
Mar 06 #PHP
详解PHP多个进程配合redis的有序集合实现大文件去重
Mar 06 #PHP
一次因composer错误使用引发的问题与解决
Mar 06 #PHP
利用PHP如何统计Nginx日志的User Agent数据
Mar 06 #PHP
You might like
用PHP和ACCESS写聊天室(九)
2006/10/09 PHP
PHP 验证码的实现代码
2011/07/17 PHP
php中sql注入漏洞示例 sql注入漏洞修复
2014/01/24 PHP
PHP页面实现定时跳转的方法
2014/10/31 PHP
php+mysqli预处理技术实现添加、修改及删除多条数据的方法
2015/01/30 PHP
PHP实现简单搜歌的方法
2015/07/28 PHP
PHP实现查询两个数组中不同元素的方法
2016/02/23 PHP
Zend Framework实现具有基本功能的留言本(附demo源码下载)
2016/03/22 PHP
PHP支付系统设计与典型案例分享
2016/08/02 PHP
PHP使用Nginx实现反向代理
2017/09/20 PHP
Extjs4 消息框去掉关闭按钮(类似Ext.Msg.alert)
2013/04/02 Javascript
JavaScript截取字符串的Slice、Substring、Substr函数详解和比较
2014/03/20 Javascript
AngularJS基于ngInfiniteScroll实现下拉滚动加载的方法
2016/12/14 Javascript
[js高手之路]原型式继承与寄生式继承详解
2017/08/28 Javascript
JavaScript中数组常见操作技巧
2017/09/01 Javascript
JS验证码实现代码
2017/09/14 Javascript
JQuery选中select组件被选中的值方法
2018/03/08 jQuery
JavaScript 下载svg图片为png格式
2018/06/21 Javascript
微信小程序画布圆形进度条显示效果
2020/11/17 Javascript
学习python (2)
2006/10/31 Python
python学习笔记:字典的使用示例详解
2014/06/13 Python
Python异常模块traceback用法实例分析
2019/10/22 Python
pytorch如何冻结某层参数的实现
2020/01/10 Python
python datetime处理时间小结
2020/04/16 Python
Django实现celery定时任务过程解析
2020/04/21 Python
Django:使用filter的pk进行多值查询操作
2020/07/15 Python
CSS3 实现的火焰动画
2020/12/07 HTML / CSS
猫咪家具:CatsPlay
2018/11/03 全球购物
东芝官网商城:还原日式美学,打造美好生活
2018/12/27 全球购物
英国健身超市:Fitness Superstore
2019/06/17 全球购物
考试作弊检讨书大全
2014/02/18 职场文书
《数星星的孩子》教学反思
2014/04/11 职场文书
春游踏青活动方案
2014/08/14 职场文书
民用住房租房协议书
2014/10/29 职场文书
仓库保管员岗位职责
2015/02/09 职场文书
金榜题名主持词
2015/07/02 职场文书