<?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 MySQL implementation
* @access public
*
* PHP versions 5.1 or greater
*/
//////////////////////////////////////////////////////////////////
require_once('rc4php_autoload.php');
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* class RC4PHP_DB_MySQL
*
* It's the MySQL SQL class.
*
* GET PROPERTIES
* ---------------------------------------------------------------------------
* (Note: get properties marked with [], can also be accessed as array keys.)
* ---------------------------------------------------------------------------
* type = object's type: 'MySQL' []
* 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 passwor []
*
* 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
*/
class RC4PHP_DB_MySQL extends RC4PHP_DB_SQL
{
protected $RC4PHP_DB_QUOTE_PATTERN='%s';
//////////////////////////////////////////////////////////////////
/**
* Constructing RC4PHP_DB_MySQL object
*
* Initialize object's properties.
* It doesn't establish connection to the SQL server. The connection
* it's established only when it's needed.
*
* @param string $dbSQLDBName
* @param string $dbSQLServer
* @param string $dbSQLUser
* @param string $dbSQLPassword
* @return RC4PHP_DB_MySQL
*/
public function __construct($dbSQLDBName='',$dbSQLServer='localhost:3306',$dbSQLUser='',$dbSQLPassword='')
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
self::_checkPHPExtension('mysqli');
parent::__construct($this->quoteName($dbSQLDBName),$dbSQLServer,$dbSQLUser,$dbSQLPassword);
}
//////////////////////////////////////////////////////////////////
/**
* Destroing RC4PHP_DB_MySQL object
*
* When object it's destroyed, the database connection will be closed.
*/
public function __destruct()
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
parent::__destruct();
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns a string of SQL server's type: 'MySQL'.
*
* @access protected
* @return string
*/
protected function _getType()
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
return 'MySQL';
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns SQL server's version.
*
* @access protected
* @return string | boolean
*/
protected function _getVersion()
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
$this->connect();
return $this->dbSQLConnection->server_info;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* The method returns escaped version of string $string.
*
* @access public
* @param string $string
* @return string
*/
public function escapeString($string)
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
$this->connect();
return $this->dbSQLConnection->escape_string($string);
}
//////////////////////////////////////////////////////////////////
/**
*
*
* The method returns escaped version of binary string $binaryString.
*
* @access public
* @param string $binartString
* @return string
*/
public function &escapeBinaryString(&$binaryString)
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
$this->connect();
$escapedBinaryString=$this->dbSQLConnection->escape_string($binaryString);
return $escapedBinaryString;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* The method returns unescaped version of binary string $binaryString
* returned by the SQL server.
*
* @access public
* @param string $binaryString
* @return string
*/
public function &unescapeSQLBinaryString(&$binaryString)
///class RC4PHP_DB_MySQL//////////////////////////////////////////
{
return $binaryString;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* The method returned boolean TRUE if connection to SQL server is
* established, otherwise it returns FALSE.
*
* @access public
* @return bool
*/
public function isConnected()
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
static $isValidConnection=false;
if($isValidConnection==false)
{
if($this->_isObjectConnection()) $this->dbSQLConnection->ping();
$isValidConnection=($this->_isObjectConnection() && @$this->dbSQLConnection->ping());
}
return ($isValidConnection && @$this->dbSQLConnection->ping());
}
//////////////////////////////////////////////////////////////////
/**
*
*
* If the connection wasn't made yet, then establish connection to SQL server.
*
* @access public
* @return void
*/
public function connect()
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
if($this->isConnected()==false)
{
if(($this->dbSQLConnection=new mysqli($this->dbSQLServer,$this->dbSQLUser,$this->dbSQLPassword,$this->dbSQLDBName))===false)
throw new RC4PHP_DB_MySQL_Exception($this->dbSQLConnection,@mysqli_connect_error(),@mysqli_connect_errno());
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* If the connection was made, then disconnects object from SQL server.
*
* @access public
* @return bool
*/
public function disconnect()
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
if($this->isConnected())
{
$returnedValue=($this->_isObjectConnection() && $this->dbSQLConnection->close());
$this->dbSQLConnection=false;
return $returnedValue;
}
return false;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Sends a query to be executed by the SQL server and returns an result
* object. If the SQL instruction it's not generating a result that would
* be used , then it's mandatory to execute recorset's method execute().
*
* @access public
* @param string $sql
* @return RC4PHP_DB_MySQL_Result
*/
public function query($sql)
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
try { return new RC4PHP_DB_MySQL_Result($this,$sql); }
catch(Exception $e)
{
$this->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* @access public
* Returns an array with databases from SQL server.
* @return array
*/
public function getDatabases()
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
return $this->_get("SHOW DATABASES");
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns an array with tables from specified database.
* If database it's not set, then it's used current database.
*
* @access public
* @param string $database
* @return array
*/
public function getTables($database='')
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
if(empty($database)) $database=$this->dbSQLDBName;
try { return $this->_get("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE ((TABLE_SCHEMA='$database') AND (TABLE_TYPE='BASE TABLE'))"); }
catch(Exception $e)
{
switch($e->getCode())
{
case 1146: //DATABASE NOT FOUNDED
case 1109: //TABLE NOT FOUNDED
case 1054: //COLUMN NOT FOUNDED
return $this->_get("SHOW TABLES FROM `$database`");
default:
throw $e;
}
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns an array with views from specified database.
* If database it's not set, then it's used current database.
*
* @access public
* @param string $database
* @return array | boolean
*/
public function getViews($database='')
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
if(empty($database)) $database=$this->dbSQLDBName;
try { return $this->_get("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA='$database'"); }
catch(Exception $e)
{
switch($e->getCode())
{
case 1146://DATABASE NOT FOUNDED
case 1109://TABLE NOT FOUNDED
case 1054://COLUMN NOT FOUNDED
return array();
default:
throw $e;
}
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Creates the SQL function DATE2MIDAS(ISODATE date).
* If database it's not set, then it's used current database.
*
* @access public
* @param string $database
* @return boolean
*/
public function createSQLFunctionDATE2MIDAS($database='')
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
if(empty($database)) $database=$this->dbSQLDBName;
$this->connect();
return $this->query('
CREATE FUNCTION `'.$database.'`.`DATE2MIDAS`(ISODATE date) RETURNS int
DETERMINISTIC
BEGIN
DECLARE MIDASDATE int;
SET MIDASDATE=TO_DAYS(ISODATE) - TO_DAYS(\'1971-12-31\');
RETURN MIDASDATE;
END',$this->dbSQLConnection);
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Creates the SQL function MIDAS2DATE(MIDASDATE int).
* If database it's not set, then it's used current database.
*
* @access public
* @param string $database
* @return boolean
*/
public function createSQLFunctionMIDAS2DATE($database='')
/////class RC4PHP_DB_MySQL////////////////////////////////////////
{
if(empty($database)) $database=$this->dbSQLDBName;
$this->connect();
return $this->query('
CREATE FUNCTION `'.$database.'`.`MIDAS2DATE`(MIDASDATE int) RETURNS date
DETERMINISTIC
BEGIN
DECLARE ISODATE date;
SET ISODATE=FROM_DAYS(MIDASDATE + TO_DAYS(\'1971-12-31\'));
RETURN ISODATE;
END',$this->dbSQLConnection);
}
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* class RC4PHP_DB_MySQL_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: 'MySQL'
* 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
*/
class RC4PHP_DB_MySQL_Result extends RC4PHP_DB_SQL_Result
{
protected $dbSQLResultCurrentPageOffset=0;
protected $dbSQLCommandLIMIT='';
//////////////////////////////////////////////////////////////////
/**
* Constructing RC4PHP_DB_MySQL_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_MySQL $RC4PHP_DB_MySQLObject
* @param string $dbSQLCommand
* @return RC4PHP_DB_MySQL_Result
*/
public function __construct(RC4PHP_DB_MySQL &$RC4PHP_DB_MySQLObject,&$dbSQLCommand)
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
if(substr_count($dbSQLCommand,';')==1) $dbSQLCommand=str_replace(';','',$dbSQLCommand);
parent::__construct($RC4PHP_DB_MySQLObject,$dbSQLCommand);
}
//////////////////////////////////////////////////////////////////
/**
* Destroing RC4PHP_DB_MySQL_Result object
*
* When object it's destroyed, the associated memory with the result
* it's freed.
*
* @return void
*/
public function __destruct()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
parent::__destruct();
}
//////////////////////////////////////////////////////////////////
/**
* Clonning RC4PHP_DB_MySQL_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_MySQL_Result
*/
public function __clone()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
parent::__clone();
$this->dbSQLResultCurrentPageOffset=$that->dbSQLResultCurrentPageOffset;
$this->dbSQLCommandLIMIT=$that->dbSQLCommandLIMIT;
}
//////////////////////////////////////////////////////////////////
public function __sleep()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
$sleepArray=parent::__sleep();
$sleepArray[]='dbSQLResultCurrentPageOffset';
$sleepArray[]='dbSQLCommandLIMIT';
return $sleepArray;
}
//////////////////////////////////////////////////////////////////
/**
* Getting RC4PHP_DB_SQL_Result properties
*
* type = object's type: 'MySQLResult'
* 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_MySQL_Result/////////////////////////////////
{
$varname=@strtoupper($varname);
switch($varname)
{
case 'TYPE': return 'MySQL.Result';
default: return parent::__get($varname);
}
}
//////////////////////////////////////////////////////////////////
/**
* Setting RC4PHP_DB_MySQL_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_MySQL_Result/////////////////////////////////
{
try
{
$varname=@strtoupper($varname);
$value=@intval($value);
parent::__set($varname,$value);
switch($varname)
{
case 'PAGE':
$this->dbSQLResultCurrentPageOffset=($this->dbSQLResultCurrentPage<2)?(0):(($this->dbSQLResultCurrentPage*$this->dbSQLResultPageSize)-$this->dbSQLResultPageSize);
$this->dbSQLCommandLIMIT=($this->dbSQLResultPageSize==0)?(''):(($this->dbSQLResultCurrentPage<2)?('LIMIT '.$this->dbSQLResultPageSize):('LIMIT '.$this->dbSQLResultCurrentPageOffset.','.$this->dbSQLResultPageSize));
return true;
case 'ROW':
$this->_checkConnectionAndResult();
$value=($value<0)?(0):($value>($this->rows-1)?($this->rows-1):($value));
$this->dbSQLResultCurrentRow=$value;
return $this->dbSQLResult->data_seek($this->dbSQLResultCurrentRow);
}
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns a string of SQL server's type: 'MySQL.Result'.
*
* @access protected
* @return string
*/
protected function _getType()
///class RC4PHP_DB_MySQL//////////////////////////////////////////
{
return 'MySQL.Result';
}
//////////////////////////////////////////////////////////////////
protected function _isResultGeneratingCommand(&$sql)
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
return !(((stripos($sql,'SELECT ')===false) && (stripos($sql,'CALL ')===false) && (stripos($sql,'SHOW ')===false) && (stripos($sql,'DESCRIBE ')===false)) || stripos($sql,'INTO '));
}
//////////////////////////////////////////////////////////////////
/**
*
*
* It checks if the connection was already established and the SQL command
* was sended to the server. If not, try to connect to the SQL server and
* sends command to server.
*
* @access protected
* @return void
*/
protected function _checkConnectionAndResult()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
$this->_checkConnection();
$cn=&$this->_getConnection();
if(($this->dbSQLResult===false) || ($this->dbSQLResultPreviousPage!=$this->dbSQLResultCurrentPage))
{
$startTime=microtime(true);
$this->dbSQLResultPreviousPage=$this->dbSQLResultCurrentPage;
$this->freeResult();
if(strlen($this->dbSQLCommandLIMIT))
{
if(substr_count($this->dbSQLCommand,';')>1) throw new RC4PHP_DB_SQL_Exception('Pagination feature is supported only for single queryes. '.self::_ErrorMessageHeader_.trim($this->dbSQLCommand).self::_ErrorMessageFooter_);
/* current SQL command should be a SELECT command */
if(@$cn->multi_query('SELECT __rc4php__.* FROM ('.$this->dbSQLCommand.') AS __rc4php__ '.$this->dbSQLCommandLIMIT)===false)
{ if(@$cn->multi_query($this->dbSQLCommand.' '.$this->dbSQLCommandLIMIT)===false) { throw new RC4PHP_DB_MySQL_Exception($cn,self::_ErrorMessageHeader_.trim('SELECT __rc4php__.* FROM ('.$this->dbSQLCommand.') AS __rc4php__ '.$this->dbSQLCommandLIMIT).self::_ErrorMessageFooter_); }}
}
else
{
/* current SQL command shouldn't be a SELECT command or a SELECT command without pagination */
if(@$cn->multi_query($this->dbSQLCommand)===false) { throw new RC4PHP_DB_MySQL_Exception($cn,self::_ErrorMessageHeader_.trim($this->dbSQLCommand).self::_ErrorMessageFooter_); }
}
$this->dbSQLResult=@$cn->store_result();
$this->dbSQLQueryTime=microtime(true)-$startTime;
/*at this point I have to recheck if it's a resource result*/
$this->_isObjectResult(true);
if($this->dbSQLResult===false) $this->dbSQLResult=true;
}
if($cn->errno) { throw new RC4PHP_DB_SQL_Exception('Invalid result.',-1); }
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the number of rows from result.
*
* @access protected
* @return integer | boolean
*/
protected function _getRows()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
try {
if($this->dbSQLResultRows==0)
{
$this->_checkConnectionAndResult();
$this->dbSQLResultRows=$this->dbSQLResult->num_rows;
}
return $this->dbSQLResultRows;
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the number of affected rows by the SQL command.
*
* @access protected
* @return integer | boolean
*/
protected function _getAffectedRows()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
try {
$this->_checkConnectionAndResult();
return $this->_getConnection()->affected_rows;
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the last inserted ID.
*
* @access protected
* @return integer | boolean
*/
protected function _getLastInsertedID()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
try {
$this->_checkConnectionAndResult();
return $this->_getConnection()->insert_id;
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the number of fields(columns) from result.
*
* @access protected
* @return integer | boolean
*/
protected function _getFields()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
try {
$this->_checkConnectionAndResult();
return $this->dbSQLResult->field_count;
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Returns the number of total rows not just the number of rows from
* current page for result.
*
* @access protected
* @return integer
*/
protected function _getTotalRows()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
if($this->dbSQLResultTotalRows==0)
{
$this->_checkConnection();
$sqlCn=&$this->_getConnection();
$sql=strtoupper($this->dbSQLCommand);
if(($sqlRs=@$sqlCn->query('SELECT SQL_CALC_FOUND_ROWS __rc4php__.* FROM ( '.$sql.' ) AS __rc4php__ LIMIT 0'))!==false)
{
$sqlRs->free();
$sqlRs=@$sqlCn->query('SELECT FOUND_ROWS() AS __rc4php__totalRows__');
$totalRows=@$sqlRs->fetch_row();
$this->dbSQLResultTotalRows=$totalRows[0];
@$sqlRs->free();
unset($sqlRs);
}
else
{ /*in this case SQL_CALC_FOUND_ROWS failed and I try with COUNT */
if(($sqlRs=@$sqlCn->query('SELECT COUNT(__rc4php__.*) AS __rc4php__totalRows__ FROM ( '.$sql.' ) AS __rc4php__'))!==false)
{
$totalRows=@$sqlRs->fetch_row();
$this->dbSQLResultTotalRows=$totalRows[0];
@$sqlRs->free();
unset($sqlRs);
}
else
{ /* in this last case COUNT also failed and I am forced to run directly the SQL query in order to get number of rows */
if(($sqlRs=@$sqlCn->query($sql))!==false)
{
$this->dbSQLResultTotalRows=@$sqlRs->num_rows;
@$sqlRs->free();
}
else $this->dbSQLResultTotalRows=0;
}
}
}
return $this->dbSQLResultTotalRows;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Send the SQL command to the SQL server.
*
* @access public
* @return boolean
*/
public function execute()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
try {
$this->_checkConnectionAndResult();
return true;
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch field or returns FALSE.
*
* @access public
* @return mixed | boolean
*/
public function fetchField($fieldOffset=NULL)
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
try {
$this->_checkConnectionAndResult();
return (($fieldOffset!==NULL)?($this->dbSQLResult->fetch_field_direct($fieldOffset)):($this->dbSQLResult->fetch_field()));
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns one row as an array. The method returns FALSE
* when no more rows are available.
*
* @access public
* @return array | boolean
*/
public function fetchRow()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
try {
$this->_checkConnectionAndResult();
++$this->dbSQLResultCurrentRow;
return $this->dbSQLResult->fetch_row();
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns one row as an associative array. The method
* returns FALSE when no more rows are available.
*
* @access public
* @return array | boolean
*/
public function fetchRowAssociative()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
try
{
$this->_checkConnectionAndResult();
++$this->dbSQLResultCurrentRow;
return $this->dbSQLResult->fetch_assoc();
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns one row as an associative and numerical array.
* The method returns FALSE when no more rows are available.
*
* @access public
* @return array | boolean
*/
public function fetchRowArray()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
try
{
$this->_checkConnectionAndResult();
++$this->dbSQLResultCurrentRow;
return $this->dbSQLResult->fetch_array();
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Fetch and returns one row as object.
* The method returns FALSE when no more rows are available.
*
* @access public
* @return object | boolean
*/
public function fetchObject()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
try
{
$this->_checkConnectionAndResult();
++$this->dbSQLResultCurrentRow;
return $this->dbSQLResult->fetch_object();
}
catch(Exception $e)
{
$this->freeResult();
if($this->dbSQLObject instanceof RC4PHP_DB_SQL) $this->dbSQLObject->disconnect();
throw $e;
}
}
//////////////////////////////////////////////////////////////////
/**
*
*
* When sending more than one SQL statement to the server or executing
* a stored procedure with multiple results, it will cause the server
* to return multiple result sets. This function will test for additional
* results available form the server. If an additional result set exists
* it will free the existing result set and prepare to fetch the rows from
* the new result set. The function will return TRUE if an additional result
* set was available or FALSE otherwise.
*
* @access public
* @return boolean
*/
public function nextResult()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
$this->freeResult();
$this->dbSQLResultRows=0;
$this->dbSQLResultCurrentRow=0;
$this->dbSQLResultCurrentPage=1;
$this->dbSQLResultPreviousPage=1;
$this->dbSQLResultCurrentPageStartingRow=0;
$cn=&$this->_getConnection();
if($cn->more_results() && $cn->next_result())
{
$this->dbSQLResult=$cn->store_result();
if($cn->errno) { throw new RC4PHP_DB_SQL_Exception('Invalid result.',-1); }
return true;
}
else return false;
}
//////////////////////////////////////////////////////////////////
/**
*
*
* Frees the associated result memory.
*
* @access public
* @return boolean
*/
public function freeResult()
/////class RC4PHP_DB_MySQL_Result/////////////////////////////////
{
$returnedValue=false;
if($this->_isObjectResult(true)) $returnedValue=$this->dbSQLResult->free();
$this->dbSQLResult=false;
return $returnedValue;
}
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* class RC4PHP_DB_MySQL_DATA_DICTIONARY
*
* It's a MySQL 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),$optionalScale=self::DB_DEFAULT_NUMERIC_SCALE);
*
* @access public
*/
class RC4PHP_DB_MySQL_DATA_DICTIONARY extends RC4PHP_DB_SQL_DATA_DICTIONARY
{
//////////////////////////////////////////////////////////////////
public function __construct($dbSQLcommand='')
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{ parent::__construct($dbSQLcommand); }
//////////////////////////////////////////////////////////////////
protected function _boolean()
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{ return 'boolean'; }
//////////////////////////////////////////////////////////////////
protected function _char($size=self::DB_DEFAULT_CHAR_SIZE)
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{
if(($size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_CHAR_SIZE))):(abs(intval($size))))>255) $size=255;
return "char($size)";
}
//////////////////////////////////////////////////////////////////
protected function _unicodeChar($size=self::DB_DEFAULT_UNICODE_CHAR_SIZE)
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{
if(($size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_UNICODE_CHAR_SIZE))):(abs(intval($size))))>255) $size=255;
return "char($size) unicode";
}
//////////////////////////////////////////////////////////////////
protected function _varChar($size=self::DB_DEFAULT_VARCHAR_SIZE)
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{
if(($size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_VARCHAR_SIZE))):(abs(intval($size))))>65535) $size=65535;
return "varchar($size)";
}
//////////////////////////////////////////////////////////////////
protected function _unicodeVarChar($size=self::DB_DEFAULT_UNICODE_VARCHAR_SIZE)
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{
$size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_UNICODE_VARCHAR_SIZE))):(abs(intval($size)));
if($size>4000) $size=4000;
return "varchar($size) CHARACTER SET utf8 COLLATE utf8_general_ci";
}
//////////////////////////////////////////////////////////////////
protected function _binary()
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{ return 'longblob'; }
//////////////////////////////////////////////////////////////////
protected function _float($size=self::DB_DEFAULT_FLOAT_SIZE)
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{
if(($size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_FLOAT_SIZE))):(abs(intval($size))))>53) $size=53;
return "float($size)";
}
//////////////////////////////////////////////////////////////////
protected function _integer($size=self::DB_DEFAULT_INTEGER_SIZE)
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{
$size=(is_array($size))?((isset($size[0])?(abs(intval($size[0]))):(self::DB_DEFAULT_INTEGER_SIZE))):(abs(intval($size)));
if($size>8) $size=8;
switch($size)
{
case 1: return 'tinyint';
case 2: return 'smallint';
case 4: return 'int';
case 8: return 'bigint';
default: return '';
}
}
//////////////////////////////////////////////////////////////////
protected function _numeric($fieldDefinition=array(self::DB_DEFAULT_NUMERIC_PRECISION,self::DB_DEFAULT_NUMERIC_SCALE),$optionalScale=self::DB_DEFAULT_NUMERIC_SCALE)
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{
if(($precision=(is_array($fieldDefinition))?((isset($fieldDefinition[0]))?(abs(intval($fieldDefinition[0]))):(self::DB_DEFAULT_NUMERIC_PRECISION)):(abs(intval($fieldDefinition))))>65) $precision=65;
if(($scale=(is_array($fieldDefinition))?((isset($fieldDefinition[1]))?(abs(intval($fieldDefinition[1]))):(self::DB_DEFAULT_NUMERIC_SCALE)):((empty($optionalScale)?(self::DB_DEFAULT_NUMERIC_SCALE):(abs(intval($optionalScale))))))>$precision) $scale=$precision;
return "numeric($precision,$scale)";
}
//////////////////////////////////////////////////////////////////
protected function _dateTime()
///class RC4PHP_DB_MySQL_DATA_DICTIONARY//////////////////////////
{ return 'datetime'; }
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
/**
* class RC4PHP_DB_MySQL_Exception
*
* It's the MySQL exception class.
*
* 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
*/
class RC4PHP_DB_MySQL_Exception extends RC4PHP_DB_SQL_Exception
{
//////////////////////////////////////////////////////////////////
/**
* Constructing RC4PHP_DB_MySQL_Exception object
*
* Initialize object's properties.
*
* @param object $dbSQLConnection
* @param string $message
* @param integer $code
* @return RC4PHP_DB_SQL_Exception
*/
public function __construct(&$dbSQLConnection=false,$SQLErrorMessage=self::_ExceptionDefaultMessage_,$SQLErrorCode=self::_ExceptionDefaultCode_)
///class RC4PHP_DB_MySQL_Exception////////////////////////////////
{
parent::__construct($SQLErrorMessage, $SQLErrorCode);
if(@is_object($dbSQLConnection))
{
if($errorMessage=@mysqli_error($dbSQLConnection)) $this->message=@trim($SQLErrorMessage.' '.RC4PHP_DB_SQL_Result::_ServerErrorMessageHeader_.$errorMessage.RC4PHP_DB_SQL_Result::_ServerErrorMessageFooter_);
else $this->message=trim($SQLErrorMessage);
if(!$SQLErrorCode) $this->code=@mysqli_errno($dbSQLConnection);
}
else
{
if($errorMessage=@mysqli_error()) $this->message=@trim($SQLErrorMessage.' '.RC4PHP_DB_SQL_Result::_ServerErrorMessageHeader_.$errorMessage.RC4PHP_DB_SQL_Result::_ServerErrorMessageFooter_);
else $this->message=trim($SQLErrorMessage);
if(!$SQLErrorCode) $this->code=@mysqli_errno();
}
}
//////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
?>