<?
   //namespace lib\database;
   class db
   {
      private $host, $user, $pwd, $driver, $dbName;
	  private $conn;
	  
	  function __construct($type="", $db="")
	  {
	     global $CONFIG;
		 
		 $this->host= $CONFIG['HOST'];
		 $this->user= $CONFIG['USER'];
		 $this->pwd= $CONFIG['PWD'];
		 $this->driver= $CONFIG['DRIVER'];
		 $this->dbName= (!empty($db))? $db:$CONFIG['DBNAME'];
		 

		 if(!$CONFIG['DBHANDLE'])
		 {				 			
			$this->dbConnect();	
		 }	 	
	  }
	  
	  private function dbConnect()
	  {		
		$mysqli= new mysqli($this->host, $this->user, $this->pwd, $this->dbName);   
		if($mysqli->connect_error){
			die('Connect error ('. $mysqli->connect_errno(). ')'. $mysqli->connect_error);
		 }		    
		
		 if($mysqli){		 		 
		    $this->conn= $mysqli;		    	
		 }
	  }	  	  
	  
	  public function dbQuery($sql)
	  {
		 //$result=mysqli_query($this->conn, $sql);// or die(mysqli_error($this->conn));
		 //if(!$result) header('HTTP/1.0 500 '. mysqli_error($this->conn));
		 try{
			$result=mysqli_query($this->conn, $sql);// or die(mysqli_error($this->conn));
			if($result){
				return $result;
			}
			else throw new Exception(mysqli_error($this->conn));
		}
		catch (Exception $e) {			
			header('HTTP/1.0 400 '. $e->getMessage());			
		}
		 //return $result;
	  }
	  
	  public function dbFetchRow($qry)
	  {
	     return mysqli_fetch_row($qry);
	  }
	  
	  public function dbFetchArray($qry)
	  {
	     return mysqli_fetch_array($qry);
	  }
	  
	  public function dbFetchObject($sql)
	  {
	     if(is_string($sql))
		 {
		    if($this->conn) 
			$result= mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
			return mysqli_fetch_object($result);
		 }
		else
		   return mysqli_fetch_object($sql);
	  }

       public function dbFetchAssoc($sql)
       {
           if(is_string($sql))
           {
               if($this->conn)
                   $result= mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
               return mysqli_fetch_assoc($result);
           }
           else
               return mysqli_fetch_assoc($sql);
       }
	  
	  public function dbNumRow($sql)
	  {
	     $result= mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
		 return mysqli_num_rows($result);
	  }
	  
	  public function dbQNumRow($qry)
	  {
		 return mysqli_num_rows($qry);
	  }
	  
	  public function dbNumFields($qry)
	  {
	     return mysqli_num_fields($qry);
	  }	  	 
	  
	  public function dbFreeResult($qry)
	  {
	     mysqli_free_result($qry);
	  }
	  
	  public function lastID(){
          return mysqli_insert_id($this->conn);
	  }
	  
	  function __destruct(){
         if($this->conn)  mysqli_close($this->conn);
		  
	  }   
   }      
?>