<?php !defined('APP_DIR') ? die('acceess not defined') : '';
class db {
    /**
     * 数据库读连接
     *
     * @var mysql_connect
     */
    private $_connect_r = null;
    
    /**
     * 数据库写连接
     *
     * @var mysql_connect
     */
    private $_connect_w = null;
    
    /**
     * 数据库连接池
     *
     * @var array
     */
    static $instance = array();
    
    /**
     * 所有的SQL
     *
     * @var array
     */
    static $sqls = array();
    
    
    /**
     * 数据库连接初始化
     *
     */
    public function __construct($db='default'){
        $db_config = tool::config("database.$db");
        
        if ( is_array($db_config['host']) ){
            $db_num = count($db_config['host']);
            srand(time());
            $rand = rand(0,$db_num-1);
            $db_host = $db_config['host'][$rand];
        }else {
            $db_host = $db_config['host'];
        }
        //echo $db_host;die();
        
        //数据库连接
        $_connect_r = mysql_connect("{$db_host}:{$db_config['port']}", $db_config['user'], $db_config['pass']);
        if ( $_connect_r != false ) {
        	$this->_connect_w = $this->_connect_r = $_connect_r;
        	$this->select_db($db_config['database']);
        }else {
            die('Can not conect to database!');
        }
        if (!is_null($this->_connect_r)) {
            mysql_query("set names gbk", $this->_connect_r);
        }
    }
    
    /**
     * 连接数据库
     *
	 * @example db::instsance()
     */
    static public function instance($db='default'){
        if (isset(self::$instance[$db])) {
            return self::$instance[$db];
        }else {
            self::$instance[$db] = new db($db);
        }
        return self::$instance[$db];
    }
    
    
    public function select_db($db_name){
        $sql = "USE $db_name";
        mysql_query($sql,$this->_connect_r);
    }
    /**
     * 执行SQL，并返回数据库结果
     *
     * @param unknown_type $sql
     */
    public function query($sql){
        self::$sqls[] = $sql;
        if ( preg_match('/\s?(insert|update|delete)(.+)/i', $sql, $matchs) ) {
            return @mysql_query($sql, $this->_connect_w);
        }else {
            return @mysql_query($sql, $this->_connect_r);
        }
    }
    
    /**
     * 获取单个数据
     *
     * @param array $query_struct
     */
    public function get($sql){
        self::$sqls[] = $sql;
        if (preg_match('/\s?select(.+)/i',$sql, $matchs)) {
        	$rs = mysql_query($sql, $this->_connect_r);
        	if ($rs == false) {
        		return array();
        	}
        	$rt = mysql_fetch_assoc($rs);
        	return $rt;
        }else {
            return array();
        }
    }
    
    /**
     * 获取全部数据
     *
     * @param array $query_struct
	 * @exaple db::instsance()->get_all($sql);
     */
    public function get_all( $sql, $key_field = NULL ){
        self::$sqls[] = $sql;
        if (preg_match('/\s?select(.+)/i',$sql, $matchs)) {
        	$rs = mysql_query($sql, $this->_connect_r);
			//print_r($rs);
        	if ($rs == false) {
        		return array();
        	}
        	$rt = array();
			//print_r(mysql_fetch_assoc($rs));
        	while ( ($row = mysql_fetch_assoc($rs)) != false ){
        	    if ( $key_field == null || !key_exists($key_field,$row) ) {
        	    	$rt[] = $row;
        	    }else {
        	        $rt[$row[$key_field]] = $row;
        	    }
    		}
        	return $rt;
        }else {
            return array();
        }
    }
    
    /**
     * 获取满足条件的数量
     *
     * @param array $query_struct
     */
    public function count( $sql ){
        self::$sqls[] = $sql;
        if (preg_match('/\s?select(.+)/i',$sql, $matchs)) {
        	$rs = mysql_query($sql, $this->_connect_r);
        	if ($rs == false) {
        		return 0;
        	}
        	$row = mysql_fetch_assoc($rs);
        	$rt = $row['COUNT(*)'];
        	return $rt;
        }else {
            return 0;
        }
    }
    
    /**
     * 保存数据，包括添加和修改
     *
     * @param array $data
     */
    public function save( $sql ){
        self::$sqls[] = $sql;
        if (preg_match('/\s?insert(.+)/i',$sql, $matchs)) {
            $rs = mysql_query($sql, $this->_connect_w);
            //echo $this->_connect_w."<br />";
            //echo("****************".mysql_insert_id($this->_connect_w));
            if ($rs == false) {
            	return false;
            }
            
            
            //die();
            return mysql_insert_id($this->_connect_w);
            
        }elseif (preg_match('/\s?update(.+)/i',$sql, $matchs)){
            return mysql_query($sql, $this->_connect_w);
        }
        return false;
    }
    
    /**
     * 删除满足条件的数据
     *
     * @param array $query_struct
     */
    public function delete( $sql ){
        self::$sqls[] = $sql;
        if (preg_match('/\s?delete(.+)/i',$sql, $matchs)) {
            return mysql_query($sql,$this->_connect_w);
        }
        return false;
    }
    
    public function fetch_arrays($sql){
        self::$sqls[] = $sql;
        $rs = @mysql_query($sql, $this->_connect_r);
        $rt = array();
        while($row = mysql_fetch_array($rs)){
            $rt[] = $row;
        }
        return $rt;
    }
    
    /**
     * 获取表的字段
     *
     * @param unknown_type $table
     */
    public function get_table_fields($database,$table){
        $rs = mysql_list_fields($database,$table,$this->_connect_r);
		if($rs){
			$columns = mysql_num_fields($rs);
			$cols = array();
			for ($i = 0; $i < $columns; $i++) {
				$cols[] = mysql_field_name($rs, $i);
			}
			return $cols;
		}
		return array();
        
    }
    
    public function close_db(){
        mysql_close($this->_connect_r);
        //mysql_close($this->_connect_w);
    }
    
    static public function close(){
        foreach (self::$instance as $k => $_db){
            $_db->close_db();
            unset(self::$instance[$k]);
        }
    }
}
?>