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 相关文章推荐
PHP邮件专题
Oct 09 PHP
PHP安全配置
Dec 06 PHP
php jquery 实现新闻标签分类与无刷新分页
Dec 18 PHP
php的list()的一步操作给一组变量进行赋值的使用
May 18 PHP
使用PHP实现密保卡功能实现代码&amp;lt;打包下载直接运行&amp;gt;
Oct 09 PHP
thinkPHP实现瀑布流的方法
Nov 29 PHP
分享一则PHP定义函数代码
Feb 26 PHP
PHP程序员不应该忽略的3点
Oct 09 PHP
Yii CFileCache 获取不到值的原因分析
Feb 08 PHP
phpStudy 2016 使用教程详解(支持PHP7)
Oct 18 PHP
PHP实现基本留言板功能原理与步骤详解
Mar 26 PHP
详解PHP Swoole与TCP三次握手
May 27 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
全国中波电台频率表
2020/03/11 无线电
PHP+XML 制作简单的留言本 图文教程
2009/11/02 PHP
PHP扩展模块memcached长连接使用方法分析
2014/12/24 PHP
PHP 使用memcached简单示例分享
2015/03/05 PHP
Yii实现文章列表置顶功能示例
2016/10/18 PHP
详谈phpAdmin修改密码后拒绝访问的问题
2017/04/03 PHP
VBScript版代码高亮
2006/06/26 Javascript
jQuery EasyUI API 中文文档 - ComboBox组合框
2011/10/07 Javascript
JS实现的鼠标跟随代码(卡通手型点击效果)
2015/10/26 Javascript
微信小程序 教程之小程序配置
2016/10/17 Javascript
Vue.js第二天学习笔记(vue-router)
2016/12/01 Javascript
JS倒计时实例_天时分秒
2017/08/22 Javascript
vue动态绑定组件子父组件多表单验证功能的实现代码
2018/05/14 Javascript
JavaScript引用类型Object常见用法实例分析
2018/08/08 Javascript
vue中的ref和$refs的使用
2018/11/22 Javascript
js简单遍历获取对象中的属性值的方法示例
2019/06/19 Javascript
JavaScript展开操作符(Spread operator)详解
2019/07/20 Javascript
layui type2 通过url给iframe子页面传值的例子
2019/09/06 Javascript
JS多个异步请求 按顺序执行next实现解析
2019/09/16 Javascript
微信小程序学习之自定义滚动弹窗
2020/12/20 Javascript
Python装饰器使用示例及实际应用例子
2015/03/06 Python
Python实现提取文章摘要的方法
2015/04/21 Python
Python使用logging结合decorator模式实现优化日志输出的方法
2016/04/16 Python
Python的Flask框架应用程序实现使用QQ账号登录的方法
2016/06/07 Python
win10系统中安装scrapy-1.1
2016/07/03 Python
python获取外网IP并发邮件的实现方法
2017/10/01 Python
用十张图详解TensorFlow数据读取机制(附代码)
2018/02/06 Python
Python 给屏幕打印信息加上颜色的实现方法
2019/04/24 Python
python3.x中安装web.py步骤方法
2020/06/23 Python
使用CSS3实现SVG路径描边动画效果入门教程
2019/10/21 HTML / CSS
草莓网英国官网:Strawberrynet UK
2017/02/12 全球购物
芭比波朗加拿大官方网站:Bobbi Brown Cosmetics CA
2020/11/05 全球购物
2015年志愿者服务工作总结
2015/04/20 职场文书
2016年第32个教师节红领巾广播稿
2015/12/18 职场文书
Golang表示枚举类型的详细讲解
2021/09/04 Golang
Win10 Anaconda安装python-pcl
2022/04/29 Servers