日期:2012-06-08 浏览次数:20569 次
<?php
class Core{
/*对数组进行继承*/
static function inHerit($arr_orgin,$arr_output){
return array_merge($arr_orgin,$arr_output);
}
/*打印错误*/
static function throwError($errmsg){
echo '<p>error:'.$errmsg.'</p>';
exit();
}
}
?>
<?php
class db{
private $result = array();
private $connector = array();
private $configs = array();
private $active = 0;
private $default_config = array(
'dbtype' => 'mysql',
'index' => 0,'user' => 'root', 'pwd' => '' ,'host' => 'localhost' ,'port'=> 3306,'charset' => 'utf8' ,'dbname' => null
);
/*初始化*/
public function __construct($config = array()){
if($config) $this->connect($config);
}
public function __destruct(){
foreach($this->connector as $index => $connect)
$this->{'_'.$this->configs[$index]['dbtype'].'_close'}($connect);
}
private function _mysql_close($connect){
mysqli_close($connect);
}
/*选择连接*/
public function selectConnect($index){
return isset($this->connector[$index]) && (($this->active = $index) || true);
}
/*建立连接*/
public function connect($config){
(!isset($config['index'])) && $config['index'] = $this->default_config['index']++ ;
$config = Core::inHerit($this->default_config,$config);
!in_array($config['dbtype'],array('mysql')) && Core::throwError('未支持的数据库类型');
extract($config);
$this->configs[$index] = $config;
$this->{'_'.$config['dbtype'].'_connect'}($user, $pwd,$host,$dbname,$charset,$index,$port);
}
private function _mysql_connect($user = 'root', $pwd = '' ,$host = 'localhost' ,$dbname = null,$charset = 'utf8' ,$index = 0 ,$port = 3306){
$this->connector[$index] = mysqli_connect ( $host, $user, $pwd , null, $port) or Core::throwError(mysql_error());
$this->active = $index;
if($dbname) $this->selectDb($dbname,$charset);
}
/*取得当前连接*/
private function _getConnect(){
return $this->connector[$this->active];
}
/*取得当前连接使用的数据库类型 带参数自动拼接为函数名*/
private function _getDbTypeFunc($funcname = null){
$dbtype = $this->configs[$this->active]['dbtype'];
return $funcname?'_'.$dbtype.'_'