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

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

May 23, 2016 am 08:39 AM

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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1319
25
PHP教程
1269
29
C# 教程
1248
24
MySQL和PhpMyAdmin:核心功能和功能 MySQL和PhpMyAdmin:核心功能和功能 Apr 22, 2025 am 12:12 AM

MySQL和phpMyAdmin是強大的數據庫管理工具。 1)MySQL用於創建數據庫和表、執行DML和SQL查詢。 2)phpMyAdmin提供直觀界面進行數據庫管理、表結構管理、數據操作和用戶權限管理。

在MySQL中解釋外鍵的目的。 在MySQL中解釋外鍵的目的。 Apr 25, 2025 am 12:17 AM

在MySQL中,外鍵的作用是建立表與表之間的關係,確保數據的一致性和完整性。外鍵通過引用完整性檢查和級聯操作維護數據的有效性,使用時需注意性能優化和避免常見錯誤。

IIS和PHP的兼容性:深度潛水 IIS和PHP的兼容性:深度潛水 Apr 22, 2025 am 12:01 AM

IIS和PHP可以兼容,通過FastCGI實現。 1.IIS通過配置文件將.php文件請求轉發給FastCGI模塊。 2.FastCGI模塊啟動PHP進程處理請求,提高性能和穩定性。 3.實際應用中需注意配置細節、錯誤調試和性能優化。

比較和對比Mysql和Mariadb。 比較和對比Mysql和Mariadb。 Apr 26, 2025 am 12:08 AM

MySQL和MariaDB的主要區別在於性能、功能和許可證:1.MySQL由Oracle開發,MariaDB是其分支。 2.MariaDB在高負載環境中性能可能更好。 3.MariaDB提供了更多的存儲引擎和功能。 4.MySQL採用雙重許可證,MariaDB完全開源。選擇時應考慮現有基礎設施、性能需求、功能需求和許可證成本。

如果session_start()被多次調用會發生什麼? 如果session_start()被多次調用會發生什麼? Apr 25, 2025 am 12:06 AM

多次調用session_start()會導致警告信息和可能的數據覆蓋。 1)PHP會發出警告,提示session已啟動。 2)可能導致session數據意外覆蓋。 3)使用session_status()檢查session狀態,避免重複調用。

SQL與MySQL:澄清兩者之間的關係 SQL與MySQL:澄清兩者之間的關係 Apr 24, 2025 am 12:02 AM

SQL是一種用於管理關係數據庫的標準語言,而MySQL是一個使用SQL的數據庫管理系統。 SQL定義了與數據庫交互的方式,包括CRUD操作,而MySQL實現了SQL標準並提供了額外的功能,如存儲過程和触發器。

作曲家:通過AI的幫助開發PHP 作曲家:通過AI的幫助開發PHP Apr 29, 2025 am 12:27 AM

AI可以幫助優化Composer的使用,具體方法包括:1.依賴管理優化:AI分析依賴關係,建議最佳版本組合,減少衝突。 2.自動化代碼生成:AI生成符合最佳實踐的composer.json文件。 3.代碼質量提升:AI檢測潛在問題,提供優化建議,提高代碼質量。這些方法通過機器學習和自然語言處理技術實現,幫助開發者提高效率和代碼質量。

MySQL:數據庫,PHPMYADMIN:管理接口 MySQL:數據庫,PHPMYADMIN:管理接口 Apr 29, 2025 am 12:44 AM

MySQL和phpMyAdmin可以通過以下步驟進行有效管理:1.創建和刪除數據庫:在phpMyAdmin中點擊幾下即可完成。 2.管理表:可以創建表、修改結構、添加索引。 3.數據操作:支持插入、更新、刪除數據和執行SQL查詢。 4.導入導出數據:支持SQL、CSV、XML等格式。 5.優化和監控:使用OPTIMIZETABLE命令優化表,並利用查詢分析器和監控工具解決性能問題。

See all articles