1. 程式人生 > >PHP連線mysql資料庫之根據配置檔案選擇mysqli還是pdo方式

PHP連線mysql資料庫之根據配置檔案選擇mysqli還是pdo方式

配置檔案config.php

<?php
    return array(
        'DB' => array(
            'default_extension' => 'mysqli',
        ),
    );

介面I_DB.interface.php

<?php
    interface I_DB{
        public static function getInstance($config);
        public function my_query($sql);
        public function
fetchAll($sql);
public function fetchRow($sql); public function fetchColumn($sql); }

Mysqli連線配置檔案MysqliDB.class.php

<?php
header("content-type:text/html;charset=utf-8");
include "./I_DB.interface.php";
class MysqliDB implements I_DB{
    //私有的屬性
    private static $instance; //用來儲存單例物件
private $host; //主機名稱 private $port; //主機埠號 private $user; //資料庫使用者名稱 private $pass; //資料庫密碼 private $dbname; //要操作的資料庫名稱 private $charset; //要設定的字符集 private $link; //資料庫連線控制代碼 /** * 私有的構造方法 * 初始化引數 * 資料庫連線三步曲 * 1、連線資料庫 * 2、選擇資料庫 * 3、設定字符集 */
private function __construct($config){ //初始化屬性的值 $this->init($config); //連線資料庫 $this->db_connect(); //選擇資料庫 $this->db_usedb(); //設定字符集 $this->db_charset(); } //接收配置引數 private function init($config){ $this->host = isset($config['host']) ? $config['host']:'localhost'; $this->port = isset($config['port']) ? $config['port'] : '3306'; $this->user = isset($config['user']) ? $config['user'] : 'root'; $this->pass = isset($config['pass']) ? $config['pass'] : ''; $this->dbname = isset($config['dbname']) ? $config['dbname'] : ''; $this->charset=isset($config['charset']) ? $config['charset'] : 'utf8'; } //連線資料庫 private function db_connect(){ $this->link = mysqli_connect($this->host.':'.$this->port,$this->user,$this->pass); if(!$this->link){ echo "資料庫連線失敗! "; echo "錯誤編碼:".mysqli_errno($this->link)." "; echo "錯誤資訊:".mysqli_error($this->link)." "; exit; } } /** * 資料查詢並對錯誤進行處理 * @param string $sql * @return mixed(book|resource) */ public function my_query($sql){ $res = mysqli_query($this->link,$sql); if(!$res){ echo "sql語句執行失敗 "; echo "錯誤編碼是".mysqli_errno($this->link)." "; echo "錯誤資訊是".mysqli_error($this->link)." "; } return $res; } /** * 返回多選多列的結果集,二維陣列 * @param string $sql 一條sql語句 * @return mixed(array|false) 執行成功是陣列,失敗是false */ public function fetchAll($sql){ //執行sql if($res = $this->my_query($sql)){ $rows = []; while($row = mysqli_fetch_assoc($res)){ $rows[] = $row; }; //結果集使用完畢,主動釋放 mysqli_free_result($res); return $rows; }else{ return false; } } //返回一條記錄 public function fetchRow($sql){ //先執行 if($res = $this->my_query($sql)){ $row = mysqli_fetch_assoc($res); mysqli_free_result($res); return $row; }else{ return false; } } //返回單一值,也就是單行單列 public function fetchColumn($sql){ //先執行 if($res = $this->my_query($sql)){ $row = mysqli_fetch_row($res); mysqli_free_result($res); return isset($row[0])?$row[0]:false ; }else{ return false; } } //設定字符集 private function db_charset(){ $sql = "set names $this->charset"; return $this->my_query($sql); } //選擇資料庫 private function db_usedb(){ $sql = "use $this->dbname"; return $this->my_query($sql); } //私有的克隆,不允許克隆建立物件 private function __clone(){ die('clone is not allowed'); } //公開的靜態方法 public static function getInstance($config){ if(!self::$instance instanceof self){ self::$instance = new self($config); } return self::$instance; } public function __destruct(){ @mysqli_close($this->link); } }

PDO連線配置檔案PDODB.class.php

<?php
    header('content-type:text/html;charset=utf-8');
    include './I_DB.interface.php';
    class PDODB implements I_DB{
        //私有的屬性
        private static $instance; //用來儲存單例物件
        private $host;         //主機名稱
        private $port;         //主機埠號
        private $user;         //資料庫使用者名稱
        private $pass;         //資料庫密碼
        private $dbname;           //要操作的資料庫名稱
        private $charset;      //要設定的字符集
        private $dsn;         //資料資源名稱
        private $pdo;         // pdo連線
        /**
         * 私有的構造方法
         * 初始化引數
         * 資料庫連線三步曲
         * 1、連線資料庫
         * 2、選擇資料庫
         * 3、設定字符集
         */
        private function __construct($config){
            //初始化屬性
            $this->initParams($config);
            //初始化dsn
            $this->initDSN();
            //初始化pdo
            $this->initPDO();
            //初始化PDO物件的屬性
            $this->initAttribute();
        }
        // 對外公開的入口
        public static function getInstance($config){
            if(!self::$instance instanceof self){
                self::$instance = new self($config);
            }
            return self::$instance;
        }
        // 初始化引數
        private function initParams($config){
            $this->host = isset($config['host']) ? $config['host']:'localhost';
            $this->port = isset($config['port']) ? $config['port'] : '3306';
            $this->user = isset($config['user']) ? $config['user'] : 'root';
            $this->pass = isset($config['pass']) ? $config['pass'] : '';
            $this->dbname = isset($config['dbname']) ? $config['dbname'] : '';
            $this->charset=isset($config['charset']) ? $config['charset'] : 'utf8';
        }
        //初始化dsn
        private function initDSN(){
            $this->dsn = "mysql:host=$this->host;port=$this->port;dbname=$this->dbname;charset=$this->charset";
        }
            /**
         * 輸出異常資訊
         */
        private function my_error($e) {
            echo 'SQL語句執行失敗!<br />';
            echo '錯誤的程式碼是:', $e->getCode(), '<br />';
            echo '錯誤的資訊是:', $e->getMessage(), '<br />';
            echo '錯誤的指令碼是:', $e->getFile(), '<br />';
            echo '錯誤的行號是:', $e->getLine(), '<br />';
            return false;
        }
        //初始化pdo
        private function initPDO(){
            try{
                $this->pdo = new PDO($this->dsn,$this->user,$this->pass);
            }catch(Exception $e){
                $this->my_error($e);
            }
        }
        // 初始化PDO物件的屬性
        private function initAttribute(){
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        }
        // 查詢語句
        public function my_query($sql){
            try{
                $result = $this->pdo->exec($sql);
            }catch(Exception $e){
                $this->my_error($e);
            }
            return $result;
        }
        // 實現fetchAll抽象方法
        public function fetchAll($sql){
            try{
                $stmt = $this->pdo->query($sql);
                $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
                // 關閉遊標,釋放結果集
                $stmt->closeCursor();
            }catch(Exception $e){
                $this->my_error($e);
            }
            return $result;
        }
        public function fetchRow($sql){
            try{
                $stmt = $this->$pdo->query($sql);
                $result = $stmt->fetch(PDO::FETCH_ASSOC);
                // 關閉遊標,釋放結果集
                $stmt->closeCursor();
            }catch(Exception $e){
                $this->my_error($e);
            }
            return $result;
        }
        public function fetchColumn($sql){
            try{
                $stmt = $this->pdo->query($sql);
                $result = $stmt->fetchColumn();
                $stmt->closeCursor();
            }catch(Exception $e){
                $this->my_error($e);
            }
            return $result;
        }
        // 禁止克隆建立一個物件
        private function __clone(){
            die('clone is not allowed');
        }
    }

使用方法database.php

<?php
header("content-type:text/html;charset=utf-8");
$conf = include "./config.php";
$config = array(
    "pass" => "789890",
    "dbname" => "bbs"
);
switch ($conf['DB']['default_extension']) {
    case 'mysqli':
        include "./MysqliDB.class.php";
        $db = MysqliDB::getInstance($config);
        break;

    case 'pdo' :
        include "./PDODB.class.php";
        $db = PDODB::getInstance($config);
}
$sql = "select * from user";
echo "<pre>";

var_dump($db->fetchAll($sql));