項目中常常要調用php鏈接數據庫(沒有使用PDO鏈接),使用設計模式中的單例模式作了簡單的封裝。另外能夠作爲客戶端app鏈接數據庫調用。php
閒話少敘,具體以下:mysql
1 <?php 2 3 class Db { 4 static private $_instance; 5 static private $_connectSource; 6 private $_dbConfig = array( 7 'host' => '127.0.0.1', 8 'user' => 'root', 9 'password' => '', 10 'database' => '', 11 ); 12 13 private function __construct() { 14 } 15 16 static public function getInstance() { 17 if(!(self::$_instance instanceof self)) { 18 self::$_instance = new self(); 19 } 20 return self::$_instance; 21 } 22 23 public function connect() { 24 if(!self::$_connectSource) { 25 self::$_connectSource = @mysql_connect($this->_dbConfig['host'], $this->_dbConfig['user'], $this->_dbConfig['password']); 26 27 if(!self::$_connectSource) { 28 throw new Exception('mysql connect error ' . mysql_error()); 29 //die('mysql connect error' . mysql_error()); 30 } 31 32 mysql_select_db($this->_dbConfig['database'], self::$_connectSource); 33 mysql_query("set names UTF8", self::$_connectSource); 34 } 35 return self::$_connectSource; 36 } 37 }