PHP 單例模式封裝MySQL-PDO
阿新 • • 發佈:2020-12-15
<?php class MyPDO{ private $type; //資料庫類別 private $host; //主機地址 private $port; //埠號 private $dbname; //資料庫名 private $charset; //字符集 private $user; //使用者名稱 private $pwd; //密碼 private $pdo; //儲存PDO物件 private static $instance; private function__construct($param) { $this->initParam($param); $this->initPDO(); $this->initException(); } private function __clone() { } public static function getInstance($param=array()){ if(!self::$instance instanceof self) self::$instance=newself($param); return self::$instance; } //初始化引數 private function initParam($param){ $this->type=$param['type']??'mysql'; $this->host=$param['host']??'127.0.0.1'; $this->port=$param['port']??'3306'; $this->dbname=$param['dbname']??'sel';$this->charset=$param['charset']??'utf8'; $this->user=$param['user']??'root'; $this->pwd=$param['pwd']??''; } //初始化PDO private function initPDO(){ try{ $dsn="{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}"; $this->pdo=new PDO($dsn, $this->user, $this->pwd); } catch (PDOException $ex) { $this->showException($ex); exit; } } //顯示異常 private function showException($ex,$sql=''){ if($sql!=''){ echo 'SQL語句執行失敗<br>'; echo '錯誤的SQL語句是:'.$sql,'<br>'; } echo '錯誤編號:'.$ex->getCode(),'<br>'; echo '錯誤行號:'.$ex->getLine(),'<br>'; echo '錯誤檔案:'.$ex->getFile(),'<br>'; echo '錯誤資訊:'.$ex->getMessage(),'<br>'; } //設定異常模式 private function initException(){ $this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); } //執行增、刪、改操作 public function exec($sql){ try{ return $this->pdo->exec($sql); } catch (PDOException $ex) { $this->showException($ex, $sql); exit; } } //獲取自動增長的編號 public function lastInsertId(){ return $this->pdo->lastInsertId(); } //判斷匹配的型別 private function fetchType($type){ switch ($type){ case 'num': return PDO::FETCH_NUM; case 'both': return PDO::FETCH_BOTH; case 'obj': return PDO::FETCH_OBJ; default: return PDO::FETCH_ASSOC; } } //獲取所有資料 ,返回二維陣列 public function fetchAll($sql,$type='assoc'){ try{ $stmt=$this->pdo->query($sql); //獲取PDOStatement物件 $type= $this->fetchType($type); //獲取匹配方法 return $stmt->fetchAll($type); } catch (Exception $ex) { $this->showException($ex, $sql); } } //獲取一維陣列 public function fetchRow($sql,$type='assoc'){ try{ $stmt=$this->pdo->query($sql); //獲取PDOStatement物件 $type= $this->fetchType($type); //獲取匹配方法 return $stmt->fetch($type); } catch (Exception $ex) { $this->showException($ex, $sql); exit; } } //返回一行一列 public function fetchColumn($sql){ try{ $stmt=$this->pdo->query($sql); return $stmt->fetchColumn(); } catch (Exception $ex) { $this->showException($ex, $sql); exit; } } } //測試 $param=array( ); $mypdo= MyPDO::getInstance($param); if($mypdo->exec("insert into news values (null,'11','1111',unix_timestamp())")) echo '自動增長的編號是:'.$mypdo->lastInsertId (); $list=$mypdo->fetchColumn('select count(*) from news'); var_dump($list); ?>