1. 程式人生 > >使用pdo和mysqli封裝mysql資料庫的常用操作

使用pdo和mysqli封裝mysql資料庫的常用操作

<1>使用pdo操作mysql資料庫

使用了單例模式封裝了資料庫操作,主要包括以下幾步

①首先宣告一個靜態變數,便於資料庫連線狀態儲存

②宣告構造方法為私有,禁止外部呼叫構造方法進行連線資料庫操作

③宣告一個公有的獲取資料連線屬性的靜態方法,便於外部直接呼叫,該方法首先判斷靜態變數是否存在,不存在則例項化自身類獲取連線屬性,存在則直接返回連線屬性

④宣告一個私有的克隆魔術方法__clone,目的是在有克隆物件操作的時候,自動呼叫,因方法為空,起到了克隆到的屬性為空的作用,從而避免了連線屬性的盜用

具體程式碼實現如下:MysqlPdo.class.php

<?php
class MysqlPdo{
    protected static $_instance = null;
    protected $dsn;
    protected $dbh;
    private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset){
        try {
            $this->dsn = 'mysql:host='.$dbHost.';dbname='.$dbName;
            $this->dbh = new PDO($this->dsn, $dbUser, $dbPasswd);
            $this->dbh->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary');
        } catch (PDOException $e) {
            $this->outputError($e->getMessage());
        }
    }
    private function __clone(){

    }
    public static function getInstance($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset){
        if(self::$_instance === null){
            self::$_instance = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset);
        }
        return self::$_instance;
    }
    public function query($strSql, $queryMode = 'All', $debug = false)
    {
        if ($debug === true) $this->debug($strSql);
        $recordset = $this->dbh->query($strSql);
        $this->getPDOError();
        if ($recordset) {
            $recordset->setFetchMode(PDO::FETCH_ASSOC);
            if ($queryMode == 'All') {
                $result = $recordset->fetchAll();
            } elseif ($queryMode == 'Row') {
                $result = $recordset->fetch();
            }
        } else {
            $result = null;
        }
        return $result;
    }
    public function update($table, $arrayDataValue, $where = '', $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        if ($where) {
            $strSql = '';
            foreach ($arrayDataValue as $key => $value) {
                $strSql .= ", `$key`='$value'";
            }
            $strSql = substr($strSql, 1);
            $strSql = "UPDATE `$table` SET $strSql WHERE $where";
        }else {
            $strSql = "REPLACE INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
        }
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    public function insert($table, $arrayDataValue, $debug = false)
    {
        $this->checkFields($table, $arrayDataValue);
        $strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    public function delete($table, $where = '', $debug = false)
    {
        if ($where == '') {
            $this->outputError("'WHERE' is Null");
        } else {
            $strSql = "DELETE FROM `$table` WHERE $where";
            if ($debug === true) $this->debug($strSql);
            $result = $this->dbh->exec($strSql);
            $this->getPDOError();
            return $result;
        }
    }
    //直接執行增刪改sql語句
    public function execSql($strSql, $debug = false)
    {
        if ($debug === true) $this->debug($strSql);
        $result = $this->dbh->exec($strSql);
        $this->getPDOError();
        return $result;
    }
    //預處理執行
    public function prepareSql($sql=''){
        return $this->dbh->prepare($sql);
    }
    //執行預處理
    public function execute($presql){
        return $this->dbh->execute($presql);
    }
    /**
     * 獲取欄位最大值
     * 
     * @param string $table 表名
     * @param string $field_name 欄位名
     * @param string $where 條件
     */
    public function getMaxValue($table, $field_name, $where = '', $debug = false)
    {
        $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
        if ($where != '') $strSql .= " WHERE $where";
        if ($debug === true) $this->debug($strSql);
        $arrTemp = $this->query($strSql, 'Row');
        $maxValue = $arrTemp["MAX_VALUE"];
        if ($maxValue == "" || $maxValue == null) {
            $maxValue = 0;
        }
        return $maxValue;
    }
     
    /**
     * 獲取指定列的數量
     * 
     * @param string $table
     * @param string $field_name
     * @param string $where
     * @param bool $debug
     * @return int
     */
    public function getCount($table, $field_name, $where = '', $debug = false)
    {
        $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
        if ($where != '') $strSql .= " WHERE $where";
        if ($debug === true) $this->debug($strSql);
        $arrTemp = $this->query($strSql, 'Row');
        return $arrTemp['NUM'];
    }
     
    /**
     * checkFields 檢查指定欄位是否在指定資料表中存在
     *
     * @param String $table
     * @param array $arrayField
     */
    private function checkFields($table, $arrayFields)
    {
        $fields = $this->getFields($table);
        foreach ($arrayFields as $key => $value) {
            if (!in_array($key, $fields)) {
                $this->outputError("Unknown column `$key` in field list.");
            }
        }
    }
     
    /**
     * getFields 獲取指定資料表中的全部欄位名
     *
     * @param String $table 表名
     * @return array
     */
    private function getFields($table)
    {
        $fields = array();
        $recordset = $this->dbh->query("SHOW COLUMNS FROM $table");
        $this->getPDOError();
        $recordset->setFetchMode(PDO::FETCH_ASSOC);
        $result = $recordset->fetchAll();
        foreach ($result as $rows) {
            $fields[] = $rows['Field'];
        }
        return $fields;
    }
     
    /**
     * getPDOError 捕獲PDO錯誤資訊
     */
    private function getPDOError()
    {
        if ($this->dbh->errorCode() != '00000') {
            $arrayError = $this->dbh->errorInfo();
            $this->outputError($arrayError[2]);
        }
    }
     
    /**
     * debug
     * 
     * @param mixed $debuginfo
     */
    private function debug($debuginfo)
    {
        var_dump($debuginfo);
        exit();
    }
     
    /**
     * 輸出錯誤資訊
     * 
     * @param String $strErrMsg
     */
    private function outputError($strErrMsg)
    {
        throw new Exception('MySQL Error: '.$strErrMsg);
    }
     
    /**
     * destruct 關閉資料庫連線
     */
    public function destruct()
    {
        $this->dbh = null;
        return 0;
    }
     
}

<2>使用mysqli操作mysql的常用封裝

該封裝有兩個類,其中一個類是抽象類,定義了資料庫操作的常用抽象方法,另一個類繼承抽象類,並且重寫了具體的資料庫操作方法,具體程式碼實現如下:MysqlI.class.php

<?php
abstract class aDB {
    /**
     * 連線資料庫,從配置檔案中讀取配置資訊
     */
    abstract public function conn();
    /**
     * 傳送query查詢
     * @param string $sql sql??
     * @return mixed
     */
    abstract public function query($sql);
    /**
     * 查詢多行資料
     * @param string $sql sql語句
     * @return array
     */
    abstract public function getAll($sql);
    /**
    * 單行資料
     * @param string $sql sql語句
     * @return array
     */
    abstract public function getRow($sql);
    /**
     * 查詢單個數據  count(*)
     * @param string $sql sql語句
     * @return mixed
     */
    abstract public function getOne($sql);
    /**
     * 自動建立sql並執行,insert/update
     * @param array $data  關聯陣列 鍵/值 與表的 列/值對應
     * @param string $table 表明
     * @param string $act 動作/update/insert
     * @param string $where 條件,用於update
     * @return int 新插入的行的主鍵值或者影響行數
     */
    abstract public function Exec($data , $table , $act='insert' , $where='0');
    /**
     * 返回上一條insert語句產生的值
     */
    abstract public function lastId();
    /**
     * 返回上一條語句影響的行數
     */
    abstract public function affectRows();
}
class MyMysqlI extends aDB{
    public $mysqli;
	public $conf;
    public function __construct($config){
	$this->conf=$config;
        $this->conn();
    }
    /**
     * 連線資料庫,從配置檔案中讀取配置資訊
     */
    public function conn(){
        //$conf=include './conf.php';
        $this->mysqli = new mysqli($this->conf['host'], $this->conf['user'], $this->conf['pwd'], $this->conf['db']);
        //設定字符集
        $this->mysqli->query('set names '.$this->conf['charset']);
    }
    /**
     * 傳送query查詢
     * @param string $sql sql??
     * @return mixed
     */
    public function query($sql){
        //select返回一個物件或者無結果集sql返回bool
        return $this->mysqli->query($sql);
    }
    /**
     * 查詢多行資料
     * @param string $sql sql語句
     * @return array
     */
    public function getAll($sql){
        $data=[];
        $res=$this->mysqli->query($sql);
        while($row=$res->fetch_assoc()){
            $data[]=$row;
        }
        return $data;
    }
    /**
    * 單行資料
     * @param string $sql sql語句
     * @return array
     */
    public function getRow($sql){
        $res=$this->mysqli->query($sql);
        return $res->fetch_assoc();
    }
    /**
     * 查詢單個數據  count(*)
     * @param string $sql sql語句
     * @return mixed
     */
    public function getOne($sql){
        $res=$this->mysqli->query($sql);
        return $res->fetch_row()[0];
    }
    /**
     * 自動建立sql並執行,insert/update
     * @param array $data  關聯陣列 鍵/值 與表的 列/值對應
     * @param string $table 表明
     * @param string $act 動作/update/insert
     * @param string $where 條件,用於update
     * @return int 新插入的行的主鍵值或者影響行數
     */
    public function Exec($data , $table , $act='insert' , $where='0'){
        if($act == 'insert'){
            $sql ="insert into $table (";
            $sql.=implode(',',array_keys($data)).") values('";
            $sql.=implode(array_values($data),"','")."')";          
        }else{
            $sql="update $table set ";
            foreach($data as $k => $v){
                $sql.=$k."='".$v."',";
            }
            $sql=rtrim($sql,',')." where ".$where;
        }
        return $this->mysqli->query($sql);
    }
    /**
     * 返回上一條insert語句產生的值
     */
    public function lastId(){
        return $this->mysqli->insert_id;
    }
    /**
     * 返回上一條語句影響的行數
     */
    public function affectRows(){
        return $this->mysqli->affected_rows;
    }
}