<?php
/**********************************************************************************************************************
File Name 	: DbInterface.php
Purpose 		: This file contains MySqlAdo class which manages db functions and 
				  provides methods to navigate through the tables as well as manipulate records
Creation Date 	: 04/12/2005 04:35PM
***********************************************************************************************************************/


/**********************************************************************************************************************
													class MysqlAdo
					This class connects to MySQL and takes care of add,update and delete functionality
**********************************************************************************************************************/
class MySqlAdo
{
	var $is_db_connected;	//Identifies whether mysql is connected or not
	var $dblink;  			//link to database if connected
	var $insert_array; 		//Common associative array for values to be used in insert query;
	var $update_array;		//Common associative array for values to be used in update query;
	var $query_res_id;  	//Common resource identifier which can be used to fetch records by MySQL_Fetch_Array etc.
	var $sql_query_string;	//Common variable for SQL Query string
	var $affected_rows;		//Count of rows affetcted by add,update,delete statements
	var $hostname;			//MySQL Hostname
	var $username;			//MySQL Username
	var $password;			//MySQL Password
	var $dbname;			//Database Name
	var $err;				//Error if any
	
/*======================================================================================================================
Constructor -> connect to MySQL when instantiated.
======================================================================================================================*/
	function MySqlAdo($hostname="localhost",$username="thevugro_bannari",$password="bannari",$dbname="thevugro_bannarimills")
	{	
		//If required set a custom error handling function
		$this->hostname=$hostname;
		$this->username=$username;
		$this->password=$password;
		$this->dbname=$dbname;
		
		$this->dblink=MySQL_Connect($this->hostname,$this->username,$this->password); //Connect to MySQL;
		
		if(!$this->dblink)
		{
			trigger_error("Couldn't Connect to MySQL Server",E_USER_ERROR); 
			$this->err="Couldn't Connect To MySQL";
			die();
		}
		else
		{
			if(!MySQL_Select_Db($this->dbname))
			{
				trigger_error("Couldn't Select Database ".$conf->DBNAME,E_USER_ERROR);
				$this->err="Couldn't Select Database";
				MySQL_Close();
				die();								
			}
			else
			{
				$this->is_db_connected=true;
			}
		}	
	}
	
/*=====================================================================================================================
Following function adds the data to the database.
Arguments :- $table_name ->	name of the table as string

Returns None
======================================================================================================================*/
	function AddRecord($table_name)
	{
		if($this->is_db_connected==true)
		{
			$this->sql_query_string="INSERT INTO $table_name ";
		//	print_r($this->insert_array);
			foreach($this->insert_array as $key=>$value)
			{
				$cols[]=$key;
				$vals[]=$value;	
			}
			
			$this->sql_query_string .="(".implode($cols,",").")";
			$this->sql_query_string .=" VALUES(".implode($vals,",").")";			
			
			$this->query_res_id=MySQL_Query($this->sql_query_string);
		
			if(!$this->query_res_id)
			{
				//echo $this->sql_query_string;
				trigger_error(MySQL_Error(),E_USER_ERROR);
				$this->err=MySQL_Error();
				die();
			}
			else
			{
				
				//$this->affected_rows=MySQL_Affected_Rows($this->query_res_id);
				$this->last_insert_id=mysql_insert_id();
				
				$this->affected_rows=1;
				$this->insert_array="";
			}
		}
		
		else
		{
			trigger_error(MySQL_Error(),E_USER_ERROR);
			$err=MySQL_Error();
			die();
		}	
		
	}

/*=====================================================================================================================
Following function updates the data in the given table
Arguments :- $table_name 		->name of the table as string
			 $sql_where_string 	->sql string containing where condition (Use the word "where" in condition)

Returns None
======================================================================================================================*/
	function UpdateRecord($table_name,$sql_where_string)
	{
		if($this->is_db_connected==true)
		{
			$this->sql_query_string="UPDATE $table_name SET ";
			$counter=0;
			
			if(count($this->update_array)==1)
			{
				$cols_val=key($this->update_array)."=".$this->update_array[key($this->update_array)];
			}
			else
			{
				foreach($this->update_array as $key=>$value)
				{
					$cols_val .=$key."=".$value.",";
				}
				$cols_val=substr($cols_val,count($cols_val)-1,-1);
			}
			
			$this->sql_query_string .=$cols_val;
			$this->sql_query_string .=" WHERE ".$sql_where_string;
			
			$this->query_res_id=MySQL_Query($this->sql_query_string);
			
			if(!$this->query_res_id)
			{
				//echo $this->sql_query_string;
				trigger_error(MySQL_Error(),E_USER_ERROR);
				$this->error_messages[]=$error->fatal_error;
				MySQL_Close();
				die();
			}
			
			else
			{
				
				//$this->affected_rows=MySQL_Affected_Rows($this->query_res_id);
				$this->affected_rows=@MySQL_Affected_Rows($this->query_res_id);
                $this->update_array="";
			}
			
		}	
	}

/*=====================================================================================================================
Following function deletes the data from the given table.
Arguments :- $table_name 		->name of the table as string
			 $sql_where_string 	->sql string containing where condition (Do not use the word "where" in the condition)

Returns None
======================================================================================================================*/
	function DeleteRecord($table_name,$sql_where_string)
	{
		if($this->is_db_connected==true)
		{
			$this->sql_query_string="DELETE FROM $table_name WHERE ".$sql_where_string;
			$this->query_res_id=MySQL_Query($this->sql_query_string);
			
			if(!$this->query_res_id)
			{
				trigger_error(MySQL_Error(),E_USER_ERROR);
				$this->err=MySQL_Error();
				MySQL_Close();
				die();
			}
			else
			{
				$this->affected_rows=MySQL_Affected_Rows(); //Do not spcify link identifier,since we want to use the last identifier
			}
			
		}	
	}

};
//****************************************************End Of Class******************************************************




/**********************************************************************************************************************
													class Recordset
					This class is used specially for retreiving records. For navigation,pagination etc.
***********************************************************************************************************************/
class Recordset extends MySqlAdo
{
	var $row;				//Single row in the form of object
	var $result_set;		//Array of row objcts
	var $page_limit;		//Limit of records for pagination
	var $no_of_pages;		//Pages returned based on page_limit
	var $no_of_records;     //No of records in the recordset
	var $cursor;			//Pointer to the current record
	var $sql_string;		//common sql query string
	var $query_res;			//common resource identifier for queries
	var $page;				//Single page
	var $pages;				//Array of rows grouped together as per no_of_pages

/*======================================================================================================================
Constructor -> Initialize some default values.
======================================================================================================================*/
	function Recordset()
	{
		parent::MySQlAdo();		//Call constructor of the parent to connect to MySql
		if($this->is_db_connected!=true)
		{
			trigger_error("MySQL Not Connected",E_USER_ERROR);
			$this->err="MySQL Not connected";
			die();
		}
	}

/*=====================================================================================================================
Following function returns the data based on the given query and sets various properties of recordset
Arguments :- $sql_query_string	-> sql select query without limit parameter. Spcify limit as second argument
			 $page_limit 		-> How many records per page? as number (Optional argument)

Returns None
======================================================================================================================*/
	function GetRecords($sql_query_string,$page_limit=0)
	{
            if(!empty($this->result_set))
            {
              $this->result_set="";
            }
            
			$this->page_limit=$page_limit;
			$this->sql_string=$sql_query_string;
			$this->query_res=MySQL_Query($this->sql_string);
		
			if(!$this->query_res)
			{
			//	trigger_error(MySQL_Error(),E_USER_ERROR);
				$this->err=MySQL_Error();
				MySQL_Close();
				die();
			}
			else
			{
				$this->no_of_records=MySQL_Num_Rows($this->query_res);
			}
			
			if($page_limit==0 || $page_limit=="")
			{
					$this->no_of_pages=1;
					
					while($this->row=MySQL_Fetch_Object($this->query_res))
					{
						$this->result_set[]=$this->row;
					}
					$this->cursor=0;		
			}
			else
			{
				$this->no_of_pages=$this->no_of_records/$page_limit; //Find no of pages
				
				if(gettype($this->no_of_pages)=="double")
				{
					$this->no_of_pages=ceil($this->no_of_pages);
				}
				
				$updated_pages=0;  //updated pages is the number which will increment with no of pages
				$pages_counter=0;
				
				for($i=0;$i<$this->no_of_pages;$i++)
				{
					$new_sql_string=$this->sql_string." LIMIT $updated_pages,$page_limit"; 
					$this->query_res=MySQL_Query($new_sql_string);
					
					if($this->query_res=="")
					{	$this->err=MySQL_Error();
						trigger_error("Error in select query: ".$this->err,E_USER_ERROR);
						
						MySQL_Close();
						die();
					}
					else
					{
						while($this->row=MySQL_Fetch_Object($this->query_res))
						{
							$this->result_set[]=$this->row;
						}
						
						$this->pages[$pages_counter]=$this->result_set;
					}
					
					$updated_pages+=$page_limit;
					$pages_counter+=1;
					$this->result_set="";
				}
				
				$this->cursor=0;
			}	
	}	
		

		/*=====================================================================================================================
Following function returns the data based on the given query and sets various properties of recordset
Arguments :- $sql_query_string	-> sql select query without limit parameter. Spcify limit as second argument
			 $page_limit 		-> How many records per page? as number (Optional argument)

Returns None
======================================================================================================================*/
	function GetRecordsByPage($sql_query_string,$page_id,$page_limit=0)
	{
            if(!empty($this->result_set))
            {
              $this->result_set="";
            }
            

			$this->page_limit=$page_limit;
			$this->sql_string=$sql_query_string;

			if(!eregi("SQL_CALC_FOUND_ROWS",$this->sql_string))
				$new_sql_string=eregi_replace("^SELECT"," SELECT SQL_CALC_FOUND_ROWS ",trim($this->sql_string) );

			
			
				//echo $this->sql_string;	
			
			if($page_limit==0 || $page_limit=="")
			{
				$this->query_res=MySQL_Query($new_sql_string);	
				if(mysql_error())
				{
					$this->err=MySQL_Error();
						trigger_error("Error in select query: ".$this->err,E_USER_ERROR);
						
						MySQL_Close();
						die();
				}
				$this->no_of_records=mysql_num_rows($this->query_res);

					$this->no_of_pages=1;
					
					while($this->row=MySQL_Fetch_Object($this->query_res))
					{
						$this->result_set[]=$this->row;
					}
					$this->cursor=0;		
			}
			else
			{	
				
				$updated_pages=($page_id-1)*$page_limit;
				$new_sql_string.=" LIMIT $updated_pages,$page_limit"; 
				$this->query_res=MySQL_Query($new_sql_string);
				//echo $new_sql_string;
				
				
				if(mysql_error())
				{
					$this->err=MySQL_Error();
						trigger_error("Error in select query: ".$this->err,E_USER_ERROR);
						
						MySQL_Close();
						die();
				}
				$this->no_of_records=mysql_num_rows($this->query_res);

				while($this->row=MySQL_Fetch_Object($this->query_res))
				{
					$this->result_set[]=$this->row;
				}

				if($this->query_res=MySQL_Query("SELECT FOUND_ROWS() total_records "))
				{
							$this->row=MySQL_Fetch_Object($this->query_res);
							$this->total_records=$this->row->total_records;
							
							$this->no_of_pages=ceil($this->total_records/$page_limit);

							//$this->total_pages=ceil($this->total_records/$page_limit);
						//echo $this->no_of_pages;
						
			     }
				else
				{

					$this->err=MySQL_Error();
						trigger_error("Error in select query: ".$this->err,E_USER_ERROR);						
						MySQL_Close();
						die();
						
				}				
				
					
					
				
				
				$this->cursor=0;
			}	
	}	
/*=====================================================================================================================
Following function moves the cursor forward in the resultset. One record at a time
Arguments :- None

Returns next row in the resultSet;
======================================================================================================================*/
	function MoveNext()
	{
		static $current_pos;
		if($this->cursor>=count($this->result_set))
		{
			$this->cursor-=1;
		}
		else
		{
			$this->cursor+=1;
			$current_pos=$this->cursor;
			return $this->result_set[$current_pos];
		}
	}

/*=====================================================================================================================
Following function moves the cursor backward in the resultset. One record at a time
Arguments :- None

Returns previous row in the resultSet;
======================================================================================================================*/
	function MovePrevious()
	{
		static $current_pos;
		if($this->cursor==0)
		{
			$this->cursor+=1;
		}
		else
		{
			$this->cursor-=1;
			$current_pos=$this->cursor;
			return $this->result_set[$current_pos];
		}
	}
	
/*=====================================================================================================================
Following function moves the cursor to the first record in the resultset.
Arguments :- None

Returns first row in the resultSet;
======================================================================================================================*/	
	function MoveFirst()
	{
		$this->cursor=0;
		return $this->result_set[0];
	}
	
/*=====================================================================================================================
Following function moves the cursor to the last record in the resultset.
Arguments :- None

Returns last row in the resultSet;
======================================================================================================================*/
	function MoveLast()
	{
		$this->cursor=count($this->result_set);
		return $this->result_set[count($this->result_set)];
	}

/*=====================================================================================================================
Following function moves the cursor to the specified record in the resultset.
Arguments :- record_pos -> Position of the row as integer.

Returns specified row in the resultSet;
======================================================================================================================*/
	function SeekRow($row_pos)
	{
		/*print($this->result_set);
		echo "<br>".count($this->result_set);
		echo ":".$row_pos;*/
		if(count($this->result_set)<$row_pos)
		{
			trigger_error("Count Of Resultset is less than specified row",E_USER_ERROR);
			$this->err="Total number of records are less than the specified row's number";
			MySQL_Close();
			die();
		}
		else
		{
			$this->cursor=$row_pos;
			return $this->result_set[$row_pos];
		}
	}
}; 
//****************************************************End Of Class******************************************************
?>
