0

0

MysqPdo封装

PHP中文网

PHP中文网

发布时间:2016-05-25 17:03:06

|

1406人浏览过

|

来源于php中文网

原创

mysqpdo封装

connect();
    }
    /**
     * 连接数据库
     *
     * @access protected
     */
    protected function connect(){
        if(!class_exists('PDO')) $this->halt('不支持PDO扩展!');
        try{
            $this->_pdo = new PDO(
                'mysql:dbname='.$this->options["dbName"].';host='.$this->options["host"].';
                port='.$this->options['port'],
                $this->options["user"],
                $this->options["password"],
                array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
            );
            $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->_pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $this->_connected = true;
        }catch (PDOException $e){
            $this->halt('不能链接Mysql数据库 .Error:'.$e->getMessage());
        }
    }
 
 
    /**
     * 初始化.
     *
     * @param stirng $sql
     * @param array|string $parameters
     * [url=home.php?mod=space&uid=987628]@Return[/url] void
     */
    private function _init($sql ,$parameters = ""){
        if(!$this->_connected) $this->connect();
        try {
            $this->_query = $this->_pdo->prepare($sql);
            $this->bindMore($parameters);
            if(!empty($this->_parameters)) {
                foreach($this->_parameters as $key=>$value){
                    switch( true ) {
                        case is_int($value):
                            $type = PDO::PARAM_INT;
                            break;
                        case is_bool($value):
                            $type = PDO::PARAM_BOOL;
                            break;
                        case is_null($value):
                            $type = PDO::PARAM_NULL;
                            break;
                        default:
                            $type = PDO::PARAM_STR;
                    }
                    $this->_query->bindParam($key ,$this->_parameters[$key] ,$type);
                }
            }
            $this->_parameters = array();
            return $this->_query->execute();
        }catch(PDOException $e){
            $this->halt($e->getMessage() ,$this->_query->queryString);
        }
    }
 
    /**
     * 绑定数据
     *
     * @param string $para
     * @param string $value
     */
    public function bind($para, $value){
        $this->_parameters[":" . $para] =  $value;
    }
    /**
     * 绑定数据
     *
     * @param array $parray
     */
    public function bindMore($parray){
        if(empty($this->_parameters) && is_array($parray)) {
            foreach($parray as $key => &$value) {
                $this->bind($key, $parray[$key]);
            }
        }
    }
    /**
     * 一些简单的操作
     *
     * @param string $sql
     * @param array $params
     * @param int $mode
     * [url=home.php?mod=space&uid=987628]@Return[/url] mixed
     */
    public function query($sql,$params = NULL, $mode = PDO::FETCH_ASSOC){
        $sql = trim($sql);
        if($params){
            $this->_init($sql ,$params);
            return $this->_query->fetchAll($mode);
        }else{
            $sql = str_replace('`waf_' ,'`'.$this->options['prefix'] ,$sql);
            return $this->_pdo->exec($sql);
        }
        return false;
    }
 
    /**
     * 根据查询取出所有资料
     *
     * @param  string $sql
     * @param  mixed $params
     * @return array
     */
    public function fetchAll($sql ,array $params = NULL){
        $this->_init($sql ,$params);
        $result = array();
        while($row = $this->_query->fetch(PDO::FETCH_ASSOC)){
            $result[] = $row;
        }
        return $result;
    }
    /**
     * 查询单条数据
     *
     * @param  string $sql
     * @param  mixed $params
     * @return array
     */
    public function fetchOne($sql ,array $params = NULL){
        $this->_init($sql ,$params);
        $result = $this->_query->fetch(PDO::FETCH_ASSOC);
        return $result;
    }
    /**
     * 获取总数量
     *
     * @param  string $sql
     * @param  array  $params
     * @return int
     */
    public function getCount($sql  ,$params = NULL){
        $this->_init($sql ,$params);
        $result = $this->_query->fetch(PDO::FETCH_NUM);
        return $result[0];
    }
    /**
     * 函数返回结果集中行的数目
     *
     * @param  string $sql
     * @return int
     */
    public function numRows($sql) {
        $this->_filter = array();
        $datas = $this->fetchAll($sql);
        $counts = count($datas);
        unset($datas);
        return $counts;
    }
    /**
     * 函数返回结果集中字段的数
     *
     * @param  string $sql
     * @return int
     */
    public function numFields($sql) {
        $this->_filter = array();
        $this->_init($sql);
        return $this->_query->columnCount() ;
    }
    /**
     * 获取最后插入的ID
     *
     * @return mixed
     */
    public function insertId() {
        try {
            return $this->_pdo->lastInsertId();
        }catch( PDOException $e ) {
            $this->halt($e->getMessage() ,$this->_query->queryString);
            return false;
        }
    }
    /**
     * 关闭连接.
     *
     * @access public
     */
    public function close(){
        $this->_pdo = null;
    }
    /**
     * 接.
     *
     * @access public
     */
    public function __destruct() {
        $this->close();
    }
 
    /**
     * 写入数据
     *
     * @param  string $table
     * @param  array  $data
     * @return int
     */
    public function insert($table ,$data){
        try {
            $sql = "INSERT INTO ".table($table);
            $columns = $values = '';
            foreach( $data as $k=>$v ) {
                $columns .= "$k,";
                $values .= ":$k,";
            }
            $columns = trim($columns,',');
            $values = trim($values,',');
            $sql = $sql . " ($columns) VALUES ($values)";
            $this->_init($sql ,$data);
            unset($sql ,$columns ,$values);
            return $this->insertId();
        }catch( PDOException $e ) {
            $this->halt($e->getMessage() ,$this->_query->queryString);
            return false;
        }
    }
    /**
     * 更新数据
     *
     * @param  string $table
     * @param  array  $data
     * @param  mixed  $wheres
     * @return int
     */
    public function update($table ,$data ,$wheres = NULL){
        $sql = "UPDATE ".table($table)." SET ";
        foreach($data as $key=>$value){
            if(is_array($value)){
                $sql .= "`{$key}` = ".$key . $value[0] . $value[1] . ',';
                unset($data[$key]);
            }else{
                $sql .= "`{$key}`=:{$key},";
            }
        }
        $sql = trim($sql ,',');
        if(is_array($wheres) && !empty($wheres)){
            $where = '';
            foreach($wheres as $key=>$value){
                $where .= "`{$key}`=:{$key} AND ";
            }
            $where = trim($where ,' AND ');
            $sql .= " WHERE {$where}";
            $data = array_merge($data ,$wheres);
            unset($where ,$wheres);
 
        }else{
            $sql .= " WHERE {$wheres}";
        }
        $this->_init($sql ,$data);
        unset($sql);
        return $this->_query->rowCount();
    }
    /**
     * 删除数据
     *
     * @param  string $table
     * @param  array|string  $wheres
     * @return int
     */
    public function delete($table ,$wheres = NULL){
        $sql = "DELETE FROM ".table($table).' WHERE ';
        if(is_array($wheres)){
            foreach($wheres as $key => $value){
                $sql .= "`{$key}`=:{$key} AND ";
            }
            $sql = trim($sql ,' AND ');
        }else{
            $sql .= $wheres;
        }
        $this->_init($sql ,$wheres);
        unset($sql);
        return $this->_query->rowCount();
    }
 
}

                   

以上就是MysqPdo封装的内容,更多相关内容请关注PHP中文网(www.php.cn)!

video封装ui
video封装ui

video封装ui

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
go语言 注释编码
go语言 注释编码

本专题整合了go语言注释、注释规范等等内容,阅读专题下面的文章了解更多详细内容。

32

2026.01.31

go语言 math包
go语言 math包

本专题整合了go语言math包相关内容,阅读专题下面的文章了解更多详细内容。

23

2026.01.31

go语言输入函数
go语言输入函数

本专题整合了go语言输入相关教程内容,阅读专题下面的文章了解更多详细内容。

16

2026.01.31

golang 循环遍历
golang 循环遍历

本专题整合了golang循环遍历相关教程,阅读专题下面的文章了解更多详细内容。

5

2026.01.31

Golang人工智能合集
Golang人工智能合集

本专题整合了Golang人工智能相关内容,阅读专题下面的文章了解更多详细内容。

6

2026.01.31

2026赚钱平台入口大全
2026赚钱平台入口大全

2026年最新赚钱平台入口汇总,涵盖任务众包、内容创作、电商运营、技能变现等多类正规渠道,助你轻松开启副业增收之路。阅读专题下面的文章了解更多详细内容。

268

2026.01.31

高干文在线阅读网站大全
高干文在线阅读网站大全

汇集热门1v1高干文免费阅读资源,涵盖都市言情、京味大院、军旅高干等经典题材,情节紧凑、人物鲜明。阅读专题下面的文章了解更多详细内容。

195

2026.01.31

无需付费的漫画app大全
无需付费的漫画app大全

想找真正免费又无套路的漫画App?本合集精选多款永久免费、资源丰富、无广告干扰的优质漫画应用,涵盖国漫、日漫、韩漫及经典老番,满足各类阅读需求。阅读专题下面的文章了解更多详细内容。

170

2026.01.31

漫画免费在线观看地址大全
漫画免费在线观看地址大全

想找免费又资源丰富的漫画网站?本合集精选2025-2026年热门平台,涵盖国漫、日漫、韩漫等多类型作品,支持高清流畅阅读与离线缓存。阅读专题下面的文章了解更多详细内容。

85

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
【web前端】Node.js快速入门
【web前端】Node.js快速入门

共16课时 | 2万人学习

MySQL 初学入门(mosh老师)
MySQL 初学入门(mosh老师)

共3课时 | 0.3万人学习

【李炎恢】ThinkPHP8.x 后端框架课程
【李炎恢】ThinkPHP8.x 后端框架课程

共50课时 | 4.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号