Location: PHPKode > scripts > RC4PHP class > rc4php-class/rc4php_db_sql.php
<?PHP
/**
*
* RC4PHP :  Raul's Classes For PHP <http://rc4php.sourceforge.net/>
* Copyright (c) 2006, Raul IONESCU
*                     Bucharest, ROMANIA
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @package      RC4PHP
* @copyright 	Copyright (c) 2006, Raul IONESCU.
* @author 	Raul IONESCU <hide@address.com>
* @license      http://www.opensource.org/licenses/mit-license.php The MIT License
* @version 	0.6.3 (development)
* @category 	Abstract base SQL class
* @access 	public
*
* PHP versions 5.1 or greater
*/
//////////////////////////////////////////////////////////////////
require_once('rc4php_autoload.php');
require_once('rc4php_db_sql_interface.php');
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* abstract class RC4PHP_DB_SQL
*
* It's the base class who will be extended by other SQL classes.
* 
* GET PROPERTIES
* ---------------------------------------------------------------------------
* (Note: get properties  marked with [], can also be accessed as array keys.)
* ---------------------------------------------------------------------------
* type				= object's type: 'SQL'		        []
* version			= server version			[]
* database			= database's name			[]
* server 			= server's name				[]
* user				= user's name				[]
* password			= user's password			[]
* connection		= sql connection resource
* databases			= databases from server (array)
* tables			= database's tables (array)
* views				= current database's views (array)

* SET PROPERTIES
* ---------------------------------------------------------------------------
* (Note: set properties  marked with [], can also be accessed as array keys.)
* ---------------------------------------------------------------------------
* database			= database's name			[]
* server 			= server's name				[]
* user				= user's name				[]
* password			= user's password			[]
* 
* PUBLIC METHODS
* ---------------------------------------------------------------------------
* escapeString($string);                    -> returns escaped string of $string.
* &escapeBinaryString(&$binaryString);      -> returns escaped string for binary data.
* &unescapeSQLBinaryString(&$binaryString); -> returns binary string from SQL server.
* isConnected();                            -> returns state of connection: boolean true for connected else it returns false.
* connect();                                -> try to connects to SQL server.
* disconnect();                             -> disconnect from SQL server.
* query($sql);                              -> send a query to the SQL server; it returns an SQL Result object.
* getDatabases();                           -> get array of databases
* getTables($database='');                  -> get array of tables from $database; if $database is empty then it will use current database.
* getViews($database='');                   -> get array of views from $database; if $database is empty then it will use current database.
* DATE2MIDAS($date);                        -> convert date into MIDAS date.
* MIDAS2DATE($MIDASdate);                   -> convert MIDAS date into date.
* 
* @access public
* @abstract
*/
abstract class RC4PHP_DB_SQL extends RC4PHP implements RC4PHP_DB_SQL_Interface, ArrayAccess, Iterator
{
/*
const _ExceptionDefaultMessage_='';
const _ExceptionDefaultCode_=0;
*/
const _ServerErrorMessageHeader_='[SQL message: ';
const _ServerErrorMessageFooter_=' ]';
const _ErrorMessageHeader_='[SQL command: ';
const _ErrorMessageFooter_=' ]';

protected $RC4PHP_DB_QUOTE_PATTERN='%s';
protected $dbSQLServer='';
protected $dbSQLDBName='';
protected $dbSQLUser='';
protected $dbSQLPassword='';
protected $dbSQLConnection=false;
protected static $dbSQLIteratorKeys;
protected static $dbSQLIteratorMaxPosition;
protected $dbSQLIteratorCurrentPosition=0;
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* Constructing RC4PHP_DB_SQL object
*
* Initialize object's properties.
* It doesn't establishd connection to the SQL server. The connection
* it's establishe only when it's needed.
*
* @param string $dbSQLDBName
* @param string $dbSQLServer
* @param string $dbSQLUser
* @param string $dbSQLPassword
* @return RC4PHP_DB_SQL
*/
public function __construct($dbSQLDBName='',$dbSQLServer='localhost',$dbSQLUser='',$dbSQLPassword='')
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
parent::__construct();
$dbSQLIteratorKeys=array('type','version','database','server','user','password');

$this->dbSQLServer=$dbSQLServer;
$this->dbSQLDBName=$dbSQLDBName;
$this->dbSQLUser=$dbSQLUser;
$this->dbSQLPassword=$dbSQLPassword;
$this->dbSQLConnection=false;
if(empty(self::$dbSQLIteratorKeys)) self::$dbSQLIteratorKeys=$dbSQLIteratorKeys;
if(empty(self::$dbSQLIteratorMaxPosition)) self::$dbSQLIteratorMaxPosition=count($dbSQLIteratorKeys);
}
//////////////////////////////////////////////////////////////////
/**
* Destroing RC4PHP_DB_SQL object
*
* When object it's destroyed, the database connection will be closed.
*/
public function __destruct()
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
$this->disconnect();
}
//////////////////////////////////////////////////////////////////
/**
* Clonning RC4PHP_DB_SQL object
*
* When object it's cloned, the database connection for the new object
* will be false, meanning that on demand a new connection will be made.
* @return RC4PHP_DB_SQL
*/
public function __clone()
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
$this->dbSQLServer=$that->dbSQLServer;
$this->dbSQLDBName=$that->dbSQLDBName;
$this->dbSQLUser=$that->dbSQLUser;
$this->dbSQLPassword=$that->dbSQLPassword;
$this->dbSQLConnection=false;
$this->dbSQLIteratorCurrentPosition=$that->dbSQLIteratorCurrentPosition;
}
//////////////////////////////////////////////////////////////////
public function __sleep()
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
$this->disconnect();
return array('dbSQLServer','dbSQLDBName','dbSQLUser','dbSQLPassword','dbSQLConnection','dbSQLIteratorKeys','dbSQLIteratorMaxPosition','dbSQLIteratorCurrentPosition');
}
//////////////////////////////////////////////////////////////////
public function __wakeup()
///class RC4PHP_DB_SQL////////////////////////////////////////////
{

}
//////////////////////////////////////////////////////////////////
public function __isset($varName)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
$varName=@strtoupper($varName);
switch($varName)
	{
	 case 'CONNECTION':
	 case 'DATABASE':
	 case 'SERVER':
	 case 'USER':
	 case 'PASSWORD':
	 case 'DATABASES':
	 case 'TABLES':
	 case 'VIEWS':
	 case 'TYPE':
	 case 'VERSION': return true;
	 default:        return false;
	}
}
//////////////////////////////////////////////////////////////////
public function __unset($varName)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
$varName=@strtoupper($varName);
switch($varName)
	{
	 case 'CONNECTION': $this->disconnect(); break;
	 case 'DATABASE':   $this->database='';  break;
	 case 'SERVER':     $this->server=''; break;
	 case 'USER':       $this->user=''; break;
	 case 'PASSWORD':   $this->password='';	break;
	}
}
//////////////////////////////////////////////////////////////////
/**
* Getting RC4PHP_DB_SQL properties
*
* ---------------------------------------------------------------------------
* (Note: get properties  marked with [], can also be accessed as array keys.)
* ---------------------------------------------------------------------------
* type			= object's type: 'SQL'                  []
* version		= server version			[]
* database		= database's name			[]
* server 		= server's name				[]
* user			= user's name				[]
* password		= user's password			[]
* connection	        = sql connection resource
* databases		= databases from server (array)
* tables		= database's tables (array)
* views			= current database's views (array)
*
* @param string $varName
* @return mixed
*/
public function __get($varName)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
try
	{
	 switch(@strtoupper($varName))
		{
		 case 'CONNECTION': return $this->dbSQLConnection;
		 case 'DATABASE':   return $this->dbSQLDBName;
		 case 'SERVER':     return $this->dbSQLServer;
		 case 'USER':       return $this->dbSQLUser;
		 case 'PASSWORD':   return $this->dbSQLPassword;
		 case 'DATABASES':  return $this->getDatabases();
		 case 'TABLES':     return $this->getTables();
		 case 'VIEWS':      return $this->getViews();
		 case 'TYPE':       return $this->_getType();
		 case 'VERSION':    return $this->_getVersion();
		 case 'OS':         return parent::__get('OS');
		 case 'SQL':        return $this->SQL;
		 default:           return false;
		}
	}
catch(Exception $e){ $this->disconnect(); throw $e; }		
}
//////////////////////////////////////////////////////////////////
/**
* Setting RC4PHP_DB_SQL properties
*
* ----------------------------------------------------------------
* (Note: all properties, can also be accessed as array keys.)
* ----------------------------------------------------------------
* database	= database's name
* server	= server's name	
* user		= user's name
* password	= user's password
*
* @param string $varName
* @param string $value
*/
public function __set($varName,$value)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
$varName=@strtoupper($varName);
switch($varName)
	{
	 case 'DATABASE': $this->disconnect(); $this->dbSQLDBName=$value; break;
	 case 'SERVER':   $this->disconnect(); $this->dbSQLServer=$value; break;
	 case 'USER':     $this->disconnect(); $this->dbSQLUser=$value; break;
	 case 'PASSWORD': $this->disconnect(); $this->dbSQLPassword=$value; break;
	}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns a string of SQL server's type: 'MySQL', 'MSSQL' or 'SQLite'.
* 
* @access protected
* @return string
* @abstract
*/
abstract protected function _getType();
///class RC4PHP_DB_SQL////////////////////////////////////////////
/**
*
*
* Returns SQL server's version. 
*
* @access protected
* @return string
* @abstract
*/
abstract protected function _getVersion();
///class RC4PHP_DB_SQL////////////////////////////////////////////
/**
*
*
* It's used internally for generating results for methods getDatabases(),
* getTables() and getViews().
*
* @access protected
* @param string $sql
* @return array
*/
protected function _get($sql,$database='')
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
try { 
     $array=array();
     if(!empty($database)) { $oldDatabase=$this->database; $this->database=$database; } 
     $rs=$this->query($sql);
     while($row=$rs->fetchRow()) $array[]=$row[0];
     $rs->freeResult();
     unset($rs);
     if(!empty($database)) $this->database=$oldDatabase;	
     return $array;	
    }
catch(Exception $e){ $rs->freeResult(); unset($rs); throw $e; }
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Checks if $this->dbSQLConnection it is resource or not and the
* result it's cached internally into a static variable. Further
* calls of this method will return the cached result. If the 
* method is called with the input parameter $forceCheck set to
* TRUE then the result is recalculated and recached.
*
* @access protected
* @staticvar boolean $isResourceConnection is used to cache method's returned value.
* @param boolean $forceCheck
* @return boolean
*/
protected function _isResourceConnection($forceCheck=false)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
static $isResourceConnection=false;
if(($isResourceConnection==false) || $forceCheck) $isResourceConnection=@is_resource($this->dbSQLConnection);
return $isResourceConnection;
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
*
*
* Checks if $this->dbSQLConnection it is object or not and the
* result it's cached internally into a static variable. Further
* calls of this method will return the cached result. If the 
* method is called with the input parameter $forceCheck set to
* TRUE then the result is recalculated and recached.
*
* @access protected
* @staticvar boolean $isObjectConnection is used to cache method's returned value.
* @param boolean $forceCheck
* @return boolean
*/
protected function _isObjectConnection($forceCheck=false)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
static $isObjectConnection=false;
if(($isObjectConnection==false) || $forceCheck) $isObjectConnection=@is_object($this->dbSQLConnection);
return $isObjectConnection;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* The method returns quoted version of string $name.
*
* @access public
* @param string $name
* @return string
*/
public function quoteName($name)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{
return sprintf($this->RC4PHP_DB_QUOTE_PATTERN,$name);
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Converts passed date into MIDAS date. 
* If no date it's passed, then it will return current day's MIDAS date. 
*
* @access public
* @param string $date
* @return integer
*/
public function DATE2MIDAS($date='')
{ return round(((strtotime(((empty($date))?(date('Y-m-d')):($date)))-mktime(0,0,0,12,31,1971))/86400)); }
///class RC4PHP_DB_SQL////////////////////////////////////////////
/**
*
*
* Converts passed MIDAS date into normal date. 
*
* @access public
* @param integer $MIDASdate
* @return string
*/
public function MIDAS2DATE($MIDASdate)
{ return date('Y-m-d',(($Mdate*86400)+mktime(0,0,0,12,31,1971))); }
///class RC4PHP_DB_SQL////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
//ArrayAccess functions
//////////////////////////////////////////////////////////////////
public function offsetExists($offset)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{ return in_array(@strtolower($offset),self::$dbSQLIteratorKeys); }
//////////////////////////////////////////////////////////////////
public function offsetGet($offset)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{ return $this->$offset; }
//////////////////////////////////////////////////////////////////
public function offsetSet($offset, $value)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{ $this->$offset=$value; }
//////////////////////////////////////////////////////////////////
public function offsetUnset($offset)
///class RC4PHP_DB_SQL////////////////////////////////////////////
{ $this->$offset=false; }
//////////////////////////////////////////////////////////////////
//ITERATOR functions
//////////////////////////////////////////////////////////////////
public function rewind()
///class RC4PHP_DB_SQL////////////////////////////////////////////
{ $this->dbSQLIteratorCurrentPosition=0; }
//////////////////////////////////////////////////////////////////
public function key() 
///class RC4PHP_DB_SQL////////////////////////////////////////////
{ return self::$dbSQLIteratorKeys[$this->dbSQLIteratorCurrentPosition]; }
//////////////////////////////////////////////////////////////////
public function current() 
///class RC4PHP_DB_SQL////////////////////////////////////////////
{ $currentKey=$this->key(); return $this->$currentKey; }
//////////////////////////////////////////////////////////////////
public function next()
///class RC4PHP_DB_SQL////////////////////////////////////////////
{ ++$this->dbSQLIteratorCurrentPosition; }
//////////////////////////////////////////////////////////////////
public function valid() 
///class RC4PHP_DB_SQL////////////////////////////////////////////
{ return ($this->dbSQLIteratorCurrentPosition < self::$dbSQLIteratorMaxPosition); }
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* abstract class RC4PHP_DB_SQL_Result
*
* It's the base result class who will be extended by other SQL result classes.
* 
* ------------------------------------------------------------------------------
* (Note: the result's rows and columns can also be accessed as array elements
* 		Example: $result[0][0] 		-> first columnn from 1st row
* 			 $result[1]['Foo']	-> column 'Foo' from 2nd row)
* ------------------------------------------------------------------------------
* 
* GET PROPERTIES
* -------------------------------------------------------------
* type			= object's type: 'SQL'
* maxPageSize		= limit maximum page size
* pageSize		= number of rows for page
* pages			= number of pages
* page			= current page number (starting from 1)
* row			= current row number (from current page, if pageSize is set) (starting from 0)
* rows			= number of rows from current page or total number of rows if pagination is not used
* totalRows             = total number of rows, no matter pagination is set or not
* fields		= number of fields
* affectedRows		= number of affected rows
* lastInsertedID	= last inserted ID
* executionTime         = execution time for the SQL query in msec
* 
* SET PROPERTIES
* -------------------------------------------------------------
* maxPageSize		= limit maximum page size
* pageSize		= number of rows for page
* page			= current page number (starting from 1)
* row			= current row number (from current page, if pageSize is set) (starting from 0)
* 
* PUBLIC METHODS
* -------------------------------------------------------------
* execute();				-> execute the sql querry.
* fetchField($fieldOffset=NULL);
* fetchRow();				-> fetch row from current row position as an array. each result column is stored in an array offset, starting at offset 0.
* fetchRowAssociative();		-> fetch row from current row position as an associative array of column's names.
* fetchRowArray();			-> fetch row from current row position as an array. the array offsets can be colum's name or column's number (starting from 0).
* fetchObject();			-> fetch row from current row position as an object with properties that correspond to the fetched row.
* fetchAllRows();			-> fetch all rows from current row position as a bidimensional array. first dimension is row number (starting from 0) and the 2nd dimension is column (starting from 0).
* fetchAllRowsAssociative();	        -> fetch all rows from current row position as a bidimensional array. first dimension is row number (starting from 0) and the 2nd dimension is column's name.
* fetchAllRowsArray();			-> fetch all rows from current row position as a bidimensional array. first dimension is row number (starting from 0) and the 2nd dimension can be colum's name or column's number (starting from 0).
* fetchAllObjectsArray();		-> fetch all rows from current row position as an  array of objects. the array offsets are row numbers (starting from 0).
* nextResult();
* freeResult();				-> free all memory associated with the result.
* 
* @access public
* @abstract
*/
abstract class RC4PHP_DB_SQL_Result implements RC4PHP_DB_SQL_Result_Interface, ArrayAccess, Iterator
{
const _ServerErrorMessageHeader_='[SQL message: ';
const _ServerErrorMessageFooter_=' ]';
const _ErrorMessageHeader_='[SQL command: ';
const _ErrorMessageFooter_=' ]';

protected $dbSQLObject;
protected $dbSQLCommand;
protected $dbSQLResult=false;
protected $dbSQLResultRows=0;
protected $dbSQLResultCurrentRow=0;
protected $dbSQLResultMaxPageSize=0;
protected $dbSQLResultPageSize=0;
protected $dbSQLResultCurrentPage=1;
protected $dbSQLResultPreviousPage=1;
protected $dbSQLResultTotalPages=0;
protected $dbSQLResultTotalRows=0;
protected $dbSQLResultQueryError=false;
protected $dbSQLQueryTime=0;
//////////////////////////////////////////////////////////////////
/**
* Constructing RC4PHP_DB_SQL_Result object
*
* Initialize object's properties.
* It doesn't query SQL server until execute() method or a property 
* of the result object (such as fetchRow() method or rows property,
* for example) it's called.
*
* @param RC4PHP_DB_SQL $RC4PHP_DB_SQLObject
* @param string $dbSQLCommand
* @return RC4PHP_DB_SQL_Result
*/
public function __construct(RC4PHP_DB_SQL &$RC4PHP_DB_SQLObject,&$dbSQLCommand)
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
if(!is_string($dbSQLCommand)) throw new RC4PHP_DB_SQL_Exception('SQL command must be a string. ',-1);
$this->dbSQLObject=$RC4PHP_DB_SQLObject;	
$this->dbSQLCommand=trim($dbSQLCommand);
}
//////////////////////////////////////////////////////////////////
/**
* Destroing RC4PHP_DB_SQL_Result object
*
* When object it's destroyed, the associated memory with the result
* it's freed.
*/
public function __destruct()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
$this->freeResult();
}
//////////////////////////////////////////////////////////////////
/**
* Clonning RC4PHP_DB_SQL_Result object
*
* When object it's cloned, the internal $dbSQLObject it's clonned
* and the result it's cleared. When needed, a new connection to
* the SQL server will be established and a new result will be 
* retrived.
*
* @return RC4PHP_DB_SQL
*/
public function __clone()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
$this->dbSQLObject=clone($that->dbSQLObject);
$this->dbSQLCommand=$that->dbSQLCommand;
$this->dbSQLResult=false;
$this->dbSQLResultRows=$that->dbSQLResultRows;
$this->dbSQLResultCurrentRow=$that->dbSQLResultCurrentRow;
$this->dbSQLResultMaxPageSize=$that->dbSQLResultMaxPageSize;
$this->dbSQLResultPageSize=$that->dbSQLResultPageSize;
$this->dbSQLResultCurrentPage=$that->dbSQLResultCurrentPage;
$this->dbSQLResultPreviousPage=$that->dbSQLResultPreviousPage;
$this->dbSQLResultTotalPages=$that->dbSQLResultTotalPages;
$this->dbSQLResultTotalRows=$that->dbSQLResultTotalRows;
$this->dbSQLQueryTime=0;
}
//////////////////////////////////////////////////////////////////
public function __sleep()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
$this->freeResult();
if($this->dbSQLObject) $this->dbSQLObject->disconnect();
return array('dbSQLObject','dbSQLCommand','dbSQLResult','dbSQLResultRows','dbSQLResultCurrentRow','dbSQLResultMaxPageSize','dbSQLResultPageSize','dbSQLResultCurrentPage','dbSQLResultPreviousPage','dbSQLResultTotalPages','dbSQLResultTotalRows','dbSQLQueryTime');
}
//////////////////////////////////////////////////////////////////
public function __wakeup(){}
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
/**
* Getting RC4PHP_DB_SQL_Result properties
*
* type			= object's type: 'SQL.Result'
* pageSize		= number of rows for page
* pages			= number of pages
* page			= current page number (starting from 1)
* row			= current row number (from current page, if pageSize is set) (starting from 0)
* rows			= number of rows from current page or total number of rows if pagination is not used
* totalRows             = total number of rows, no matter pagination is set or not
* fields		= number of fields
* affectedRows		= number of affected rows
* lastInsertedID	= last inserted ID
* executionTime         = execution time for the SQL query in msec
*
* @param string $varName
* @return mixed
*/
public function __get($varName)
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
try
	{
	 switch(@strtoupper($varName))
		{
		 case 'PAGES':          return $this->_getPages();			
		 case 'PAGE':           return $this->dbSQLResultCurrentPage;
		 case 'MAXPAGESIZE':	return $this->dbSQLResultMaxPageSize;
		 case 'PAGESIZE':       return $this->dbSQLResultPageSize;
		 case 'ROWS':           return $this->_getRows();
		 case 'TOTALROWS':      return $this->_getTotalRows();
		 case 'ROW':            return (($currentRow=$this->dbSQLResultCurrentRow-1)<0)?(0):(($currentRow>=$this->rows)?($this->rows-1):($currentRow));
		 case 'AFFECTEDROWS':   return $this->_getAffectedRows();
		 case 'LASTINSERTEDID': return $this->_getLastInsertedID();
		 case 'FIELDS':         return $this->_getFields();
		 case 'TYPE':           return $this->_getType();
		 case 'EXECUTIONTIME':  return $this->dbSQLQueryTime;
		 default:               return false;
		}
	}
catch(Exception $e){ $this->freeResult(); if($this->dbSQLObject instanceof RC4PHP_DB_SQL) { $this->dbSQLObject->disconnect(); } throw $e; }		
}
//////////////////////////////////////////////////////////////////
/**
* Setting RC4PHP_DB_SQL_Result properties
*
* pageSize	= number of rows for page
* page		= current page number (starting from 1)
* row		= current row number (from current page, if pageSize is set) (starting from 0)
*
* @param string $varName
* @param string $value
*/
public function __set($varName,$value)
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
try
	{
	 $varName=@strtoupper($varName);
	 $value=@intval($value);
	 switch($varName)
		{
			case 'PAGE':
				$this->_checkPageSize();
				$value=($value<1)?(1):(($value>$this->pages)?($this->pages):($value));
				$this->dbSQLResultPreviousPage=$this->dbSQLResultCurrentPage;
				$this->dbSQLResultCurrentPage=$value;
				$this->dbSQLResultRows=0;
				$this->dbSQLResultCurrentRow=0;
				break;
				
			case 'PAGESIZE':
				if(($this->dbSQLResult!==false) && ($this->dbSQLResult!==true)) throw new RC4PHP_DB_SQL_Exception('Result\'s page size must be set before retriving results.',-2);
				if($value<1) { $value=abs($value); }
				if((!empty($this->dbSQLResultMaxPageSize)) && ($value>($this->dbSQLResultMaxPageSize))) { $value=$this->dbSQLResultMaxPageSize; }
				$this->dbSQLResultPageSize=$value;
				$this->dbSQLResultCurrentPage=1;
				break;
				
			case 'MAXPAGESIZE':
				$this->dbSQLResultMaxPageSize=abs($value);
				break;
				
			case 'ROW':
				break;		

		}
	}		
catch(Exception $e){ $this->freeResult(); if($this->dbSQLObject instanceof RC4PHP_DB_SQL) { $this->dbSQLObject->disconnect(); } throw $e; }
}
//////////////////////////////////////////////////////////////////
public function __toString()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
//
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns a string of SQL server's type: 'MySQL.Result', 'MSSQL.Result' or 'SQLite.Result'.
* 
* @access protected
* @return string
* @abstract
*/
abstract protected function _getType();
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
/**
*
*
* It's used to check if pageSize property was set.
* 
* @access protected
* @return void
*/
protected function _checkPageSize()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
try{ if((is_integer($this->dbSQLResultPageSize)==false) || ($this->dbSQLResultPageSize<=0)) { throw new RC4PHP_DB_SQL_Exception('Result page size not set.',-3); }}
catch(Exception $e){ $this->freeResult(); if($this->dbSQLObject instanceof RC4PHP_DB_SQL) { $this->dbSQLObject->disconnect(); } throw $e; }		
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Checks if $this->dbSQLResult it is resource or not and the
* result it's cached internally into a static variable. Further
* calls of this method will return the cached result. If the 
* method is called with the input parameter $forceCheck set to
* TRUE then the result is recalculated and recached.
*
* @access protected
* @staticvar boolean $isResourceResult is used to cache method's returned value.
* @param boolean $forceCheck
* @return boolean
*/
protected function _isResourceResult($forceCheck=false)
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
static $isResourceResult=false;
if(($isResourceResult==false) || $forceCheck) $isResourceResult=@is_resource($this->dbSQLResult);
return $isResourceResult;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Checks if $this->dbSQLResult it is object or not and the
* result it's cached internally into a static variable. Further
* calls of this method will return the cached result. If the 
* method is called with the input parameter $forceCheck set to
* TRUE then the result is recalculated and recached.
*
* @access protected
* @staticvar boolean $isObjectResult is used to cache method's returned value.
* @param boolean $forceCheck
* @return boolean
*/
protected function _isObjectResult($forceCheck=false)
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
static $isObjectResult=false;
if(($isObjectResult==false) || $forceCheck) $isObjectResult=@is_object($this->dbSQLResult);
return $isObjectResult;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the connection resource to the SQL server. 
*
* @access protected
* @return mixed
*/
protected function _getConnection()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
return $this->dbSQLObject->connection;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* It checks if the connection was already established. If not,
* try to connect to the SQL server.
*
* @access protected
* @return mixed
*/
protected function _checkConnection()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
try {
     if(!($this->dbSQLObject instanceof RC4PHP_DB_SQL)) throw new RC4PHP_DB_SQL_Exception('Result error: invalid SQL server connection.',-4);
     if($this->dbSQLObject->isConnected()==false) $this->dbSQLObject->connect();
     if($this->dbSQLObject->isConnected()==false) throw new RC4PHP_DB_SQL_Exception('Result error: invalid SQL server connection.',-5);
    }
catch(Exception $e){ $this->freeResult(); if($this->dbSQLObject instanceof RC4PHP_DB_SQL) { $this->dbSQLObject->disconnect(); } throw $e; }	
}	
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the number of rows from result.
*
* @access protected
* @return integer
* @abstract
*/
abstract protected function _getRows();
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
/**
*
*
* Returns the number of affected rows by the SQL command.
*
* @access protected
* @return integer
* @abstract
*/
abstract protected function _getAffectedRows();
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
/**
*
*
* Returns the last inserted ID.
*
* @access protected
* @return integer
* @abstract
*/
abstract protected function _getLastInsertedID();
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
/**
*
*
* Returns the number of fields(columns) from result.
*
* @access protected
* @return integer
* @abstract
*/
abstract protected function _getFields();
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
/**
*
*
* Returns the number of total rows not just the number of rows from
* current page for result.
*
* @access protected
* @return integer
* @abstract
*/
abstract protected function _getTotalRows();
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
/**
*
*
* Returns the number of total pages for the result.
*
* @access protected
* @return integer
*/
protected function _getPages()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
if($this->dbSQLResultTotalPages==0)
	{
	 $this->_checkPageSize();
         $this->_getTotalRows();
         $this->dbSQLResultTotalPages=($this->dbSQLResultTotalRows)?(($this->dbSQLResultPageSize>=$this->dbSQLResultTotalRows)?(1):(ceil($this->dbSQLResultTotalRows/($this->dbSQLResultPageSize)))):(0);
	} 
return $this->dbSQLResultTotalPages;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns all rows as an array. The method returns FALSE 
* when no more rows are available.
*
* @access public
* @return array | boolean
*/
public function fetchAllRows()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
$allRows=array();
while($row=$this->fetchRow()) $allRows[]=$row;
return $allRows;	
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns all rows as an associative array. The method 
* returns FALSE when no more rows are available.
*
* @access public
* @return array | boolean
*/
public function fetchAllRowsAssociative()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
$allRows=array();
while($row=$this->fetchRowAssociative()) $allRows[]=$row;
return $allRows;	
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns all row as an associative and numerical array.
* The method returns FALSE when no more rows are available.
*
* @access public
* @return array | boolean
*/
public function fetchAllRowsArray()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
$allRows=array();
while($row=$this->fetchRowArray()) $allRows[]=$row;
return $allRows;	
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns all rows as an array of objects.
* The method returns FALSE when no more rows are available.
*
* @access public
* @return object | boolean
*/
public function fetchAllObjectsArray()
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
$allObjects=array();
while($object=$this->fetchObject()) $allObjects[]=$object;
return $allObjects;	
}
//////////////////////////////////////////////////////////////////
/**
* Print page select
*
* @access public
*/
public function printPageSelect($selectName='page',$otherSelectParameters='',$ReturnAsStringInsteadOfPrint=false)
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
{
for($selectCode='<select name="'.$selectName.'" '.$otherSelectParameters.'>',$page=$this->page,$pages=$this->pages,$i=1;$i<=$pages;++$i) 
        $selectCode.='<option value="'.$i.'"'.(($i==$page)?(' selected'):('')).'>'.$i.'</option>';
$selectCode.='</select>';
if($ReturnAsStringInsteadOfPrint) return $selectCode;
print $selectCode;
}
//////////////////////////////////////////////////////////////////
//ArrayAccess functions
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
/*
public function offsetExists($offset);
public function offsetGet($offset);
public function offsetSet($offset, $value);
public function offsetUnset($offset);
*/
//////////////////////////////////////////////////////////////////
//Iterator functions
///class RC4PHP_DB_SQL_Result/////////////////////////////////////
/*
public function rewind();
public function key();
public function current();
public function next();
public function valid();
*/
//////////////////////////////////////////////////////////////////
//ArrayAccess functions
//////////////////////////////////////////////////////////////////
public function offsetExists($offset)
///class RC4PHP_DB_SQL_Result///Array Access function/////////////
{ return is_int($offset) && ($offset>=0) && ($offset<$this->rows); }
//////////////////////////////////////////////////////////////////
public function offsetGet($offset)
///class RC4PHP_DB_SQL_Result///Array Access function/////////////
{
try {
     if ($this->offsetExists($offset)==false) $offset=($offset<0)?(0):($offset>($this->rows-1)?($this->rows-1):($offset));
     $this->row=$offset;
     return $this->fetchRowArray();
    }
catch(Exception $e){ $this->freeResult(); if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect(); throw $e; }		
}
//////////////////////////////////////////////////////////////////
public function offsetSet($offset, $value)
///class RC4PHP_DB_SQL_Result///Array Access function/////////////
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw new RC4PHP_DB_SQL_Exception('Modifying result values is forbidden.',-7);
}
//////////////////////////////////////////////////////////////////
public function offsetUnset($offset)
///class RC4PHP_DB_SQL_Result///Array Access function/////////////
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw new RC4PHP_DB_SQL_Exception('Unsetting result values is forbidden.',-8);
}
//////////////////////////////////////////////////////////////////
//ITERATOR functions
//////////////////////////////////////////////////////////////////
public function rewind()
///class RC4PHP_DB_SQL_Result///ITERATOR function/////////////////
{ $this->seek(0); }
//////////////////////////////////////////////////////////////////
public function key() 
///class RC4PHP_DB_SQL_Result///ITERATOR function/////////////////
{ return $this->dbSQLResultCurrentRow; }
//////////////////////////////////////////////////////////////////
public function current() 
///class RC4PHP_DB_SQL_Result///ITERATOR function/////////////////
{ return $this->fetchRow(); }
//////////////////////////////////////////////////////////////////
public function next(){}
///class RC4PHP_DB_SQL_Result///ITERATOR function/////////////////
public function valid() 
///class RC4PHP_DB_SQL_Result///ITERATOR function/////////////////
{ return $this->dbSQLResultCurrentRow < $this->dbSQLResultRows; }
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* abstract class RC4PHP_DB_SQL_DATA_DICTIONARY
*
* It's a SQL dictionary class.
* 
* GET PROPERTIES
* ---------------------------------------------------------------------------
* DATA TYPES
* ==========
* boolean
* binary
* char	
* unicodeChar
* varChar
* unicodeVarChar
* float			
* integer
* numeric
* date
* 
* PUBLIC METHODS
* ---------------------------------------------------------------------------
* DATA TYPES
* ==========
* char($size=self::DB_DEFAULT_CHAR_SIZE)
* unicodeChar($size=self::DB_DEFAULT_CHAR_SIZE);
* varchar($size=self::DB_DEFAULT_VARCHAR_SIZE);
* unicodeVarChar($size=self::DB_DEFAULT_VARCHAR_SIZE);
* float($size=self::DB_DEFAULT_FLOAT_SIZE);
* integer($size=self::DB_DEFAULT_INTEGER_SIZE);
* numeric($fieldDefinition=array(self::DB_DEFAULT_NUMERIC_PRECISION,self::DB_DEFAULT_NUMERIC_SCALE));
*
* @access public
*/
abstract class RC4PHP_DB_SQL_DATA_DICTIONARY
{
const CRLF="\r\n";

const DB_DEFAULT_CHAR_SIZE=255;
const DB_DEFAULT_VARCHAR_SIZE=255;
const DB_DEFAULT_UNICODE_CHAR_SIZE=511;
const DB_DEFAULT_UNICODE_VARCHAR_SIZE=511;

const DB_DEFAULT_INTEGER_SIZE=4;
const DB_DEFAULT_FLOAT_SIZE=53;
const DB_DEFAULT_NUMERIC_PRECISION=18;
const DB_DEFAULT_NUMERIC_SCALE=0;
//////////////////////////////////////////////////////////////////
protected $dbSQLcommand='';
//////////////////////////////////////////////////////////////////
public function __construct($dbSQLcommand='')
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
{
if(!is_string($dbSQLcommand)) throw new RC4PHP_DB_SQL_Exception('SQL command must be a string. ',-1);
$this->dbSQLcommand=$dbSQLcommand;
}
//////////////////////////////////////////////////////////////////
function __call($methodName,$params)
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
{
$methodName=@strtoupper($methodName);
switch($methodName)
	{
		case 'CHAR':           return $this->_char($params);
		case 'VARCHAR':        return $this->varchar($params);
		case 'UNICODECHAR':    return $this->_unicodeChar($params);				
		case 'UNICODEVARCHAR': return $this->_unicodeVarChar($params);				
		case 'INTEGER':        return $this->_integer($params);
		case 'FLOAT':          return $this->_float($params);
		case 'NUMERIC':        return $this->_numeric($params);
  		default:               return '';
	}
}
//////////////////////////////////////////////////////////////////
function __get($varName)
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
{
$varName=@strtoupper($varName);
switch($varName)
	{
		case 'BOOLEAN':        return $this->_boolean();
		case 'CHAR':           return $this->_char();
		case 'VARCHAR':	       return $this->varChar();
		case 'UNICODECHAR':    return $this->_unicodeChar();				
		case 'UNICODEVARCHAR': return $this->_unicodeVarChar();				
		case 'BINARY':         return $this->_binary();
		case 'FLOAT':          return $this->_float();		
		case 'INTEGER':        return $this->_integer();
		case 'NUMERIC':        return $this->_numeric();		
		case 'DATETIME':       return $this->_dateTime();
		case 'SQL':            return $this->dbSQLcommand;		
	  	default:               return '';
	}
}
//////////////////////////////////////////////////////////////////
public function __set($varName,$value)
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
{
$varName=@strtoupper($varName);
switch($varName)
	{
	 case 'SQL': if(!is_string($value)) { throw new RC4PHP_DB_SQL_Exception('SQL command must be a string. ',-1); } else { $this->dbSQLcommand=$value; } break;
	}
}
//////////////////////////////////////////////////////////////////
abstract protected function _boolean();
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
abstract protected function _char($size=self::DB_DEFAULT_CHAR_SIZE);
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
abstract protected function _unicodeChar($size=self::DB_DEFAULT_UNICODE_CHAR_SIZE);
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
abstract protected function _varChar($size=self::DB_DEFAULT_VARCHAR_SIZE); 
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
abstract protected function _unicodeVarChar($size=self::DB_DEFAULT_UNICODE_VARCHAR_SIZE);
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
abstract protected function _binary();
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
abstract protected function _float($size=self::DB_DEFAULT_FLOAT_SIZE);
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
abstract protected function _integer($size=self::DB_DEFAULT_INTEGER_SIZE);
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
abstract protected function _numeric($fieldDefinition=array(self::DB_DEFAULT_NUMERIC_PRECISION,self::DB_DEFAULT_NUMERIC_SCALE),$scale=self::DB_DEFAULT_NUMERIC_SCALE);
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
abstract protected function _dateTime();
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
public function addSQLcommand($dbSQLcommand='')
///class RC4PHP_DB_SQL_DATA_DICTIONARY////////////////////////////
{
if(!is_string($dbSQLcommand)) throw new RC4PHP_DB_SQL_Exception('SQL command must be a string. ',-1);
$this->dbSQLcommand.=$dbSQLcommand.self::CRLF;
}
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* class RC4PHP_DB_SQL_Exception
*
* It's the base exception class who will be extended by other SQL exception classes.
* 
* PUBLIC METHODS
* -------------------------------------------------------------
* getMessage();			-> returns message of exception 
* getCode();			-> returns code of exception
* getFile();			-> returns source filename
* getLine();			-> returns source line
* getTrace();			-> returns an array of the backtrace()
* getTraceAsString();		-> returns formated string of trace
* getBacktrace();		-> returns an array of the backtrace
* 
* @access public
* @abstract
*/
class RC4PHP_DB_SQL_Exception extends Exception
{
const _ExceptionDefaultMessage_='';
const _ExceptionDefaultCode_=-1;
private $backtrace;
//////////////////////////////////////////////////////////////////
/**
* Constructing RC4PHP_DB_SQL_Exception object
*
* Initialize object's properties.
*
* @param string $message
* @param integer $code
* @return RC4PHP_DB_SQL_Exception
*/
public function __construct($message=self::_ExceptionDefaultMessage_,$code=self::_ExceptionDefaultCode_)
///class RC4PHP_DB_SQL_Exception///////////////////////////////////
{
parent::__construct($message, $code);
}
//////////////////////////////////////////////////////////////////
public function getBacktrace()
///class ErrorException///////////////////////////////////////////
{
return $this->backtrace;
}
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
?>
Return current item: RC4PHP class