PHP PDO的簡單封裝(使用命名空間方式)
阿新 • • 發佈:2019-02-19
try exec函數 sta array demo state sdf 模式 引入
直接上代碼:要點都在註釋中了
<?php namespace core; //引入全局空間類:PDO相關的3個類 use \PDO,\PDOStatement,\PDOException; class SimplePDO{ 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‘] ?? ‘chz‘; $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); $str = substr($sql,0,7); if($str === ‘select ‘){ //檢查到是select語句,使用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 SimplePDO(); 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"));
PHP PDO的簡單封裝(使用命名空間方式)