PHP 單例模式封裝MySQL
阿新 • • 發佈:2020-12-15
<?php class MySQLDB { private $host; // 主機地址 private $port; // 埠號 private $user; // 使用者名稱 private $pwd; // 密碼 private $dbname; // 資料庫名 private $charset; // 字符集 private $link; // 連線物件 privatestatic $instance; private function __construct($param){ $this->initParam($param); $this->initConnect(); } private function __clone(){ } // 獲取單例 public static function getInstance($param= array()){ if(!self::$instance instanceof self){ self::$instance= new self($param); } return self::$instance; } // 初始化引數 private function initParam($param){ $this->host= $param['host']??'127.0.0.1'; $this->port= $param['port']??'3306'; $this->user= $param['user']??''; $this->pwd= $param['pwd']??''; $this->dbname= $param['dbname']??''; $this->charset= $param['charset']??'utf8'; } // 連線資料庫 private function initConnect(){ $this->link= @mysqli_connect($this->host, $this->user, $this->pwd, $this->dbname, $this->port); if(mysqli_connect_error()){ echo '資料庫連線失敗<br>'; echo '錯誤資訊:'.mysqli_connect_error(),'<br>'; echo '錯誤碼:'.mysqli_connect_errno(),'<br>'; exit; }else{ echo '資料庫連線成功!'; } mysqli_set_charset($this->link, $this->charset); } // 資料庫的增刪改查 private function execute($sql){ if(!$rs= mysqli_query($this->link, $sql)){ echo 'SQL語句執行失敗<br>'; echo '錯誤資訊:'.mysqli_error($this->link),'<br>'; echo '錯誤碼:'.mysqli_errno($this->link),'<br>'; echo '錯誤的SQL語句:'.$sql,'<br>'; exit; } return $rs; } // 執行增刪改語句 public function exec($sql) { $key=substr($sql,0,6); if(in_array($key,array('insert','update','delete'))) return $this->execute($sql); else{ echo '非法訪問<br>'; exit; } } //獲取自動增長的編號 public function getLastInsertId() { return mysqli_insert_id($this->link); } //執行查詢語句 private function query($sql) { if(substr($sql,0,6)=='select' || substr($sql,0,4)=='show' || substr($sql,0,4)=='desc'){ return $this->execute($sql); }else{ echo '非法訪問<br>'; exit; } } //匹配所有資料 public function fetchAll($sql,$type='assoc') { $rs=$this->query($sql); $type=$this->getType($type); return mysqli_fetch_all($rs,$type); } //匹配一維陣列 public function fetchRow($sql,$type='assoc') { $list=$this->fetchAll($sql,$type); if(!empty($list)) return $list[0]; return array(); } //匹配一行一列 public function fetchColumn($sql) { $list=$this->fetchRow($sql,'num'); if(!empty($list)) return $list[0]; return null; } //獲取匹配型別 private function getType($type) { switch($type){ case 'num': return MYSQLI_NUM; case 'both': return MYSQLI_BOTH; default: return MYSQLI_ASSOC; } } } $param= array( 'user' => 'root', 'pwd' => '', 'dbname' => 'sel' ); $db= MySQLDB::getInstance($param); // 查詢所有資訊 $listAll= $db->fetchAll('select * from news'); var_dump($listAll); // 查詢一條記錄 $listRow= $db->fetchRow('select * from news'); var_dump($listRow); // 查詢一個欄位 $listColumn= $db->fetchColumn('select * from news'); var_dump($listColumn); ?>