搜索
首页php教程PHP源码php mysql数据库操作mysql和pdo的实现

php mysql数据库操作mysql和pdo的实现

最近在项目中用到了pdo,之前一直用的mysql类,查了查手册,发现功能大同小异,于是我用接口封装了一个pdo类,实现了与mysql 的相同实现。

<?php
/**
 * Created by PhpStorm.
 * User: jiangbo
 * Date: 2016/1/24
 * Time: 1:05
 * 与mysql接口一致(模型层调用一致),利用interface
 */
interface i_DAO{
    //获取与前DAO的接口
    public static function getInstance($config = array());
    //执行sql的方法
    public function query($sql = &#39;&#39;);
    //获取全部数据
    public function fetchAll($sql = &#39;&#39;);
    //获取一行数据
    public function fetchRow($sql = &#39;&#39;);
    //获取一个数据
    public function fetchOne($sql = &#39;&#39;);
    //转义sql,防止注入
    public function escapeString($str = &#39;&#39;);
 
}

2. [文件] MySqlDB.class.php

<?php
 
/**
 * Created by PhpStorm.
 * User: jiangbo
 * Date: 2016/1/19
 * Time: 17:27
 * 单例化的mysql类:3私1公
 */
class MySqlDB implements i_DAO
{
    private $_host;
    private $_port;
    private $_user;
    private $_password;
    private $_charset;
    private $_dbname;
    private $_link;
 
    /**
     * MySqlDB constructor.
     * @param array $config
     */
    private function __construct($config = array())
    {
        $this->_initServer($config);//初始化服务器信息
        $this->_connectServer();//链接服务器
        $this->_setCharset();//设置字符集编码
        $this->_selectDB();//选择默认数据库
    }
 
    private function __clone()
    {
        echo "不能克隆该对象", "<br>";
        die();
    }
 
    private static $_instance;
 
    public static function getInstance($config = array())
    {
        if (!(static::$_instance instanceof static)) {
            static::$_instance = new static($config);
        }
        return static::$_instance;
    }
 
    private function _initServer($config)
    {
        $this->_host = isset($config[&#39;host&#39;]) ? $config[&#39;host&#39;] : &#39;localhost&#39;;
        $this->_port = isset($config[&#39;port&#39;]) ? $config[&#39;port&#39;] : &#39;3306&#39;;
        $this->_user = isset($config[&#39;user&#39;]) ? $config[&#39;user&#39;] : &#39;&#39;;
        $this->_password = $config[&#39;password&#39;];
        $this->_charset = isset($config[&#39;charset&#39;]) ? $config[&#39;charset&#39;] : &#39;UTF8&#39;;
        $this->_dbname = isset($config[&#39;dbname&#39;]) ? $config[&#39;dbname&#39;] : &#39;test&#39;;
    }
 
    private function _connectServer()
    {
        $connect_result = @mysql_connect("$this->_host:$this->_port", $this->_user, $this->_password);
        if ($connect_result) {
            $this->_link = $connect_result;
        } else {
            echo &#39;数据库连接失败,请确认服务器信息&#39;;
            die();
        }
    }
 
    private function _setCharset()
    {
        $sql = "SET NAMES $this->_charset";
        $this->query($sql);
    }
 
    private function _selectDB()
    {
        $sql = "USE `$this->_dbname`";
        $this->query($sql);
    }
 
    /**
     * 执行SQL语句
     * @param string $sql
     * @return mixed 执行结果。查询类的SQL(select, show, desc),成功返回结果集资源,
     失败返回false。非查询类(insert, delete, update),成功返回true,失败返回false.
     */
    public function query($sql)
    {
        $query_result = @mysql_query($sql, $this->_link);
        if (false == $query_result) {
            echo "SQL执行失败:", "<br>";
            echo "错误的SQL:", "<br>", $sql, "<br>";
            echo "错误的消息为:", "<br>", mysql_errno($this->_link), "<br>";
            die();
        } else {
            return $query_result;
        }
    }
 
    /**
     * @param string $sql 通常为:select * from ...
     * @return array
     */
    public function fetchRow($sql)
    {
        $result = $this->query($sql);
        $row = @mysql_fetch_assoc($result);
        @mysql_free_result($result);
        return $row;
    }
 
    /**
     * @param string $sql 通常为:select count(*) from ...
     * @return string 如果没有值就返回NULL
     */
    public function fetchOne($sql)
    {
        $result = $this->query($sql);
        $row = @mysql_fetch_row($result);
        @mysql_free_result($result);
        if ($row)
            return $row[0];
        else
            return NULL;
    }
 
    /**
     * @param string $sql 通常为:select * from ... where ..like &#39;han%&#39;
     * @return array
     */
    public function fetchAll($sql)
    {
        $result = $this->query($sql);
        $rows = array();
        while ($row = @mysql_fetch_assoc($result))
            $rows[] = $row;
        @mysql_free_result($result);
        return $rows;
    }
 
    /*
     * 关闭当前数据库连接, 一般无需使用. 连接会随php脚本结束自动关闭
     */
    /*public function close()
    {
        return @mysql_close($this->_link);
    }*/
 
    /**
     * 防止sql注入:转义字符串,在模型中使用
     * @param string $str 带转义的字符串
     * @return string 带引号包裹的转义后的字符串
     */
    public function escapeString($str = &#39;&#39;)
    {
        return "&#39;" . mysql_real_escape_string($str, $this->_link) . "&#39;";
    }
 
}

3. [文件] PDODB.class.php

<?php
 
/**
 * Created by PhpStorm.
 * User: jiangbo
 * Date: 2016/1/24
 * Time: 1:00
 * dao层使用dao扩展封装实现
 */
class PDODB implements i_DAO
{
    private $_host;
    private $_port;
    private $_user;
    private $_password;
    private $_charset;
    private $_dbname;
 
    private $_dsn;
    private $_option;
    private $_pdo;
 
 
    /**
     * PDODB constructor.
     * @param array $config
     */
    private function __construct($config = array())
    {
        $this->_initServer($config);
        $this->_newPDO();
    }
 
    private function _initServer($config)
    {
        $this->_host = isset($config[&#39;host&#39;]) ? $config[&#39;host&#39;] : &#39;localhost&#39;;
        $this->_port = isset($config[&#39;port&#39;]) ? $config[&#39;port&#39;] : &#39;3306&#39;;
        $this->_user = isset($config[&#39;user&#39;]) ? $config[&#39;user&#39;] : &#39;&#39;;
        $this->_password = $config[&#39;password&#39;];
        $this->_charset = isset($config[&#39;charset&#39;]) ? $config[&#39;charset&#39;] : &#39;UTF8&#39;;
        $this->_dbname = isset($config[&#39;dbname&#39;]) ? $config[&#39;dbname&#39;] : &#39;test&#39;;
    }
 
    private function _newPDO()
    {
        //设置参数
        $this->_setDSN();//设置数据源参数
        $this->_setOption();//设置选项
        $this->_getPDO();//得到PDO对象
    }
 
    private function _setDSN()
    {
        $this->_dsn = "mysql:host=$this->_host;port=$this->_port;dbname=$this->_dbname";
    }
 
    private function _setOption()
    {
        $this->_option = array(
            PDO::MYSQL_ATTR_INIT_COMMAND => "set names $this->_charset"
        );
    }
 
    private function _getPDO()
    {
        $this->_pdo = new PDO($this->_dsn, $this->_user, $this->_password, $this->_option);
 
    }
 
    private function __clone()
    {
        echo "不能克隆该对象", "<br>";
        die();
    }
 
    private static $_instance;
 
    public static function getInstance($config = array())
    {
        if (!(static::$_instance instanceof static)) {
            static::$_instance = new static($config);
        }
        return static::$_instance;
    }
    //执行方法,适用的场景
    private static $_queryStr = array(
        "select",
        "show",
        "desc"
    );
    public function query($sql = &#39;&#39;)
    {
        //使用正则过滤,分别使用query和exec
 
        foreach (static::$_queryStr as $str){
 
            if (preg_match("/^\s*".$str.".*?/i",$sql)){
                //查询类 返回结果集对象
                $result = $this->_pdo->query($sql);
            }else{
                //非查询类 返回bool
                $result = $this->_pdo->exec($sql) !== false;//有可能是0
            }
            //如果执行失败,报错
            if($result === false){
                $error_info = $this->errorInfo();
                echo "SQL执行失败:", "<br>";
                echo "错误的SQL:", "<br>", $sql, "<br>";
                echo "错误的消息为:", "<br>", $error_info[2], "<br>";
                die();
            }else{
                return $result;
            }
            break;
        }
    }
 
    public function fetchAll($sql = &#39;&#39;)
    {
        $result = $this->query($sql);
        $rows = $result->fetchAll(PDO::FETCH_ASSOC);
        $result->closeCursor();
        return $rows;
    }
 
    public function fetchRow($sql = &#39;&#39;)
    {
        $result = $this->query($sql);
        $row = $result->fetch(PDO::FETCH_ASSOC);
        $result->closeCursor();
        return $row;
    }
 
    public function fetchOne($sql = &#39;&#39;)
    {
        $result = $this->query($sql);
        $string = $result->fetchColumn();
        $result->closeCursor();
        return $string;
    }
 
    public function escapeString($str = &#39;&#39;)
    {
        return $this->_pdo->quote($str);
    }
}

4. [代码]model中调用

<?php
/**
 * Created by PhpStorm.
 * User: jiangbo
 * Date: 2016/1/19
 * Time: 1:02
 * 基础模型类
 */
 
 
class Model{
    /**
     * DAO : data access object
     */
    protected $_dao;//存储实例化好的数据库对象
 
    /**
     * Model constructor.
     */
    public function __construct()
    {
        $this->_initDAO();//初始化基础模型
    }
 
    protected function _initDAO(){
        
        $config = array(
            &#39;host&#39; => &#39;***&#39;,
            &#39;user&#39; => &#39;***&#39;,
            &#39;password&#39; => &#39;&#39;,
            &#39;dbname&#39; => &#39;***&#39;
        );
        //$this->_dao = MySqlDB::getInstance($config);//调用mysqldb
        $this->_dao = PDODB::getInstance($config);//调用pdo
    }
 
}

 

 以上就是php mysql数据库操作mysql和pdo的实现的内容,更多相关内容请关注PHP中文网(www.php.cn)! 


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具