Source for file adodb.inc.php
Documentation is available at adodb.inc.php
* Set tabs to 4 for best viewing.
* Latest version is available at http://adodb.sourceforge.net/
* This is the main include file for ADOdb.
* Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
* The ADOdb files are formatted so that doxygen can be used to generate documentation.
* Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
@version V4.97 22 Jan 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license. You can choose which license
PHP's database access functions are not standardised. This creates a need for a database
class library to hide the differences between the different database API's (encapsulate
the differences) so we can easily switch databases.
We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
other databases via ODBC.
Latest Download at http://adodb.sourceforge.net/
//==============================================================================================
//==============================================================================================
* Set ADODB_DIR to the directory where this file resides...
* This constant was formerly called $ADODB_RootPath
if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__ ));
//==============================================================================================
//==============================================================================================
$ADODB_vers, // database version
$ADODB_COUNTRECS, // count number of records returned - slows down query
$ADODB_CACHE_DIR, // directory to cache recordsets
$ADODB_EXTENSION, // ADODB extension installed
$ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
$ADODB_FETCH_MODE, // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
$ADODB_QUOTE_FIELDNAMES; // Allows you to force quotes (backticks) around field names in queries generated by getinsertsql and getupdatesql.
//==============================================================================================
//==============================================================================================
$ADODB_EXTENSION = defined('ADODB_EXTENSION');
//********************************************************//
Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3).
Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi
0 = ignore empty fields. All empty fields in array are ignored.
1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and empty fields '' are set to empty '' sql values.
define('ADODB_FORCE_IGNORE',0);
define('ADODB_FORCE_EMPTY',2);
define('ADODB_FORCE_VALUE',3);
//********************************************************//
if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
// allow [ ] @ ` " and . in table names
define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
// prefetching used by oracle
if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
This currently works only with mssql, odbc, oci8po and ibase derived drivers.
0 = assoc lowercase field names. $rs->fields['orderid']
1 = assoc uppercase field names. $rs->fields['ORDERID']
2 = use native-case field names. $rs->fields['OrderID']
define('ADODB_FETCH_DEFAULT',0);
define('ADODB_FETCH_ASSOC',2);
if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
// PHP's version scheme makes converting to numbers difficult - workaround
$_adodb_ver = (float) PHP_VERSION;
if ($_adodb_ver >= 5.2) {
define('ADODB_PHPVER',0x5200);
} else if ($_adodb_ver >= 5.0) {
define('ADODB_PHPVER',0x5000);
} else if ($_adodb_ver > 4.299999) { # 4.3
define('ADODB_PHPVER',0x4300);
} else if ($_adodb_ver > 4.199999) { # 4.2
define('ADODB_PHPVER',0x4200);
} else if (strnatcmp(PHP_VERSION,'4.0.5')>= 0) {
define('ADODB_PHPVER',0x4050);
define('ADODB_PHPVER',0x4000);
//if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
Accepts $src and $dest arrays, replacing string $data
$ADODB_vers, // database version
$ADODB_COUNTRECS, // count number of records returned - slows down query
$ADODB_CACHE_DIR, // directory to cache recordsets
if (!isset ($ADODB_CACHE_DIR)) {
$ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
// do not accept url based paths, eg. http:/ or ftp:/
if (strpos($ADODB_CACHE_DIR,'://') !== false)
die("Illegal path http:// or ftp://");
// Initialize random number generator for randomizing cache flushes
// -- note Since PHP 4.2.0, the seed becomes optional and defaults to a random value if omitted.
* ADODB version as a string.
$ADODB_vers = 'V4.97 22 Jan 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
* Determines whether recordset->RecordCount() is used.
* Set to false for highest performance -- RecordCount() will always return -1 then
* for databases that provide "virtual" recordcounts...
if (!isset ($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
//==============================================================================================
// CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
//==============================================================================================
//==============================================================================================
//==============================================================================================
* Helper class for FetchFields -- holds info on a column
// additional fields by dannym... (danny_milo@yahoo.com)
// actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
// so we can as well make not_null standard (leaving it at "false" does not harm anyways)
var $has_default = false; // this one I have done only in mysql and postgres for now ...
// others to come (dannym)
var $default_value; // default, if any, and supported. Check has_default first.
//print "Errorno ($fn errno=$errno m=$errmsg) ";
$thisConnection->_transOK = false;
if ($thisConnection->_oldRaiseFn) {
$fn = $thisConnection->_oldRaiseFn;
$fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
//==============================================================================================
//==============================================================================================
* Connection object. For connecting to databases, and executing queries.
var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
var $database = ''; /// Name of database to be used.
var $host = ''; /// The hostname of the database server
var $user = ''; /// The username which is used to connect to the database server.
var $password = ''; /// Password for the username. For security, we no longer store it.
var $debug = false; /// if set to true will output sql statements
var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
var $substr = 'substr'; /// substring operator
var $length = 'length'; /// string length ofperator
var $random = 'rand()'; /// random function
var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
var $true = '1'; /// string that represents TRUE for a database
var $false = '0'; /// string that represents FALSE for a database
var $nameQuote = '"'; /// string to use to quote identifiers and names
var $charSet= false; /// character set to use - only for interbase, postgres and oci8
var $uniqueOrderBy = false; /// All order by columns have to be unique
var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
var $readOnly = false; /// this is a readonly database - used by phpLens
var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
var $hasGenID = false; /// can generate sequences using GenID();
var $genID = 0; /// sequence id used by GenID();
var $isoDates = false; /// accepts dates in ISO format
var $memCache = false; /// should we use memCache instead of caching in files
var $memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
var $sysDate = false; /// name of function that returns the current date
var $sysTimeStamp = false; /// name of function that returns the current timestamp
var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
var $uniqueSort = false; /// indicates that all fields in order by must be unique
var $leftOuter = false; /// operator to use for left outer join in WHERE clause
var $rightOuter = false; /// operator to use for right outer join in WHERE clause
var $ansiOuter = false; /// whether ansi outer join syntax supported
var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
var $autoCommit = true; /// do not modify this yourself - actually private
var $transOff = 0; /// temporarily disable transactions
var $transCnt = 0; /// count of nested transactions
var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null
var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
/// then returned by the errorMsg() function
var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
var $_queryID = false; /// This variable keeps the last created result link identifier
var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
die('Virtual Class -- cannot instantiate');
return (float) substr($ADODB_vers,1);
Get server version info...
@returns An array with 2 elements: $arr['string'] is the description string,
and $arr[version] is the version (also a string).
return array('description' => '', 'version' => '');
if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
* All error messages go through this bottleneck function.
* You can define your own handler by defining the function name in ADODB_OUTP.
function outp($msg,$newline= true)
global $ADODB_FLUSH,$ADODB_OUTP;
} else if (isset ($ADODB_OUTP)) {
if ($newline) $msg .= "<br>\n";
if (isset ($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
* @param [argHostname] Host to connect to
* @param [argUsername] Userid to login
* @param [argPassword] Associated password
* @param [argDatabaseName] database
* @param [forceNew] force new connection
function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
if ($argHostname != "") $this->host = $argHostname;
if ($argUsername != "") $this->user = $argUsername;
if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
if ($argDatabaseName != "") $this->database = $argDatabaseName;
if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
* Always force a new connection to database - currently only works with oracle
* @param [argHostname] Host to connect to
* @param [argUsername] Userid to login
* @param [argPassword] Associated password
* @param [argDatabaseName] database
function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
* Establish persistent connect to database
* @param [argHostname] Host to connect to
* @param [argUsername] Userid to login
* @param [argPassword] Associated password
* @param [argDatabaseName] database
* @return return true or false
function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
if (defined('ADODB_NEVER_PERSIST'))
return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
if ($argHostname != "") $this->host = $argHostname;
if ($argUsername != "") $this->user = $argUsername;
if ($argPassword != "") $this->password = $argPassword;
if ($argDatabaseName != "") $this->database = $argDatabaseName;
if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
// Format date column in sql string given an input format that understands Y M D
return $col; // child class implement
* Should prepare the sql statement and return the stmt resource.
* For databases that do not support this, we return the $sql. To ensure
* compatibility with databases that do not support prepare:
* $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
* $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
* $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
* @param sql SQL to send to database
* @return return FALSE, or the prepared statement, or the original sql if
* if the database does not support prepare.
* Some databases, eg. mssql require a different function for preparing
* stored procedures. So we cannot use Prepare().
* Should prepare the stored procedure and return the stmt resource.
* For databases that do not support this, we return the $sql. To ensure
* compatibility with databases that do not support prepare:
* @param sql SQL to send to database
* @return return FALSE, or the prepared statement, or the original sql if
* if the database does not support prepare.
return $this->Prepare($sql,$param);
Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
#if (!empty($this->qNull)) if ($s == 'null') return $s;
* PEAR DB Compat - do not use internally.
* PEAR DB Compat - do not use internally.
return $this->GenID($seq_name);
* Lock a row, will escalate and lock the table if row locking not supported
* will normally free the lock at the end of the transaction
* @param $table name of table to lock
* @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
* PEAR DB Compat - do not use internally.
* The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
* @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
* @returns The previous fetch mode
global $ADODB_FETCH_MODE;
return $ADODB_FETCH_MODE;
* PEAR DB Compat - do not use internally.
function &Query($sql, $inputarr= false)
$rs = &$this->Execute($sql, $inputarr);
* PEAR DB Compat - do not use internally
function &LimitQuery($sql, $offset, $count, $params= false)
$rs = &$this->SelectLimit($sql, $count, $offset, $params);
* PEAR DB Compat - do not use internally
Returns placeholder for parameter, eg.
will return ':a' for Oracle, and '?' for most other databases...
For databases that require positioned params, eg $1, $2, $3 for postgresql,
pass in Param(false) before setting the first parameter.
function Param($name,$type= 'C')
InParameter and OutParameter are self-documenting versions of Parameter().
function InParameter(&$stmt,&$var,$name,$maxLen= 4000,$type= false)
function OutParameter(&$stmt,&$var,$name,$maxLen= 4000,$type= false)
$stmt = $db->Prepare('select * from table where id =:myid and group=:group');
$db->Parameter($stmt,$id,'myid');
$db->Parameter($stmt,$group,'group',64);
@param $stmt Statement returned by Prepare() or PrepareSP().
@param $var PHP variable to bind to
@param $name Name of stored procedure variable name to bind to.
@param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
@param [$maxLen] Holds an maximum length of the variable.
@param [$type] The data type of $var. Legal values depend on driver.
function Parameter(&$stmt,&$var,$name,$isOutput= false,$maxLen= 4000,$type= false)
Improved method of initiating a transaction. Used together with CompleteTrans().
a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
Only the outermost block is treated as a transaction.<br>
b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
are disabled, making it backward compatible.
function StartTrans($errfn = 'ADODB_TransMonitor')
Used together with StartTrans() to end a transaction. Monitors connection
for sql errors, and will commit or rollback as appropriate.
@autoComplete if true, monitor sql errors and commit and rollback as appropriate,
and if set to false force rollback even if no SQL error detected.
@returns true on commit, false on rollback.
if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
At the end of a StartTrans/CompleteTrans block, perform a rollback.
Check if transaction has failed, only for Smart Transactions.
* @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
* @param [inputarr] holds the input data to bind to. Null elements will be set to null.
* @return RecordSet or false
function &Execute($sql,$inputarr= false)
$ret = & $fn($this,$sql,$inputarr);
if (isset ($ret)) return $ret;
if (!is_array($inputarr)) $inputarr = array($inputarr);
$element0 = reset($inputarr);
# is_object check because oci8 descriptors can be passed in
//remove extra memory copy of input -mikefedyk
if (!$array_2d) $inputarr = array($inputarr);
foreach($inputarr as $arr) {
//Use each() instead of foreach to reduce memory usage -mikefedyk
while(list (, $v) = each($arr)) {
// from Ron Baldwin <ron.baldwin#sourceprose.com>
// Only quote string types
//New memory copy of input created here -mikefedyk
else if ($typ == 'double')
$sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
else if ($typ == 'boolean')
else if ($typ == 'object') {
else $sql .= $this->qstr((string) $v);
if (isset ($sqlarr[$i])) {
} else if ($i != sizeof($sqlarr))
foreach($inputarr as $arr) {
$ret = & $this->_Execute($sql,$inputarr);
function &_Execute($sql,$inputarr= false)
global $ADODB_INCLUDED_LIB;
if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR. '/adodb-lib.inc.php');
$this->_queryID = @$this->_query($sql,$inputarr);
/************************
*************************/
if ($this->_queryID === false) { // error handling if query fails
if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
// return real recordset from select statement
$rs->connection = &$this; // Pablo suggestion
if ($rs->_numOfRows <= 0) {
if (empty($this->_genSeqSQL)) return false;
if (empty($this->_dropSeqSQL)) return false;
* Generates a sequence id and stores it in $this->genID;
* GenID is only available if $this->hasGenID = true;
* @param seqname name of sequence to use
* @param startID if sequence does not exist, start at this ID
* @return 0 if not supported, otherwise a sequence id
function GenID($seqname= 'adodbseq',$startID= 1)
return 0; // formerly returns false pre 1.60
$getnext = sprintf($this->_genIDSQL,$seqname);
$this->_transOK = $holdtransOK; //if the status was ok before reset
$createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
else $this->genID = 0; // false
* @param $table string name of the table, not needed by all databases (eg. mysql), default ''
* @param $column string name of the column, not needed by all databases (eg. mysql), default ''
* @return the last inserted ID. Not all databases support this.
if ($this->hasInsertID) return $this->_insertid($table,$column);
* Portable Insert ID. Pablo Roca <pabloroca#mvps.org>
* @return the last inserted ID. All databases support this. But aware possible
* problems in multiuser environments. Heavy test this before deploying.
return $this->GetOne("SELECT MAX($id) FROM $table");
* @return # rows affected by UPDATE/DELETE
$val = $this->_affectedrows();
return ($val < 0) ? false : $val;
* @return the last error message
* @return the last error number. Normally 0 means no error.
include_once(ADODB_DIR. "/adodb-error.inc.php");
include_once(ADODB_DIR. "/adodb-error.inc.php");
* @returns an array with the primary key columns in it.
// owner not used in base class - see oci8
if (!empty($v->primary_key))
* @returns assoc array where keys are tables, and values are foreign keys
* Choose a database to connect to. Many databases do not support this.
* @param dbName is the name of the database to select
* Will select, getting rows from $offset (1-based), for $nrows.
* This simulates the MySQL "select * from table limit $offset,$nrows" , and
* the PostgreSQL "select * from table limit $nrows offset $offset". Note that
* MySQL and PostgreSQL parameter ordering is the opposite of the other.
* SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
* SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
* Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
* BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
* @param [offset] is the row to start calculations from (1-based)
* @param [nrows] is the number of rows to get
* @param [inputarr] array of bind variables
* @param [secs2cache] is a private parameter only used by jlim
* @return the recordset ($rs->databaseType == 'array')
function &SelectLimit($sql,$nrows=- 1,$offset=- 1, $inputarr= false,$secs2cache= 0)
if ($this->hasTop && $nrows > 0) {
// suggested by Reinhard Balling. Access requires top after distinct
// Informix requires first before distinct - F Riosa
if ($ismssql) $isaccess = false;
// access includes ties in result
'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '. $this->hasTop. ' '. ((integer) $nrows). ' ',$sql);
$ret = & $this->Execute($sql,$inputarr);
'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '. $this->hasTop. ' '. ((integer) $nrows). ' ',$sql);
'/(^\s*select\s)/i','\\1 '. $this->hasTop. ' '. ((integer) $nrows). ' ',$sql);
if ($isaccess || $ismssql) {
'/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '. $this->hasTop. ' '. $nn. ' ',$sql);
'/(^\s*select\s)/i','\\1 '. $this->hasTop. ' '. $nn. ' ',$sql);
// if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
// 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
$savec = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
else $rs = &$this->Execute($sql,$inputarr);
if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
else $rs = &$this->Execute($sql,$inputarr);
$ADODB_COUNTRECS = $savec;
$rs = & $this->_rs2rs($rs,$nrows,$offset);
* Create serializable recordset. Breaks rs link to connection.
* @param rs the recordset to serialize
$rs2->connection = & $ignore;
* Convert database recordset to an array recordset
* input recordset's cursor should be at beginning, and
* old $rs will be closed.
* @param rs the recordset to copy
* @param [nrows] number of rows to retrieve (optional)
* @param [offset] offset by number of rows (optional)
* @return the new recordset
function &_rs2rs(&$rs,$nrows=- 1,$offset=- 1,$close= true)
$dbtype = $rs->databaseType;
$rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == - 1 && $offset == - 1) {
$rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
for ($i= 0, $max= $rs->FieldCount(); $i < $max; $i++ ) {
$flds[] = $rs->FetchField($i);
$arr = & $rs->GetArrayLimit($nrows,$offset);
if ($close) $rs->Close();
$rs2 = new $arrayClass();
$rs2->connection = &$this;
$rs2->InitArrayFields($arr,$flds);
$rs2->fetchMode = isset ($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
* Return all rows. Compat with PEAR DB
function &GetAll($sql, $inputarr= false)
$arr = & $this->GetArray($sql,$inputarr);
function &GetAssoc($sql, $inputarr= false,$force_array = false, $first2cols = false)
$rs = & $this->Execute($sql, $inputarr);
$arr = & $rs->GetAssoc($force_array,$first2cols);
function &CacheGetAssoc($secs2cache, $sql= false, $inputarr= false,$force_array = false, $first2cols = false)
$first2cols = $force_array;
$force_array = $inputarr;
$arr = & $rs->GetAssoc($force_array,$first2cols);
* Return first element of first row of sql statement. Recordset is disposed
* @param sql SQL statement
* @param [inputarr] input bind array
function GetOne($sql,$inputarr= false)
$crecs = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$rs = &$this->Execute($sql,$inputarr);
if ($rs->EOF) $ret = null;
else $ret = reset($rs->fields);
$ADODB_COUNTRECS = $crecs;
function CacheGetOne($secs2cache,$sql= false,$inputarr= false)
if ($rs->EOF) $ret = null;
else $ret = reset($rs->fields);
function GetCol($sql, $inputarr = false, $trim = false)
$rs = &$this->Execute($sql, $inputarr);
$rv[] = reset($rs->fields);
function CacheGetCol($secs, $sql = false, $inputarr = false,$trim= false)
$rv[] = reset($rs->fields);
function &Transpose(&$rs,$addfieldnames= true)
if (!$rs2) return $false;
$rs2->_transpose($addfieldnames);
Calculate the offset of a date for a particular database and generate
appropriate SQL. Useful for calculating future/past dates and storing
If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
if (!$date) $date = $this->sysDate;
return '('. $date. '+'. $dayFraction. ')';
* @param sql SQL statement
* @param [inputarr] input bind array
function &GetArray($sql,$inputarr= false)
$savec = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$rs = & $this->Execute($sql,$inputarr);
$ADODB_COUNTRECS = $savec;
function &CacheGetAll($secs2cache,$sql= false,$inputarr= false)
$savec = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$ADODB_COUNTRECS = $savec;
$rezarr = $this->GetAll($sql, $arr);
* Return one row of sql statement. Recordset is disposed for you.
* @param sql SQL statement
* @param [inputarr] input bind array
function &GetRow($sql,$inputarr= false)
$crecs = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$rs = & $this->Execute($sql,$inputarr);
$ADODB_COUNTRECS = $crecs;
if (!$rs->EOF) $arr = $rs->fields;
function &CacheGetRow($secs2cache,$sql= false,$inputarr= false)
if (!$rs->EOF) $arr = $rs->fields;
* Insert or replace a single record. Note: this is not the same as MySQL's replace.
* ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
* Also note that no table locking is done currently, so it is possible that the
* record be inserted twice by two programs...
* $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
* $fieldArray associative array of data (you must quote strings yourself).
* $keyCol the primary key field name or if compound key, array of field names
* autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
* but does not work with dates nor SQL functions.
* has_autoinc the primary key is an auto-inc field, so skip in insert.
* Currently blob replace not supported
* returns 0 = fail, 1 = update, 2 = insert
function Replace($table, $fieldArray, $keyCol, $autoQuote= false, $has_autoinc= false)
global $ADODB_INCLUDED_LIB;
if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR. '/adodb-lib.inc.php');
return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
* Will select, getting rows from $offset (1-based), for $nrows.
* This simulates the MySQL "select * from table limit $offset,$nrows" , and
* the PostgreSQL "select * from table limit $nrows offset $offset". Note that
* MySQL and PostgreSQL parameter ordering is the opposite of the other.
* CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
* CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
* BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
* @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
* @param [offset] is the row to start calculations from (1-based)
* @param [nrows] is the number of rows to get
* @param [inputarr] array of bind variables
* @return the recordset ($rs->databaseType == 'array')
function &CacheSelectLimit($secs2cache,$sql,$nrows=- 1,$offset=- 1,$inputarr= false)
if ($sql === false) $sql = - 1;
if ($offset == - 1) $offset = false;
// sql, nrows, offset,inputarr
$rs = & $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
* Flush cached recordsets that match a particular $sql statement.
* If $sql == false, then we purge all files in the cache.
* Flush cached recordsets that match a particular $sql statement.
* If $sql == false, then we purge all files in the cache.
global $ADODB_INCLUDED_MEMCACHE;
if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR. '/adodb-memcache.lib.inc.php');
if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
/*if (strncmp(PHP_OS,'WIN',3) === 0)
$dir = str_replace('/', '\\', $ADODB_CACHE_DIR);
global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR. '/adodb-csvlib.inc.php');
* Private function to erase all of the files and subdirectories in a directory.
* Just specify the directory, and tell it if you want to delete the directory or just clear it out.
* Note: $kill_top_level is used internally in the function to flush subdirectories.
function _dirFlush($dir, $kill_top_level = false)
if($obj== '.' || $obj== '..') continue;
global $ADODB_INCLUDED_MEMCACHE;
if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR. '/adodb-memcache.lib.inc.php');
if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
if (strncmp(PHP_OS,'WIN',3) === 0) {
$cmd = 'del /s '. str_replace('/','\\',$ADODB_CACHE_DIR). '\adodb_*.cache';
//$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f';
$cmd = 'rm -rf '. $ADODB_CACHE_DIR. '/[0-9a-f][0-9a-f]/';
// old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR. '/adodb-csvlib.inc.php');
* Private function to generate filename for caching.
* Filename is generated based on:
* - database type (oci8, ibase, ifx, etc)
* - setFetchMode (adodb 4.23)
* When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
* Assuming that we can have 50,000 files per directory with good performance,
* then we can scale to 12.8 million unique cached recordsets. Wow!
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
if ($memcache) return $m;
if (!isset ($notSafeMode)) $notSafeMode = !ini_get('safe_mode');
$dir = ($notSafeMode) ? $ADODB_CACHE_DIR. '/'. substr($m,0,2) : $ADODB_CACHE_DIR;
if ($createdir && $notSafeMode && !file_exists($dir)) {
return $dir. '/adodb_'. $m. '.cache';
* Execute SQL, caching recordsets.
* @param [secs2cache] seconds to cache data, set to 0 to force query.
* This is an optional parameter.
* @param sql SQL statement to execute
* @param [inputarr] holds the input data to bind to
* @return RecordSet or false
function &CacheExecute($secs2cache,$sql= false,$inputarr= false)
global $ADODB_INCLUDED_MEMCACHE;
if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR. '/adodb-memcache.lib.inc.php');
global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR. '/adodb-csvlib.inc.php');
ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
$rs = &$this->Execute($sqlparam,$inputarr);
$rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
$fn($this->databaseType,'CacheExecute',- 32000,"Cache write error",$md5file,$sql,$this);
$rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
$em = 'Cache write error';
$fn($this->databaseType,'CacheExecute', $en, $em, $md5file,$sql,$this);
$em = 'Cache file locked warning';
// do not call error handling for just a warning
//$rs = &csv2rs($md5file,$err);
$rs->connection = &$this; // Pablo suggestion
$fn($this, $secs2cache, $sql, $inputarr);
// ok, set cached object found
$rs->connection = &$this; // Pablo suggestion
$inBrowser = isset ($_SERVER['HTTP_USER_AGENT']);
$ttl = $rs->timeCreated + $secs2cache - time();
Similar to PEAR DB's autoExecute(), except that
$mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
If $mode == 'UPDATE', then $where is compulsory as a safety measure.
$forceUpdate means that even if the data has not changed, perform update.
function& AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate= true, $magicq= false)
$sql = 'SELECT * FROM '. $table;
if ($where!== FALSE) $sql .= ' WHERE '. $where;
else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
if (!$rs) return $false; // table does not exist
$sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
if ($sql) $ret = $this->Execute($sql);
* Generates an Update Query based on an existing recordset.
* $arrFields is an associative array of fields with the value
* that should be assigned.
* Note: This function should only be used on a recordset
* that is run against a single table and sql should only
* be a simple select stmt with no groupby/orderby/limit
* "Jonathan Younger" <jyounger@unilab.com>
function GetUpdateSQL(&$rs, $arrFields,$forceUpdate= false,$magicq= false,$force= null)
global $ADODB_INCLUDED_LIB;
//********************************************************//
//This is here to maintain compatibility
//with older adodb versions. Sets force type to force nulls if $forcenulls is set.
global $ADODB_FORCE_TYPE;
$force = $ADODB_FORCE_TYPE;
//********************************************************//
if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR. '/adodb-lib.inc.php');
* Generates an Insert Query based on an existing recordset.
* $arrFields is an associative array of fields with the value
* that should be assigned.
* Note: This function should only be used on a recordset
* that is run against a single table.
function GetInsertSQL(&$rs, $arrFields,$magicq= false,$force= null)
global $ADODB_INCLUDED_LIB;
global $ADODB_FORCE_TYPE;
$force = $ADODB_FORCE_TYPE;
if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR. '/adodb-lib.inc.php');
* Update a blob column, given a where clause. There are more sophisticated
* blob handling functions that we could have implemented, but all require
* a very complex API. Instead we have chosen something that is extremely
* simple to understand and use.
* Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
* Usage to update a $blobvalue which has a primary key blob_id=1 into a
* field blobtable.blobcolumn:
* UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
* $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
* $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
function UpdateBlob($table,$column,$val,$where,$blobtype= 'BLOB')
return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
* UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
* $blobtype supports 'BLOB' and 'CLOB'
* $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
* $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
function IfNull( $field, $ifNull )
return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
include_once(ADODB_DIR. '/adodb-perf.inc.php');
if ($enable) $this->fnExecute = 'adodb_log_sql';
* UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
* $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
* $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
// not the fastest implementation - quick and dirty - jlim
// for best performance, use the actual $rs->MetaType().
function MetaType($t,$len=- 1,$fieldobj= false)
if (empty($this->_metars)) {
$this->_metars->connection = & $this;
return $this->_metars->MetaType($t,$len,$fieldobj);
* Change the SQL connection locale to a specified locale.
* This is used to get the date formats written depending on the client locale.
global $_ADODB_ACTIVE_DBS;
if (empty($whereOrderBy)) $whereOrderBy = '1=1';
$rows = $this->GetAll("select * from ". $table. ' WHERE '. $whereOrderBy,$bindarr);
if (!isset ($_ADODB_ACTIVE_DBS)) {
include(ADODB_DIR. '/adodb-active-record.inc.php');
$obj = new $class($table,$primkeyArr,$this);
function &GetActiveRecords($table,$where= false,$bindarr= false,$primkeyArr= false)
* Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
* @return true if succeeded or false if database does not support transactions
/* set transaction mode */
http://msdn2.microsoft.com/en-US/ms173763.aspx
http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-isolation.html
http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html
http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm
return 'ISOLATION LEVEL READ COMMITTED';
return 'ISOLATION LEVEL READ UNCOMMITTED';
return 'ISOLATION LEVEL READ COMMITTED';
return 'ISOLATION LEVEL SERIALIZABLE';
return 'ISOLATION LEVEL REPEATABLE READ';
return 'ISOLATION LEVEL SERIALIZABLE';
* If database does not support transactions, always return true as data always commited
* @param $ok set to false to rollback transaction, true to commit
* If database does not support transactions, rollbacks always fail, so return false
* return the databases that the driver can connect to.
* Some databases will return an empty array.
* @return an array of database names.
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = $save;
* @param ttype can either be 'VIEW' or 'TABLE' or false.
* If false, both views and tables are returned.
* "VIEW" returns only views
* "TABLE" returns only tables
* @param showSchema returns the schema/user with the table name, eg. USER.TABLE
* @param mask is the input mask - only supported by oci8 and postgresql
* @return array of tables for current database.
function &MetaTables($ttype= false,$showSchema= false,$mask= false)
global $ADODB_FETCH_MODE;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = $save;
if ($rs === false) return $false;
if ($hast = ($ttype && isset ($arr[0][1]))) {
for ($i= 0; $i < sizeof($arr); $i++ ) {
if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
$arr2[] = trim($arr[$i][0]);
if (!$schema && ($at = strpos($table,'.')) !== false) {
$schema = substr($table,0,$at);
$table = substr($table,$at+ 1);
* List columns in a database as an array of ADOFieldObjects.
* See top of file for definition of object.
* @param $table table name to query
* @param $normalize makes table name case-insensitive (required by some databases)
* @schema is optional database schema to use - not supported by all databases.
* @return array of ADOFieldObjects for current table.
global $ADODB_FETCH_MODE;
if (!empty($this->metaColumnsSQL)) {
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = $save;
if ($rs === false || $rs->EOF) return $false;
while (!$rs->EOF) { //print_r($rs->fields);
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
if (isset ($rs->fields[3]) && $rs->fields[3]) {
if ($rs->fields[3]> 0) $fld->max_length = $rs->fields[3];
$fld->scale = $rs->fields[4];
if ($fld->scale> 0) $fld->max_length += 1;
$fld->max_length = $rs->fields[2];
* List indexes on a table as an array.
* @param table table name to query
* @param primary true to only show primary keys. Not actually used for most databases
* @return array of indexes on current table. Each element represents an index, and is itself an associative array.
[unique] => true or false
function &MetaIndexes($table, $primary = false, $owner = false)
* List columns names in a table as an array.
* @param table table name to query
* @return array of column names for current table.
function &MetaColumnNames($table, $numIndexes= false,$useattnum= false /* only for postgres */)
$arr[$v->attnum] = $v->name;
foreach($objarr as $v) $arr[$i++ ] = $v->name;
foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
* Different SQL databases used different methods to combine strings together.
* This function provides a wrapper.
* param s variable number of string parameters
* Usage: $db->Concat($str1,$str2);
* @return concatenated string
* Converts a date "d" to a string that the database can understand.
* @param d a date in Unix date time format.
* @return date string in database date format
if (empty($d) && $d !== 0) return 'null';
if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
* Converts a timestamp "ts" to a string that the database can understand.
* @param ts a timestamp in Unix date time format.
* @return timestamp string in database timestamp format
if (empty($ts) && $ts !== 0) return 'null';
# strlen(14) allows YYYYMMDDHHMMSS format
if ($ts === 'null') return $ts;
* @param $v is a date string in YYYY-MM-DD format
* @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
($v), $rr)) return false;
* @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
* @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
//( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
"|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
($v), $rr)) return false;
if (!isset ($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
* Format database date based on user defined format.
* @param v is the character date in YYYY-MM-DD format, returned by database
* @param fmt is the format to apply to it, using date()
* @return a date formated as user desires
function UserDate($v,$fmt= 'Y-m-d',$gmt= false)
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == - 1) && $v != false) return $v;
else if ($tt == - 1) { // pre-TIMESTAMP_FIRST_YEAR
* @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
* @param fmt is the format to apply to it, using date()
* @return a timestamp formated as user desires
# strlen(14) allows YYYYMMDDHHMMSS format
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == - 1) && $v != false) return $v;
function escape($s,$magic_quotes= false)
return $this->addq($s,$magic_quotes);
* Quotes a string, without prefixing nor appending quotes.
function addq($s,$magic_quotes= false)
$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
//$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
// undo magic quotes for "
if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
else {// change \' to '' for sybase/mssql
* Correctly quotes a string so that all strings are escaped. We prefix and append
* to the string single-quotes.
* An example is $db->qstr("Don't bother",magic_quotes_runtime());
* @param s the string to quote
* @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
* This undoes the stupidity of magic quotes for GPC.
* @return quoted string to be sent back to database
function qstr($s,$magic_quotes= false)
$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
//$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
// undo magic quotes for "
if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
else {// change \' to '' for sybase/mssql
* Will select the supplied $page number from a recordset, given that it is paginated in pages of
* $nrows rows per page. It also saves two boolean values saying if the given page is the first
* and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
* See readme.htm#ex8 for an example of usage.
* @param nrows is the number of rows per page to get
* @param page is the page number to get (1-based)
* @param [inputarr] array of bind variables
* @param [secs2cache] is a private parameter only used by jlim
* @return the recordset ($rs->databaseType == 'array')
* NOTE: phpLens uses a different algorithm and does not use PageExecute().
function &PageExecute($sql, $nrows, $page, $inputarr= false, $secs2cache= 0)
global $ADODB_INCLUDED_LIB;
if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR. '/adodb-lib.inc.php');
* Will select the supplied $page number from a recordset, given that it is paginated in pages of
* $nrows rows per page. It also saves two boolean values saying if the given page is the first
* and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
* @param secs2cache seconds to cache data, set to 0 to force query
* @param nrows is the number of rows per page to get
* @param page is the page number to get (1-based)
* @param [inputarr] array of bind variables
* @return the recordset ($rs->databaseType == 'array')
/*switch($this->dataProvider) {
default: $secs2cache = 0; break;
$rs = & $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
} // end class ADOConnection
//==============================================================================================
//==============================================================================================
* Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
//==============================================================================================
// CLASS ADORecordSet_empty
//==============================================================================================
* Lightweight recordset when there are no records to be returned
function Close(){return true;}
//==============================================================================================
// DATE AND TIME FUNCTIONS
//==============================================================================================
if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR. '/adodb-time.inc.php');
//==============================================================================================
//==============================================================================================
if (PHP_VERSION < 5) include_once(ADODB_DIR. '/adodb-php4.inc.php');
else include_once(ADODB_DIR. '/adodb-iterator.inc.php');
* RecordSet class that represents the dataset returned by the database.
* To keep memory overhead low, this class holds only the current row in memory.
* No prefetching of data is done, so the RecordCount() can return -1 ( which
* means recordcount not known).
var $fields = false; /// holds the current row data
var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
/// in other words, we use a text area for editing.
var $canSeek = false; /// indicates that seek is supported
var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
var $emptyDate = ' '; /// what to display when $time==0
var $timeCreated= 0; /// datetime in Unix format rs created -- for cached recordsets
var $bind = false; /// used by Fields() to hold array - should be private?
var $_queryID = - 1; /** This variable keeps the result link identifier. */
var $_currentRow = - 1; /** This variable keeps the current row in the Recordset. */
var $_closed = false; /** has recordset been closed */
var $_inited = false; /** Init() should only be called once */
var $_obj; /** Used by FetchObj */
var $_names; /** Used by FetchObj */
var $_currentPage = - 1; /** Added by Iván Oliva to implement recordset pagination */
var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */
var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */
* @param queryID this is the queryID returned by ADOConnection->_query()
if ($this->EOF = ($this->_fetch() === false)) {
* Generate a SELECT tag string from a recordset, and return the string.
* If the recordset has 2 cols, we treat the 1st col as the containing
* the text to display to the user, and 2nd col as the return value. Default
* strings are compared with the FIRST column.
* @param name name of SELECT tag
* @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
* @param [blank1stItem] true to leave the 1st item in list empty
* @param [multiple] true for listbox, false for popup
* @param [size] #rows to show for listbox. not used by popup
* @param [selectAttr] additional attributes to defined for SELECT tag.
* useful for holding javascript onChange='...' handlers.
& @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
* column 0 (1st col) if this is true. This is not documented.
* changes by glen.davies@cce.ac.nz to support multiple hilited items
function GetMenu($name,$defstr= '',$blank1stItem= true,$multiple= false,
$size= 0, $selectAttr= '',$compareFields0= true)
global $ADODB_INCLUDED_LIB;
if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR. '/adodb-lib.inc.php');
$size, $selectAttr,$compareFields0);
* Generate a SELECT tag string from a recordset, and return the string.
* If the recordset has 2 cols, we treat the 1st col as the containing
* the text to display to the user, and 2nd col as the return value. Default
* strings are compared with the SECOND column.
function GetMenu2($name,$defstr= '',$blank1stItem= true,$multiple= false,$size= 0, $selectAttr= '')
return $this->GetMenu($name,$defstr,$blank1stItem,$multiple,
$size, $selectAttr,false);
function GetMenu3($name,$defstr= '',$blank1stItem= true,$multiple= false,
global $ADODB_INCLUDED_LIB;
if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR. '/adodb-lib.inc.php');
$size, $selectAttr,false);
* return recordset as a 2-dimensional array.
* @param [nRows] is the number of rows to return. -1 means every row.
* @return an array indexed by the rows (0-based) from the recordset
global $ADODB_EXTENSION; if ($ADODB_EXTENSION) {
$results = adodb_getall($this,$nRows);
while (!$this->EOF && $nRows != $cnt) {
* Some databases allow multiple recordsets to be returned. This function
* will return true if there is a next recordset, or false if no more.
* return recordset as a 2-dimensional array.
* Helper function for ADOConnection->SelectLimit()
* @param offset is the row to start calculations from (1-based)
* @param [nrows] is the number of rows to return
* @return an array indexed by the rows (0-based) from the recordset
while (!$this->EOF && $nrows != $cnt) {
$results[$cnt++ ] = $this->fields;
* Synonym for GetArray() for compatibility with ADO.
* @param [nRows] is the number of rows to return. -1 means every row.
* @return an array indexed by the rows (0-based) from the recordset
* return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
* The first column is treated as the key and is not included in the array.
* If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
* @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
* array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
* @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
* instead of returning array[col0] => array(remaining cols), return array[col0] => col1
* @return an associative array indexed by the first column of the array,
* or false if the data has less than 2 cols.
function &GetAssoc($force_array = false, $first2cols = false)
$numIndex = isset ($this->fields[0]);
if (!$first2cols && ($cols > 2 || $force_array)) {
// Fix for array_slice re-numbering numeric associative keys
$sliced_array[$key] = $this->fields[$key];
// Fix for array_slice re-numbering numeric associative keys
$sliced_array[$key] = $this->fields[$key];
// some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
// some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
// some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
// some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
$ref = & $results; # workaround accelerator incompat with PHP 4.4 :(
* @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
* @param fmt is the format to apply to it, using date()
* @return a timestamp formated as user desires
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == - 1) && $v != false) return $v;
* @param v is the character date in YYYY-MM-DD format, returned by database
* @param fmt is the format to apply to it, using date()
* @return a date formated as user desires
// $tt == -1 if pre TIMESTAMP_FIRST_YEAR
if (($tt === false || $tt == - 1) && $v != false) return $v;
else if ($tt == - 1) { // pre-TIMESTAMP_FIRST_YEAR
* @param $v is a date string in YYYY-MM-DD format
* @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
* @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
* @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
* PEAR DB Compat - do not use internally
* PEAR DB compat, number of rows
* PEAR DB compat, number of cols
* Fetch a row, returning false if no more rows.
* This is PEAR DB compat mode.
* @return false or array containing the current record
if (!$this->_fetch()) $this->EOF = true;
* Fetch a row, returning PEAR_Error if no more rows.
* This is PEAR DB compat mode.
* @return DB_OK or error object
if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',- 1): false;
* Move to the first row in the recordset. Many databases do NOT support this.
* Move to the last row in the recordset.
if ($this->EOF) return false;
* Move to next record in the recordset.
* @return true if there still rows available, or false if there are no more rows (EOF).
if ($this->_fetch()) return true;
/* -- tested error handling when scrolling cursor -- seems useless.
$conn = $this->connection;
if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
$fn = $conn->raiseErrorFn;
$fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
* Random access to a specific row in the recordset. Some databases do not support
* access to previous rows in the databases (no scrolling backwards).
* @param rowNumber is the row to move to (0-based)
* @return true if there still rows available, or false if there are no more rows (EOF).
function Move($rowNumber = 0)
if ($this->_seek($rowNumber)) {
if (!$this->_fetch()) $this->EOF = true;
* Get the value of a field in the current row by column name.
* Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
* @param colname is the field to access
* @return the value of $colname column
return $this->fields[$colname];
if ($upper === 2) $this->bind[$o->name] = $i;
* Use associative array to get fields array for databases that do not support
* associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it
* If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
* before you execute your SQL statement, and access $rs->fields['col'] directly.
* $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
// if (!$this->fields) return $record;
foreach($this->bind as $k => $v) {
$record[$k] = $this->fields[$v];
// free connection object - this seems to globally free the object
// and not merely the reference, so don't do this...
// $this->connection = false;
* synonyms RecordCount and RowCount
* @return the number of rows or -1 if this is not supported
* If we are using PageExecute(), this will return the maximum possible rows
* that can be returned when paging a recordset.
* synonyms RecordCount and RowCount
* @return the number of rows or -1 if this is not supported
* Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
* @return the number of records from a previous SELECT. All databases support this.
* But aware possible problems in multiuser environments. For better speed the table
* must be indexed by the condition. Heavy test this before deploying.
// the database doesn't support native recordcount, so we do a workaround
if ($condition) $condition = " WHERE " . $condition;
$resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
if ($resultrows) $lnumrows = reset($resultrows->fields);
* @return the current row in the recordset. If at EOF, will return the last row. 0-based.
* synonym for CurrentRow -- for ADO compat
* @return the current row in the recordset. If at EOF, will return the last row. 0-based.
* @return the number of columns in the recordset. Some databases will set this to 0
* if no records are returned, others will return the number of columns in the query.
* Get the ADOFieldObject of a specific column.
* @param fieldoffset is the column position to access(0-based).
* @return the ADOFieldObject for that column, or false.
// must be defined by child class
* Get the ADOFieldObjects of all columns in an array.
* Return the fields array of the current row as an object for convenience.
* The default case is lowercase field names.
* @return the object with the properties set to the fields of the current row
* Return the fields array of the current row as an object for convenience.
* The default case is uppercase.
* @param $isupper to set the object property names to uppercase
* @return the object with the properties set to the fields of the current row
if (empty($this->_obj)) {
if (PHP_VERSION >= 5) $o = clone($this->_obj);
$o->$n = $this->Fields($name);
* Return the fields array of the current row as an object for convenience.
* The default is lower-case field names.
* @return the object with the properties set to the fields of the current row,
* Fixed bug reported by tim@orotech.net
* Return the fields array of the current row as an object for convenience.
* The default is upper case field names.
* @param $isupper to set the object property names to uppercase
* @return the object with the properties set to the fields of the current row,
* Fixed bug reported by tim@orotech.net
if ($this->_fetch()) return $o;
* Get the metatype of the column. This is used for formatting. This is because
* many databases use different names for the same type, so we transform the original
* type to our standardised version which uses 1 character codes:
* @param t is the type passed in. Normally is ADOFieldObject->type.
* @param len is the maximum length of that field. This is because we treat character
* fields bigger than a certain size as a 'B' (blob).
* @param fieldobj is the field object returned by the database driver. Can hold
* additional info (eg. primary_key for mysql).
* @return the general type of the data:
* C for character < 250 chars
* X for teXt (>= 250 chars)
* N for numeric or floating point
* R for autoincrement counter/integer
function MetaType($t,$len=- 1,$fieldobj= false)
$len = $fieldobj->max_length;
// changed in 2.32 to hashing instead of switch stmt for speed...
'INTERVAL' => 'C', # Postgres
'MACADDR' => 'C', # postgres
'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
'INTEGER UNSIGNED' => 'I',
'LONG' => 'N', // interbase is numeric, oci8 is blob
'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
'DOUBLE PRECISION' => 'N',
$tmap = (isset ($typeMap[$t])) ? $typeMap[$t] : 'N';
// is the char field is too long, return as text field...
if ($this->blobSize >= 0) {
if ($len > $this->blobSize) return 'X';
if (!empty($fieldobj->primary_key)) return 'R';
if (isset ($fieldobj->binary))
return ($fieldobj->binary) ? 'B' : 'X';
if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
* set/returns the current recordset page when paginating
* set/returns the status of the atFirstPage flag when paginating
* set/returns the status of the atLastPage flag when paginating
} // end class ADORecordSet
//==============================================================================================
// CLASS ADORecordSet_array
//==============================================================================================
* This class encapsulates the concept of a recordset created in memory
* as an array. This is useful for the creation of cached recordsets.
* Note that the constructor is different from the standard ADORecordSet
var $_array; // holds the 2-dimensional data array
var $_types; // the array of types of each column (C B I L M)
var $_skiprow1; // skip 1st row because it holds column names
global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
// fetch() on EOF does not delete $this->fields
$this->compat = !empty($ADODB_COMPAT_FETCH);
global $ADODB_INCLUDED_LIB;
if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR. '/adodb-lib.inc.php');
foreach($hdr as $k => $name) {
* @param array is a 2-dimensional array holding the data.
* The first row should hold the column names
* unless paramter $colnames is used.
* @param typearr holds an array of types. These are the same types
* used in MetaTypes (C,B,L,I,N).
* @param [colnames] array of column names. If set, then the first row of
* $array should not hold the column names.
function InitArray($array,$typearr,$colnames= false)
* Setup the Array and datatype file objects
* @param array is a 2-dimensional array holding the data.
* The first row should hold the column names
* unless paramter $colnames is used.
* @param fieldarr holds an array of ADOFieldObject's.
/* Use associative array to get fields array */
$mode = isset ($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode;
return $this->fields[$colname];
$o->type = $this->_types[$fieldOffset];
$o->max_length = - 1; // length not known
//==============================================================================================
//==============================================================================================
* Synonym for ADOLoadCode. Private function. Do not use.
* Load the code for a specific database driver. Private function. Do not use.
if (!$dbType) return false;
if (PHP_VERSION >= 5) $db = 'ado5';
case 'maxsql': $class = $db = 'mysqlt'; break;
case 'pgsql': $class = $db = 'postgres7'; break;
$file = ADODB_DIR. "/drivers/adodb-". $db. ".inc.php";
//ADOConnection::outp(adodb_pr(get_declared_classes(),true));
* synonym for ADONewConnection for people like me who cannot remember the correct name
* Instantiate a new Connection class for a specific database driver.
* @param [db] is the database Connection object to create. If undefined,
* use the last database driver that was loaded by ADOLoadCode().
* @return the freshly created instance of the Connection class.
GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
if ($at = strpos($db,'://')) {
if (PHP_VERSION < 5) $dsna = @parse_url($db);
$fakedsn = 'fake'. substr($db,$at);
$dsna['scheme'] = substr($db,0,$at);
$sch = explode('_',$dsna['scheme']);
$dsna['host'] = isset ($dsna['host']) ? rawurldecode($dsna['host']) : '';
// special handling of oracle, which might not have host
if (!$dsna) return $false;
$dsna['host'] = isset ($dsna['host']) ? rawurldecode($dsna['host']) : '';
$dsna['user'] = isset ($dsna['user']) ? rawurldecode($dsna['user']) : '';
$dsna['pass'] = isset ($dsna['pass']) ? rawurldecode($dsna['pass']) : '';
$dsna['path'] = isset ($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial /
if (isset ($dsna['query'])) {
$opt1 = explode('&',$dsna['query']);
foreach($opt1 as $k => $v) {
* phptype: Database backend used in PHP (mysql, odbc etc.)
* dbsyntax: Database used with regards to SQL syntax etc.
* protocol: Communication protocol to use (tcp, unix etc.)
* hostspec: Host specification (hostname[:port])
* database: Database to use on the DBMS server
* username: User name for login
* password: Password for login
if (!empty($ADODB_NEWCONNECTION)) {
$obj = $ADODB_NEWCONNECTION($db);
if (!isset ($ADODB_LASTDB)) $ADODB_LASTDB = '';
if (empty($db)) $db = $ADODB_LASTDB;
if (isset ($origdsn)) $db = $origdsn;
$errorfn('ADONewConnection', 'ADONewConnection', - 998,
"could not load the database driver for '$db'",
ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
# constructor should not fail
if ($errorfn) $obj->raiseErrorFn = $errorfn;
if (isset ($dsna['port'])) $obj->port = $dsna['port'];
foreach($opt as $k => $v) {
$nconnect = true; $persist = true; break;
case 'persistent': $persist = $v; break;
case 'debug': $obj->debug = (integer) $v; break;
case 'role': $obj->role = $v; break;
case 'dialect': $obj->dialect = (integer) $v; break;
case 'charset': $obj->charset = $v; $obj->charSet= $v; break;
case 'buffers': $obj->buffers = $v; break;
case 'fetchmode': $obj->SetFetchMode($v); break;
case 'charpage': $obj->charPage = $v; break;
case 'clientflags': $obj->clientFlags = $v; break;
case 'port': $obj->port = $v; break;
case 'socket': $obj->socket = $v; break;
case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break;
$ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
else if (empty($nconnect))
$ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
$ok = $obj->NConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
// $perf == true means called by NewPerfMonitor(), otherwise for data dictionary
case 'odbtp': if (strncmp('odbtp_',$drivername,6)== 0) return substr($drivername,6);
case 'odbc' : if (strncmp('odbc_',$drivername,5)== 0) return substr($drivername,5);
case 'ado' : if (strncmp('ado_',$drivername,4)== 0) return substr($drivername,4);
$drivername = 'postgres';
case 'firebird15': $drivername = 'firebird'; break;
case 'oracle': $drivername = 'oci8'; break;
case 'access': if ($perf) $drivername = ''; break;
if (!$drivername || $drivername == 'generic') return $false;
include_once(ADODB_DIR. '/adodb-perf.inc.php');
@include_once(ADODB_DIR. "/perf/perf-$drivername.inc.php");
$class = "Perf_$drivername";
$perf = new $class($conn);
include_once(ADODB_DIR. '/adodb-lib.inc.php');
include_once(ADODB_DIR. '/adodb-datadict.inc.php');
$path = ADODB_DIR. "/datadict/datadict-$drivername.inc.php";
$class = "ADODB2_$drivername";
$dict->quote = $conn->nameQuote;
if (!empty($conn->_connectionID))
$dict->serverInfo = $conn->ServerInfo();
Perform a print_r, with pre tags for better formatting.
function adodb_pr($var,$as_string= false)
if (isset ($_SERVER['HTTP_USER_AGENT'])) {
echo " <pre>\n";print_r($var);echo "</pre>\n";
Perform a stack-crawl and pretty print it.
@param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
@param levels Number of levels to display
global $ADODB_INCLUDED_LIB;
if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR. '/adodb-lib.inc.php');
|