PHP PDO的簡單封裝(使用命名空間方式)


DAO:數據庫訪問對象(Database Access Object)

直接上代碼:要點都在注釋中了

namespace core;
//引入全局空間類:PDO相關的3個類
use \PDO,\PDOStatement,\PDOException;

class Dao{
    private $pdo;
    private $fetch_mode;    //獲取結果集的模式
    /**
     *@desc 構造方法,獲取pdo對象,設置字符集
     *@param1 array $info,數據庫基本信息
     *@param2 array $info,數據庫驅動配置
     */
    public function __construct($info = array(), $drivers = array()){
        $dbtype = $info['dbtype'] ?? 'mysql';
        $host = $info['host'] ?? 'localhost';
        $port = $info['port'] ?? '3306';
        $user = $info['user'] ?? 'root';
        $password = $info['password'] ?? '***';
        $dbname = $info['dbname'] ?? 'demo';
        $charset = $info['charset'] ?? 'utf8';
        $this->fetch_mode = $info['fetch_mode'] ?? PDO::FETCH_ASSOC;

        $drivers[PDO::ATTR_ERRMODE] = $drivers[PDO::ATTR_ERRMODE] ?? PDO::ERRMODE_EXCEPTION;

        $dsn = "{$dbtype}:host={$host};port={$port};dbname={$dbname}";
        try{
            $this->pdo = new PDO($dsn, $user, $password, $drivers);
        }catch(PDOException $e){
            die("數據庫連接失敗:{$e->getMessage()} in line {$e->getLine()}");
        }
        try{
            $this->pdo->exec("set names {$charset}");
        }catch(PDOException $e){
            die("字符集設置失敗:{$e->getMessage()} in line {$e->getLine()}");
        }
    }
    /**
     * @desc 合並PDO::exec和PDO::query為同一個方法,類似mysqli的query函數
     * @param1 string $sql,SQL語句
     * @param2 bool $all,是否獲取所有查詢結果
     */
    public function query($sql,$all = true){
        $sql = trim($sql);
        $str1 = substr($sql,0,7);
        $str2 = substr($sql,0,5);

        if($str1 === 'select ' || $str2 === 'desc ' || $str2 === 'show '){
            //檢查到是查詢語句,使用PDO::query函數
            try{
                $stmt = $this->pdo->query($sql);
                if($all){
                    return $stmt->fetchAll($this->fetch_mode);
                }else{
                    return $stmt->fetch($this->fetch_mode);
                }
            }catch(PDOException $e){
                die("數據庫查詢失敗{$e->getMessage()} in line {$e->getLine()}");
            }
        } else {
            //否則使用PDO::exec函數
            try{
                $row_num = $this->pdo->exec($sql);
                $last_id = $this->pdo->lastInsertId();
                //返回影響行數和lastInsertId,不是插入操作時lastInsertId為0
                return array(
                    'row_num' => $row_num,
                    'last_id' => $last_id
                );
            }catch(PDOException $e){
                die("數據庫操作失敗{$e->getMessage()} in line {$e->getLine()}");
            }
        }
    }
}
//測試 $spdo = new Dao(); echo '<pre>'; var_dump($spdo); 
print_r($spdo->query("select * from students")); 
print_r($spdo->query("insert into students values(null,'sdff',22)")); 
print_r($spdo->query("set names utf8"));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM