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 相关文章推荐
浅谈Windows下 PHP4.0与oracle 8的连接设置
Oct 09 PHP
实现dedecms全站URL静态化改造的代码
Mar 29 PHP
PHP连接SQLSERVER 注意事项(附dll文件下载)
Jun 28 PHP
基于Linux调试工具strace与gdb的常用命令总结
Jun 03 PHP
php输入流php://input使用示例(php发送图片流到服务器)
Dec 25 PHP
destoon出现验证码不显示时的紧急处理方法
Aug 22 PHP
php获取系统变量方法小结
May 29 PHP
PHP新建类问题分析及解决思路
Nov 19 PHP
讲解WordPress开发中一些常用的debug技巧
Dec 18 PHP
php 使用curl模拟ip和来源进行访问的实现方法
May 02 PHP
PHP实现微信申请退款功能
Oct 01 PHP
PHP封装的数据库模型Model类完整示例【基于PDO】
Mar 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与javascript对多项选择的处理
2006/10/09 PHP
PHP 读取和修改大文件的某行内容的代码
2009/10/30 PHP
解析thinkphp的左右值无限分类
2013/06/20 PHP
使用PHP curl模拟浏览器抓取网站信息
2013/10/28 PHP
PHP jQuery表单,带验证具体实现方法
2014/02/15 PHP
php实现简单的MVC框架实例
2015/09/23 PHP
PHP生成条形码大揭秘
2015/09/24 PHP
PHP中利用sleep函数实现定时执行功能实现代码
2016/08/25 PHP
php实现留言板功能(代码详解)
2017/03/28 PHP
PHP实现对xml的增删改查操作案例分析
2017/05/19 PHP
JavaScript中的一些定位属性[图解]
2010/07/14 Javascript
jQuery焦点控制图层展示延迟隐藏的方法
2015/03/09 Javascript
浅谈angularjs module返回对象的坑(推荐)
2016/10/21 Javascript
jquery网页日历显示控件calendar3.1使用详解
2016/11/24 Javascript
JavaScript关联数组用法分析【概念、定义、遍历】
2017/03/15 Javascript
在nginx上部署vue项目(history模式)的方法
2017/12/28 Javascript
vue通过点击事件读取音频文件的方法
2018/05/30 Javascript
详解使用 Node.js 开发简单的脚手架工具
2018/06/08 Javascript
从零开始学习搭建React脚手架项目
2018/08/23 Javascript
js使用Promise实现简单的Ajax缓存
2018/11/14 Javascript
微信小程序canvas绘制圆角base64图片的实现
2019/08/18 Javascript
微信小程序弹窗禁止页面滚动的实现代码
2020/12/30 Javascript
[01:06:07]2014 DOTA2国际邀请赛中国区预选赛5.21 DT VS CIS
2014/05/22 DOTA
用Python登录Gmail并发送Gmail邮件的教程
2015/04/17 Python
Python正则表达式匹配中文用法示例
2017/01/17 Python
python实现顺序表的简单代码
2018/09/28 Python
python 计算数据偏差和峰度的方法
2019/06/29 Python
python中upper是做什么用的
2020/07/20 Python
html5中 media(播放器)的api使用指南
2014/12/26 HTML / CSS
印尼在线购买隐形眼镜网站:Lensza.co.id
2019/04/27 全球购物
美国沃尔玛网上超市:Walmart
2020/08/14 全球购物
人事部岗位职责范本
2014/03/05 职场文书
教务处教学工作总结
2015/08/10 职场文书
机关干部纪律作风整顿心得体会
2016/01/23 职场文书
预备党员的思想汇报,你真的会写吗?
2019/06/28 职场文书
python实现批量移动文件
2021/04/05 Python