<?php /** * 數據庫模式:在一個地方統一處理數據庫鏈接 */ class DbConfig { public static $db_config = array( "test"=>array("host"=>"localhost:3306","user"=>"root","password"=>"123456","db"=>"test") ); } class DbDriver{ private $_db_handle; protected $table; public function __construct($type="mysql",$config_type="test"){ $classname = ucwords($type)."Handle"; $this->_db_handle = $classname::getDbHandle($config_type); } protected function query($sql){ $this->_db_handle->query($sql); } protected function fetchAll($sql){ $ret = array(); $query = mysql_query($sql,$this->_db_handle); if(empty($query)) return $ret; while($row= mysql_fetch_array($query,MYSQL_ASSOC)){ $ret[] = $row; } return $ret; } } class MysqlHandle{ public static $_handle = array(); public static function getDbHandle($config_type){ if(!isset(DbConfig::$db_config[$config_type])){ throw new Exception("Error db config "); } $config = DbConfig::$db_config[$config_type]; $db_key = md5(implode(":",$config)); if(empty(self::$_handle[$db_key])) { $handle = mysql_connect($config["host"],$config["user"],$config["password"]); mysql_select_db($config["db"],$handle); self::$_handle[$db_key]=$handle; } return self::$_handle[$db_key]; } } class Country extends DbDriver{ public function __construct(){ parent::__construct(); $this->table = "country"; } public function selectAll(){ $sql = "select * from ".$this->table; echo $sql; return $this->fetchAll($sql); } } $country_obj = new Country(); print_r($country_obj->selectAll());