<?php
class database
{
	var $host;	var $database;	var $user;	var $password;	var $connection;	var $queryID;	var $Record = array();	var $Row = 0;	var $debug = FALSE;	var $querycount = 0;	var $querycache = array();	var $lastQuery;	var $doQueries = TRUE;	var $techEmail = FALSE;	var $retries = 0;	var $alwaysReconnect = FALSE; var $tables=array();

	function __construct($database,$host,$user,$password)
	{
		$this->database = $database;
		//$this->connection = @mysqli_connect($host,$user,$password,TRUE);
		
		$this->connection = mysqli_connect($host, $user, $password, $database);	
		
		
	}


	function free($result = FALSE)
	{
		if ($result)
		{
			@mysqli_free_result($result);
			mysqli_close($this->connection);
		}
		else
		{
			@mysqli_free_result($this->queryID);
		  mysqli_close($this->connection);
		}
	}


	function query($sql, $logging=false)
	{
		$this->queryID = $this->queryReturnResultSet($sql, $logging);

		return $this->queryID;
	}


	function queryReturnResultSet($sql, $logging=false)
	{
	   global  $page, $config, $session;
	   
	   
		$startime = 0;

		if ($this->doQueries)
		{	
			$this->debug = 'emailAll';
			if ($this->debug == 'emailAll')
			{
				$result = mysqli_query($this->connection,$sql);
			}
			else
			{
				$result = @mysqli_query($this->connection,$sql);
			}

			if (!$result)
			{				
                $queryFailed = 'yes';

				$error = '<b>error</b>: '.mysqli_errno($this->connection).': Invalid result set returned, '.mysqli_error($this->connection).'<br />'.$sql.'<br/>'.$this->debugInfo();
				//trigger_error($error,E_USER_ERROR);
			}
			else
			{
                $queryFailed = 'no';
            }

			$this->querycount++;
			if (($this->debug) && ($this->querycount <= 100))
			{
				$this->lastQuery = $sql;

				if (isset($starttime))
				{
					list($usec, $sec) = explode(' ',microtime());
					$finishtime = ((float)$usec + (float)$sec);
	
					$time = sprintf('%0.6f',$finishtime - $starttime);				    
				}
				else
				{
					$time = -1;
				}
				
				$this->querycache[$this->querycount]['sql'] = $sql;
				$this->querycache[$this->querycount]['time'] = $time;
			}

			return $result;
		}
		else
		{
			global $page;
			$page->addToArray('informationMessages','<span style="color: #888;">Query disabled:</span> '.htmlentities($sql));
		}
	}


	function next_record($resultSet = FALSE,$debug = FALSE)
	{
		if ($resultSet)
		{
			return @mysqli_fetch_array($resultSet);
		}
		else
		{
			$this->Record = @mysqli_fetch_array($this->queryID,mysqli_ASSOC);
			$this->Row += 1;
			return is_array($this->Record);
		}
	}


	function numRows($resultSet = FALSE)
	{
		if ($resultSet)
		{
		
			return @mysqli_num_rows($resultSet);
		}
		
	}

	function num_rows($resultSet = FALSE)
	{
	
		return $this->numRows($resultSet);
	}


	function insert_id()
	{
		return $this->insertID();
	}

	function insertID()
	{
		return @mysqli_insert_id($this->connection);
	}

	function error($errorMsg,$die = TRUE,$email = TRUE)
	{
		if ($this->debug)
		{
			//trigger_error('Database error: '.$errorMsg.'<br />Error '.mysqli_errno($this->connection).': '.mysqli_error($this->connection),E_USER_ERROR);
		}
		else
		{
			if ($this->techEmail)
			{
				@mail($this->techEmail,'Database error on site '.$_SERVER['SERVER_NAME'],'Database error: '.$errorMsg.'<br />Error '.mysqli_errno($this->connection).': '.mysqli_error($this->connection));
			}
			//trigger_error('A database error occurred, please try again later.',E_USER_ERROR);
		}
	}


	function debugInfo()
	{
		$html = $lastQuery.'<br/><br/>';
		if ($this->debug)
		{
			if(function_exists('debug_backtrace')){
				$arr=debug_backtrace();
				foreach($arr as $call){
					if($call['function']=='debuginfo') continue;
					if($call['function']=='queryreturnresultset') continue;
					$html.='Function: '.$call['function'].' (File: '.$call['file'].' line:'.$call['line'].');<br>';
				};
			};		
			$html .= 'Did '.$this->querycount.' queries.<br />';
			while (list($key,$data) = each($this->querycache))
			{
				$html .= htmlentities($data['sql']).' '.$data['time'].'<br>';
			}
		}
		return $html;
	}
	
	function DelRow($_table, $_id)
	{
		if (($_table != '') && ($_id > 0))
		{
			$_result = $this->query('DELETE FROM '.$_table.' WHERE id = '.$_id);
		}
		
		if ($_result)
		{
			return true;
		}
		
		return false;
	}

	function GetRow($_fields, $_table, $_id)
	{
		if ($_id > 0)
		{
			$_result = array();
			$_res = $this->query('SELECT * FROM '.$_table.' WHERE id = '.$_id.' LIMIT 1;');
			while($_row = $this->next_record($_res)){			
				foreach($_fields as $_field)
				{
					$_result[$_field] = stripslashes($_row[$_field]);
				}
			};
			return $_result;
		}
		return null;
	}

	
	function GetRows($_fields, $_table, $_order_by, $_from, $_size, $_where_stmt = '')
	{
		$_result = array();
		$_cnt = 0;
		$_where_stmt = $_where_stmt != '' ? ' WHERE '.$_where_stmt : '';
		$_res = $this->query('SELECT * FROM '.$_table.' '.$_where_stmt.' ORDER BY '.$_order_by.' LIMIT '.$_from.', '.$_size.';');
    	while($_row = $this->next_record($_res)){
    		
			foreach($_fields as $_field)
			{
				$_result[$_cnt][$_field] = stripslashes($_row[$_field]);
 			}
			
			$_cnt++;
    	};
		
		return $_result;
	}
	
	
	function GetLastId($_table)
	{
		$_res = $this->query('SELECT id FROM '.$_table.' ORDER BY id DESC LIMIT 1;');
    	while($_row = $this->next_record($_res)){
    		return $_row['id'];
    	};
		return null;
	}
	
	function GetSql($_fields, $_table)
	{
		$_stmt = '';
		if ($_fields['id'] > 0)
		{
			$_stmt .= 'UPDATE '.$_table.' SET ';
			foreach($_fields as $_key => $_val)
			{
				if ($_val != '')
				{
					$_stmt .= $_key.' = \''.addslashes($_val).'\',';
				}
			}
			$_stmt = substr($_stmt, 0, strlen($_stmt)-1);	
			$_stmt .= ' WHERE id = '.$_fields['id'].';';
		}
		else
		{
			$_stmt = 'INSERT INTO '.$_table.' (';
			foreach($_fields as $_key => $_val)
			{
				if ($_val != '')
				{
					$_stmt .= $_key.',';
				}
			}			
			$_stmt = substr($_stmt, 0, strlen($_stmt)-1);	
			$_stmt .= ') VALUES (';
			
			foreach($_fields as $_key => $_val)
			{
				if ($_val != '')
				{
					$_stmt .= '\''.addslashes($_val).'\',';
				}
			}			
			$_stmt = substr($_stmt, 0, strlen($_stmt)-1);	
			$_stmt .= ');';
		}
		
		return $_stmt;
	}
	
	function SetRow($_fields, $_table)
	{
		if ((count($_fields) > 0) && ($_table != ''))
		{
			$_stmt = $this->GetSql($_fields, $_table);
			//print $_stmt;
			$_result = $this->query($_stmt);
		}
		
		if ($_result)
		{
			return true;
		}
		
		return false;
	}

	//Check if the table exists in the database
	function table_exist($tablename){
		if(in_array($tablename, $this->tables)){
			return true;
		}else{
    		return false;
		}
  	}
	
	function data_row($sql)
  {
           $res=$this->query($sql);
           if($this->num_rows($res))
           {   
     	  	 $row=$this->next_record($res);
           return $row;
           }
           else
           return false;
  }
  
  function data_table($sql)
  {
  
  
    	  	$res=$this->query($sql);
           if($this->num_rows($res))    			
          {
             while($row=$this->next_record($res))
             $rows[]=$row;
             return $rows;
       		}
           else
           return false;	
           
  }
	
}



?>