<?
Class db{
	private $Link = null;
	
  public function __construct(){
  	global $config;
		$this->connect($config);      
	}
	
  function Select($table, $fields = "*", $cond = false, $end = false){
		 $fields  = empty($fields) ? '*' : $fields;
     $cond    = empty($cond) ? false : $cond;
     $end     = empty($end) ? false : $end;
     $this->run("SELECT {$fields} FROM {$table}".($cond ? " WHERE ".$cond : '').($end ? ' '.$end : ''));
     return $this->FetchAllAssoc();
  }
  
  function SelectSet($table, $fields = "*", $cond = false, $end = false,$count = 10, $page = 1){
		 $fields  = empty($fields) ? '*' : $fields;
     $cond    = empty($cond) ? false : $cond;
     $end     = empty($end) ? false : $end;
     $page		= (int)$page>1 ? (int)$page : 1;
     $query = "SELECT {$fields} FROM {$table}".($cond ? " WHERE ".$cond : '').($end ? ' '.$end : '');
      if(strstr($query, 'DISTINCT')){
        $rep = array(
            "/SQL_CALC_FOUND_ROWS/i"=>"",
            "/DISTINCT/i"=>"",
            "/SELECT/i"=>"SELECT DISTINCT SQL_CALC_FOUND_ROWS");
        $query  = preg_replace(array_keys($rep), array_values($rep), $query,1);
      }else{
        $rep    = array(
          "/SQL_CALC_FOUND_ROWS/i"=>"",
          "/SELECT/i"=>"SELECT SQL_CALC_FOUND_ROWS");
        $query  = preg_replace(array_keys($rep), array_values($rep), $query,1);
      }
      $query.=" LIMIT ".intval(($page-1)*$count).", ".intval($count); 
      $this->run($query);
      $result = $this->FetchAllAssoc();
      if($result){
        $this->run("SELECT FOUND_ROWS() as c");
        $db = $this->FetchAssoc();
        return array('result'=>$result,'pages'=>PagesList($page,$db['c'],$count),'count'=>count($result),'NumRows'=>$db['c']); 
      }else{
        return false;
      }
  }
  
  public function SelectRecord($table, $fields = "", $cond = false, $end = false){
     $fields  = empty($fields) ? '*' : $fields;
     $cond    = empty($cond) ? false : $cond;
     $end     = empty($end) ? false : $end;
     $this->run("SELECT {$fields} FROM {$table}".($cond ? " WHERE ".$cond : '').($end ? ' '.$end : '')." LIMIT 1");
     return $this->FetchAssoc();
  }
  
  function run($query){
    $this->insert_id      = 0;
    $this->affected_rows  = 0; 
    $this->count          = 0;
    $this->query          = $query; 
    
    $this->Result    = mysql_query($query, $this->Link);
		$this->log[] = $query;
    if($error = mysql_error()){ 
      $this->error[] = array('query'=>$query,'error'=>$error); 
      $this->Result = false;
      return false;
    }
 
    $_type = explode(" ",trim($query));
    $_type = trim(strtolower($_type[0]));
    switch($_type){
			case 'insert':
				$this->insert_id = mysql_insert_id($this->Link);
			break;
			case 'update':
				$this->affected_rows = mysql_affected_rows($this->Link);
			break;
		}
    return $this->Result;
  }
  
	public function NumRows($result = NULL){
    if ( is_null($result) ) { $result = $this->Result; }
		return $result ? mysql_num_rows($result) : 0;
	} 
  
  function FetchAssoc($result = NULL){
    if (is_null($result)){ 
      $result = $this->Result; 
      if($result==false){
        return false;   
      }
    }
    $array = mysql_fetch_assoc($result);
    if($array){
      mysql_free_result($result);
      $this->count = 1;
      return $array;
    }  
    return false;
  }
  
	public function FetchAllAssoc($result = NULL){
    if (is_null($result)){ 
      $result = $this->Result;
      if($result==false){
        return false;
      }  
    }

    $i = 0;
    $list = array();
		while ($row=mysql_fetch_assoc($result)){ 
			$list[$i] =  $row;
			$i++;
		}  
		mysql_free_result($result);
    $this->count = $i;
    return $i>0 ? $list : false;
	}
	
	public function Quote($string, $quote_char = "'"){
		return $quote_char.mysql_real_escape_string($string,$this->Link).$quote_char;
	}
	
  public function Update($table, $rows = "", $cond = false, $quote=true){
    $set = $this->arrRow($rows,$quote);
    if(empty($set)) return false; 
    return $this->run("UPDATE {$table} SET ".$set.($cond ? ' WHERE '.$cond : '')."");
  }  
       
  public function Insert($table,$rows='',$quote=true){
    $set = $this->arrRow($rows,$quote);
    if(empty($set)) return false;   
    $this->run("INSERT INTO {$table} SET ".$set);
    return $this->insert_id>0 ? $this->insert_id : ($res);
  }
  
  function arrRow($rows,$quote = true){
		if(is_array($rows)){
      $set = array();
      foreach($rows as $key=>$val){
				if($val==="SQL_TIME_NOW()"){
					$set[] = "{$key}=NOW()";
				}else{
					$set[] = "{$key}=".($quote ? $this->Quote($val) : $val);	
				}
      }
      $set = implode(", ",$set);
    }else{
      $set = $rows;
    }
    return $set;
	}
	
	function Dissconnect(){
		@mysql_close($this->Link) or die("Ошибка MySQL Disconnect: ".mysql_error());
	}
	
	function connect($config){
    $this->Link = @mysql_connect($config['db']['host'], $config['db']['user'], $config['db']['password']) or die("Извините, сервер временно недоступен! Попробуйте зайти попозже. <br> ".mysql_error());
		@mysql_query('SET NAMES "utf8"', $this->Link);
    @mysql_select_db($config['db']['name'], $this->Link) or die("Ошибка подключения MySQL. <br> ".mysql_error());
	}
  
	public function __destruct(){
		$this->Dissconnect();
	}
	
}
?>