项目中经常要调用php连接数据库(没有使用PDO连接),使用设计模式中的单例模式做了简单的封装。另外可以做为客户端app连接数据库调用。
闲话少叙,具体如下:
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 }