Fix a possible race condition in the PaintWeb DML code.
[moodle/mihaisucan.git] / lib / adodb / adodb.inc.php
blob23fe48ed3ebc35ad6ea74e4c87172d7c9770b3ca
1 <?php
2 /*
3 * Set tabs to 4 for best viewing.
4 *
5 * Latest version is available at http://adodb.sourceforge.net/
6 *
7 * This is the main include file for ADOdb.
8 * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
10 * The ADOdb files are formatted so that doxygen can be used to generate documentation.
11 * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
14 /**
15 \mainpage
17 @version V4.98 13 Feb 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved.
19 Released under both BSD license and Lesser GPL library license. You can choose which license
20 you prefer.
22 PHP's database access functions are not standardised. This creates a need for a database
23 class library to hide the differences between the different database API's (encapsulate
24 the differences) so we can easily switch databases.
26 We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
27 Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
28 ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
29 other databases via ODBC.
31 Latest Download at http://adodb.sourceforge.net/
35 if (!defined('_ADODB_LAYER')) {
36 define('_ADODB_LAYER',1);
38 //==============================================================================================
39 // CONSTANT DEFINITIONS
40 //==============================================================================================
43 /**
44 * Set ADODB_DIR to the directory where this file resides...
45 * This constant was formerly called $ADODB_RootPath
47 if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
49 //==============================================================================================
50 // GLOBAL VARIABLES
51 //==============================================================================================
53 GLOBAL
54 $ADODB_vers, // database version
55 $ADODB_COUNTRECS, // count number of records returned - slows down query
56 $ADODB_CACHE_DIR, // directory to cache recordsets
57 $ADODB_EXTENSION, // ADODB extension installed
58 $ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
59 $ADODB_FETCH_MODE, // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
60 $ADODB_QUOTE_FIELDNAMES; // Allows you to force quotes (backticks) around field names in queries generated by getinsertsql and getupdatesql.
62 //==============================================================================================
63 // GLOBAL SETUP
64 //==============================================================================================
66 $ADODB_EXTENSION = defined('ADODB_EXTENSION');
68 //********************************************************//
70 Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3).
71 Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi
73 0 = ignore empty fields. All empty fields in array are ignored.
74 1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
75 2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
76 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.
78 define('ADODB_FORCE_IGNORE',0);
79 define('ADODB_FORCE_NULL',1);
80 define('ADODB_FORCE_EMPTY',2);
81 define('ADODB_FORCE_VALUE',3);
82 //********************************************************//
85 if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
87 define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
89 // allow [ ] @ ` " and . in table names
90 define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
92 // prefetching used by oracle
93 if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
97 Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
98 This currently works only with mssql, odbc, oci8po and ibase derived drivers.
100 0 = assoc lowercase field names. $rs->fields['orderid']
101 1 = assoc uppercase field names. $rs->fields['ORDERID']
102 2 = use native-case field names. $rs->fields['OrderID']
105 define('ADODB_FETCH_DEFAULT',0);
106 define('ADODB_FETCH_NUM',1);
107 define('ADODB_FETCH_ASSOC',2);
108 define('ADODB_FETCH_BOTH',3);
110 if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
112 // PHP's version scheme makes converting to numbers difficult - workaround
113 $_adodb_ver = (float) PHP_VERSION;
114 if ($_adodb_ver >= 5.2) {
115 define('ADODB_PHPVER',0x5200);
116 } else if ($_adodb_ver >= 5.0) {
117 define('ADODB_PHPVER',0x5000);
118 } else if ($_adodb_ver > 4.299999) { # 4.3
119 define('ADODB_PHPVER',0x4300);
120 } else if ($_adodb_ver > 4.199999) { # 4.2
121 define('ADODB_PHPVER',0x4200);
122 } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
123 define('ADODB_PHPVER',0x4050);
124 } else {
125 define('ADODB_PHPVER',0x4000);
129 //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
133 Accepts $src and $dest arrays, replacing string $data
135 function ADODB_str_replace($src, $dest, $data)
137 if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
139 $s = reset($src);
140 $d = reset($dest);
141 while ($s !== false) {
142 $data = str_replace($s,$d,$data);
143 $s = next($src);
144 $d = next($dest);
146 return $data;
149 function ADODB_Setup()
151 GLOBAL
152 $ADODB_vers, // database version
153 $ADODB_COUNTRECS, // count number of records returned - slows down query
154 $ADODB_CACHE_DIR, // directory to cache recordsets
155 $ADODB_FETCH_MODE,
156 $ADODB_FORCE_TYPE,
157 $ADODB_QUOTE_FIELDNAMES;
159 $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
160 $ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
163 if (!isset($ADODB_CACHE_DIR)) {
164 $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
165 } else {
166 // do not accept url based paths, eg. http:/ or ftp:/
167 if (strpos($ADODB_CACHE_DIR,'://') !== false)
168 die("Illegal path http:// or ftp://");
172 // Initialize random number generator for randomizing cache flushes
173 // -- note Since PHP 4.2.0, the seed becomes optional and defaults to a random value if omitted.
174 srand(((double)microtime())*1000000);
177 * ADODB version as a string.
179 $ADODB_vers = 'V4.98 13 Feb 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
182 * Determines whether recordset->RecordCount() is used.
183 * Set to false for highest performance -- RecordCount() will always return -1 then
184 * for databases that provide "virtual" recordcounts...
186 if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
190 //==============================================================================================
191 // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
192 //==============================================================================================
194 ADODB_Setup();
196 //==============================================================================================
197 // CLASS ADOFieldObject
198 //==============================================================================================
200 * Helper class for FetchFields -- holds info on a column
202 class ADOFieldObject {
203 var $name = '';
204 var $max_length=0;
205 var $type="";
207 // additional fields by dannym... (danny_milo@yahoo.com)
208 var $not_null = false;
209 // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
210 // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
212 var $has_default = false; // this one I have done only in mysql and postgres for now ...
213 // others to come (dannym)
214 var $default_value; // default, if any, and supported. Check has_default first.
220 function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
222 //print "Errorno ($fn errno=$errno m=$errmsg) ";
223 $thisConnection->_transOK = false;
224 if ($thisConnection->_oldRaiseFn) {
225 $fn = $thisConnection->_oldRaiseFn;
226 $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
230 //==============================================================================================
231 // CLASS ADOConnection
232 //==============================================================================================
235 * Connection object. For connecting to databases, and executing queries.
237 class ADOConnection {
239 // PUBLIC VARS
241 var $dataProvider = 'native';
242 var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
243 var $database = ''; /// Name of database to be used.
244 var $host = ''; /// The hostname of the database server
245 var $user = ''; /// The username which is used to connect to the database server.
246 var $password = ''; /// Password for the username. For security, we no longer store it.
247 var $debug = false; /// if set to true will output sql statements
248 var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
249 var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
250 var $substr = 'substr'; /// substring operator
251 var $length = 'length'; /// string length ofperator
252 var $random = 'rand()'; /// random function
253 var $upperCase = 'upper'; /// uppercase function
254 var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
255 var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
256 var $true = '1'; /// string that represents TRUE for a database
257 var $false = '0'; /// string that represents FALSE for a database
258 var $replaceQuote = "\\'"; /// string to use to replace quotes
259 var $nameQuote = '"'; /// string to use to quote identifiers and names
260 var $charSet=false; /// character set to use - only for interbase, postgres and oci8
261 var $metaDatabasesSQL = '';
262 var $metaTablesSQL = '';
263 var $uniqueOrderBy = false; /// All order by columns have to be unique
264 var $emptyDate = '&nbsp;';
265 var $emptyTimeStamp = '&nbsp;';
266 var $lastInsID = false;
267 //--
268 var $hasInsertID = false; /// supports autoincrement ID?
269 var $hasAffectedRows = false; /// supports affected rows for update/delete?
270 var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
271 var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
272 var $readOnly = false; /// this is a readonly database - used by phpLens
273 var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
274 var $hasGenID = false; /// can generate sequences using GenID();
275 var $hasTransactions = true; /// has transactions
276 //--
277 var $genID = 0; /// sequence id used by GenID();
278 var $raiseErrorFn = false; /// error function to call
279 var $isoDates = false; /// accepts dates in ISO format
280 var $cacheSecs = 3600; /// cache for 1 hour
282 // memcache
283 var $memCache = false; /// should we use memCache instead of caching in files
284 var $memCacheHost; /// memCache host
285 var $memCachePort = 11211; /// memCache port
286 var $memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
288 var $sysDate = false; /// name of function that returns the current date
289 var $sysTimeStamp = false; /// name of function that returns the current timestamp
290 var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
292 var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
293 var $numCacheHits = 0;
294 var $numCacheMisses = 0;
295 var $pageExecuteCountRows = true;
296 var $uniqueSort = false; /// indicates that all fields in order by must be unique
297 var $leftOuter = false; /// operator to use for left outer join in WHERE clause
298 var $rightOuter = false; /// operator to use for right outer join in WHERE clause
299 var $ansiOuter = false; /// whether ansi outer join syntax supported
300 var $autoRollback = false; // autoRollback on PConnect().
301 var $poorAffectedRows = false; // affectedRows not working or unreliable
303 var $fnExecute = false;
304 var $fnCacheExecute = false;
305 var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
306 var $rsPrefix = "ADORecordSet_";
308 var $autoCommit = true; /// do not modify this yourself - actually private
309 var $transOff = 0; /// temporarily disable transactions
310 var $transCnt = 0; /// count of nested transactions
312 var $fetchMode=false;
314 var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null
316 // PRIVATE VARS
318 var $_oldRaiseFn = false;
319 var $_transOK = null;
320 var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
321 var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
322 /// then returned by the errorMsg() function
323 var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
324 var $_queryID = false; /// This variable keeps the last created result link identifier
326 var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
327 var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
328 var $_evalAll = false;
329 var $_affected = false;
330 var $_logsql = false;
331 var $_transmode = ''; // transaction mode
336 * Constructor
338 function ADOConnection()
340 die('Virtual Class -- cannot instantiate');
343 function Version()
345 global $ADODB_vers;
347 return (float) substr($ADODB_vers,1);
351 Get server version info...
353 @returns An array with 2 elements: $arr['string'] is the description string,
354 and $arr[version] is the version (also a string).
356 function ServerInfo()
358 return array('description' => '', 'version' => '');
361 function IsConnected()
363 return !empty($this->_connectionID);
366 function _findvers($str)
368 if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
369 else return '';
373 * All error messages go through this bottleneck function.
374 * You can define your own handler by defining the function name in ADODB_OUTP.
376 function outp($msg,$newline=true)
378 global $ADODB_FLUSH,$ADODB_OUTP;
380 if (defined('ADODB_OUTP')) {
381 $fn = ADODB_OUTP;
382 $fn($msg,$newline);
383 return;
384 } else if (isset($ADODB_OUTP)) {
385 $fn = $ADODB_OUTP;
386 $fn($msg,$newline);
387 return;
390 if ($newline) $msg .= "<br>\n";
392 if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
393 else echo strip_tags($msg);
396 if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
400 function Time()
402 $rs =& $this->_Execute("select $this->sysTimeStamp");
403 if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
405 return false;
409 * Connect to database
411 * @param [argHostname] Host to connect to
412 * @param [argUsername] Userid to login
413 * @param [argPassword] Associated password
414 * @param [argDatabaseName] database
415 * @param [forceNew] force new connection
417 * @return true or false
419 function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
421 if ($argHostname != "") $this->host = $argHostname;
422 if ($argUsername != "") $this->user = $argUsername;
423 if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
424 if ($argDatabaseName != "") $this->database = $argDatabaseName;
426 $this->_isPersistentConnection = false;
427 if ($forceNew) {
428 if ($rez=$this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
429 } else {
430 if ($rez=$this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
432 if (isset($rez)) {
433 $err = $this->ErrorMsg();
434 if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
435 $ret = false;
436 } else {
437 $err = "Missing extension for ".$this->dataProvider;
438 $ret = 0;
440 if ($fn = $this->raiseErrorFn)
441 $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
444 $this->_connectionID = false;
445 if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
446 return $ret;
449 function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
451 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
456 * Always force a new connection to database - currently only works with oracle
458 * @param [argHostname] Host to connect to
459 * @param [argUsername] Userid to login
460 * @param [argPassword] Associated password
461 * @param [argDatabaseName] database
463 * @return true or false
465 function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
467 return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
471 * Establish persistent connect to database
473 * @param [argHostname] Host to connect to
474 * @param [argUsername] Userid to login
475 * @param [argPassword] Associated password
476 * @param [argDatabaseName] database
478 * @return return true or false
480 function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
482 if (defined('ADODB_NEVER_PERSIST'))
483 return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
485 if ($argHostname != "") $this->host = $argHostname;
486 if ($argUsername != "") $this->user = $argUsername;
487 if ($argPassword != "") $this->password = $argPassword;
488 if ($argDatabaseName != "") $this->database = $argDatabaseName;
490 $this->_isPersistentConnection = true;
491 if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
492 if (isset($rez)) {
493 $err = $this->ErrorMsg();
494 if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
495 $ret = false;
496 } else {
497 $err = "Missing extension for ".$this->dataProvider;
498 $ret = 0;
500 if ($fn = $this->raiseErrorFn) {
501 $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
504 $this->_connectionID = false;
505 if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
506 return $ret;
509 // Format date column in sql string given an input format that understands Y M D
510 function SQLDate($fmt, $col=false)
512 if (!$col) $col = $this->sysDate;
513 return $col; // child class implement
517 * Should prepare the sql statement and return the stmt resource.
518 * For databases that do not support this, we return the $sql. To ensure
519 * compatibility with databases that do not support prepare:
521 * $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
522 * $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
523 * $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
525 * @param sql SQL to send to database
527 * @return return FALSE, or the prepared statement, or the original sql if
528 * if the database does not support prepare.
531 function Prepare($sql)
533 return $sql;
537 * Some databases, eg. mssql require a different function for preparing
538 * stored procedures. So we cannot use Prepare().
540 * Should prepare the stored procedure and return the stmt resource.
541 * For databases that do not support this, we return the $sql. To ensure
542 * compatibility with databases that do not support prepare:
544 * @param sql SQL to send to database
546 * @return return FALSE, or the prepared statement, or the original sql if
547 * if the database does not support prepare.
550 function PrepareSP($sql,$param=true)
552 return $this->Prepare($sql,$param);
556 * PEAR DB Compat
558 function Quote($s)
560 return $this->qstr($s,false);
564 Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
566 function QMagic($s)
568 return $this->qstr($s,get_magic_quotes_gpc());
571 function q(&$s)
573 #if (!empty($this->qNull)) if ($s == 'null') return $s;
574 $s = $this->qstr($s,false);
578 * PEAR DB Compat - do not use internally.
580 function ErrorNative()
582 return $this->ErrorNo();
587 * PEAR DB Compat - do not use internally.
589 function nextId($seq_name)
591 return $this->GenID($seq_name);
595 * Lock a row, will escalate and lock the table if row locking not supported
596 * will normally free the lock at the end of the transaction
598 * @param $table name of table to lock
599 * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
601 function RowLock($table,$where)
603 return false;
606 function CommitLock($table)
608 return $this->CommitTrans();
611 function RollbackLock($table)
613 return $this->RollbackTrans();
617 * PEAR DB Compat - do not use internally.
619 * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
620 * for easy porting :-)
622 * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
623 * @returns The previous fetch mode
625 function SetFetchMode($mode)
627 $old = $this->fetchMode;
628 $this->fetchMode = $mode;
630 if ($old === false) {
631 global $ADODB_FETCH_MODE;
632 return $ADODB_FETCH_MODE;
634 return $old;
639 * PEAR DB Compat - do not use internally.
641 function &Query($sql, $inputarr=false)
643 $rs = &$this->Execute($sql, $inputarr);
644 if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
645 return $rs;
650 * PEAR DB Compat - do not use internally
652 function &LimitQuery($sql, $offset, $count, $params=false)
654 $rs = &$this->SelectLimit($sql, $count, $offset, $params);
655 if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
656 return $rs;
661 * PEAR DB Compat - do not use internally
663 function Disconnect()
665 return $this->Close();
669 Returns placeholder for parameter, eg.
670 $DB->Param('a')
672 will return ':a' for Oracle, and '?' for most other databases...
674 For databases that require positioned params, eg $1, $2, $3 for postgresql,
675 pass in Param(false) before setting the first parameter.
677 function Param($name,$type='C')
679 return '?';
683 InParameter and OutParameter are self-documenting versions of Parameter().
685 function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
687 return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
692 function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
694 return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
700 Usage in oracle
701 $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
702 $db->Parameter($stmt,$id,'myid');
703 $db->Parameter($stmt,$group,'group',64);
704 $db->Execute();
706 @param $stmt Statement returned by Prepare() or PrepareSP().
707 @param $var PHP variable to bind to
708 @param $name Name of stored procedure variable name to bind to.
709 @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
710 @param [$maxLen] Holds an maximum length of the variable.
711 @param [$type] The data type of $var. Legal values depend on driver.
714 function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
716 return false;
720 function IgnoreErrors($saveErrs=false)
722 if (!$saveErrs) {
723 $saveErrs = array($this->raiseErrorFn,$this->_transOK);
724 $this->raiseErrorFn = false;
725 return $saveErrs;
726 } else {
727 $this->raiseErrorFn = $saveErrs[0];
728 $this->_transOK = $saveErrs[1];
733 Improved method of initiating a transaction. Used together with CompleteTrans().
734 Advantages include:
736 a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
737 Only the outermost block is treated as a transaction.<br>
738 b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
739 c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
740 are disabled, making it backward compatible.
742 function StartTrans($errfn = 'ADODB_TransMonitor')
744 if ($this->transOff > 0) {
745 $this->transOff += 1;
746 return;
749 $this->_oldRaiseFn = $this->raiseErrorFn;
750 $this->raiseErrorFn = $errfn;
751 $this->_transOK = true;
753 if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
754 $this->BeginTrans();
755 $this->transOff = 1;
760 Used together with StartTrans() to end a transaction. Monitors connection
761 for sql errors, and will commit or rollback as appropriate.
763 @autoComplete if true, monitor sql errors and commit and rollback as appropriate,
764 and if set to false force rollback even if no SQL error detected.
765 @returns true on commit, false on rollback.
767 function CompleteTrans($autoComplete = true)
769 if ($this->transOff > 1) {
770 $this->transOff -= 1;
771 return true;
773 $this->raiseErrorFn = $this->_oldRaiseFn;
775 $this->transOff = 0;
776 if ($this->_transOK && $autoComplete) {
777 if (!$this->CommitTrans()) {
778 $this->_transOK = false;
779 if ($this->debug) ADOConnection::outp("Smart Commit failed");
780 } else
781 if ($this->debug) ADOConnection::outp("Smart Commit occurred");
782 } else {
783 $this->_transOK = false;
784 $this->RollbackTrans();
785 if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
788 return $this->_transOK;
792 At the end of a StartTrans/CompleteTrans block, perform a rollback.
794 function FailTrans()
796 if ($this->debug)
797 if ($this->transOff == 0) {
798 ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
799 } else {
800 ADOConnection::outp("FailTrans was called");
801 adodb_backtrace();
803 $this->_transOK = false;
807 Check if transaction has failed, only for Smart Transactions.
809 function HasFailedTrans()
811 if ($this->transOff > 0) return $this->_transOK == false;
812 return false;
816 * Execute SQL
818 * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
819 * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
820 * @return RecordSet or false
822 function &Execute($sql,$inputarr=false)
824 if ($this->fnExecute) {
825 $fn = $this->fnExecute;
826 $ret =& $fn($this,$sql,$inputarr);
827 if (isset($ret)) return $ret;
829 if ($inputarr) {
830 if (!is_array($inputarr)) $inputarr = array($inputarr);
832 $element0 = reset($inputarr);
833 # is_object check because oci8 descriptors can be passed in
834 $array_2d = is_array($element0) && !is_object(reset($element0));
835 //remove extra memory copy of input -mikefedyk
836 unset($element0);
838 if (!is_array($sql) && !$this->_bindInputArray) {
839 $sqlarr = explode('?',$sql);
841 if (!$array_2d) $inputarr = array($inputarr);
842 foreach($inputarr as $arr) {
843 $sql = ''; $i = 0;
844 //Use each() instead of foreach to reduce memory usage -mikefedyk
845 while(list(, $v) = each($arr)) {
846 $sql .= $sqlarr[$i];
847 // from Ron Baldwin <ron.baldwin#sourceprose.com>
848 // Only quote string types
849 $typ = gettype($v);
850 if ($typ == 'string')
851 //New memory copy of input created here -mikefedyk
852 $sql .= $this->qstr($v);
853 else if ($typ == 'double')
854 $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
855 else if ($typ == 'boolean')
856 $sql .= $v ? $this->true : $this->false;
857 else if ($typ == 'object') {
858 if (method_exists($v, '__toString')) $sql .= $this->qstr($v->__toString());
859 else $sql .= $this->qstr((string) $v);
860 } else if ($v === null)
861 $sql .= 'NULL';
862 else
863 $sql .= $v;
864 $i += 1;
866 if (isset($sqlarr[$i])) {
867 $sql .= $sqlarr[$i];
868 if ($i+1 != sizeof($sqlarr)) ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
869 } else if ($i != sizeof($sqlarr))
870 ADOConnection::outp( "Input array does not match ?: ".htmlspecialchars($sql));
872 $ret =& $this->_Execute($sql);
873 if (!$ret) return $ret;
875 } else {
876 if ($array_2d) {
877 if (is_string($sql))
878 $stmt = $this->Prepare($sql);
879 else
880 $stmt = $sql;
882 foreach($inputarr as $arr) {
883 $ret =& $this->_Execute($stmt,$arr);
884 if (!$ret) return $ret;
886 } else {
887 $ret =& $this->_Execute($sql,$inputarr);
890 } else {
891 $ret =& $this->_Execute($sql,false);
894 return $ret;
898 function &_Execute($sql,$inputarr=false)
900 if ($this->debug) {
901 global $ADODB_INCLUDED_LIB;
902 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
903 $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
904 } else {
905 $this->_queryID = @$this->_query($sql,$inputarr);
908 /************************
909 // OK, query executed
910 *************************/
912 if ($this->_queryID === false) { // error handling if query fails
913 if ($this->debug == 99) adodb_backtrace(true,5);
914 $fn = $this->raiseErrorFn;
915 if ($fn) {
916 $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
918 $false = false;
919 return $false;
922 if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
923 $rsclass = $this->rsPrefix.'empty';
924 $rs = (class_exists($rsclass)) ? new $rsclass(): new ADORecordSet_empty();
926 return $rs;
929 // return real recordset from select statement
930 $rsclass = $this->rsPrefix.$this->databaseType;
931 $rs = new $rsclass($this->_queryID,$this->fetchMode);
932 $rs->connection = &$this; // Pablo suggestion
933 $rs->Init();
934 if (is_array($sql)) $rs->sql = $sql[0];
935 else $rs->sql = $sql;
936 if ($rs->_numOfRows <= 0) {
937 global $ADODB_COUNTRECS;
938 if ($ADODB_COUNTRECS) {
939 if (!$rs->EOF) {
940 $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
941 $rs->_queryID = $this->_queryID;
942 } else
943 $rs->_numOfRows = 0;
946 return $rs;
949 function CreateSequence($seqname='adodbseq',$startID=1)
951 if (empty($this->_genSeqSQL)) return false;
952 return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
955 function DropSequence($seqname='adodbseq')
957 if (empty($this->_dropSeqSQL)) return false;
958 return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
962 * Generates a sequence id and stores it in $this->genID;
963 * GenID is only available if $this->hasGenID = true;
965 * @param seqname name of sequence to use
966 * @param startID if sequence does not exist, start at this ID
967 * @return 0 if not supported, otherwise a sequence id
969 function GenID($seqname='adodbseq',$startID=1)
971 if (!$this->hasGenID) {
972 return 0; // formerly returns false pre 1.60
975 $getnext = sprintf($this->_genIDSQL,$seqname);
977 $holdtransOK = $this->_transOK;
979 $save_handler = $this->raiseErrorFn;
980 $this->raiseErrorFn = '';
981 @($rs = $this->Execute($getnext));
982 $this->raiseErrorFn = $save_handler;
984 if (!$rs) {
985 $this->_transOK = $holdtransOK; //if the status was ok before reset
986 $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
987 $rs = $this->Execute($getnext);
989 if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
990 else $this->genID = 0; // false
992 if ($rs) $rs->Close();
994 return $this->genID;
998 * @param $table string name of the table, not needed by all databases (eg. mysql), default ''
999 * @param $column string name of the column, not needed by all databases (eg. mysql), default ''
1000 * @return the last inserted ID. Not all databases support this.
1002 function Insert_ID($table='',$column='')
1004 if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
1005 if ($this->hasInsertID) return $this->_insertid($table,$column);
1006 if ($this->debug) {
1007 ADOConnection::outp( '<p>Insert_ID error</p>');
1008 adodb_backtrace();
1010 return false;
1015 * Portable Insert ID. Pablo Roca <pabloroca#mvps.org>
1017 * @return the last inserted ID. All databases support this. But aware possible
1018 * problems in multiuser environments. Heavy test this before deploying.
1020 function PO_Insert_ID($table="", $id="")
1022 if ($this->hasInsertID){
1023 return $this->Insert_ID($table,$id);
1024 } else {
1025 return $this->GetOne("SELECT MAX($id) FROM $table");
1030 * @return # rows affected by UPDATE/DELETE
1032 function Affected_Rows()
1034 if ($this->hasAffectedRows) {
1035 if ($this->fnExecute === 'adodb_log_sql') {
1036 if ($this->_logsql && $this->_affected !== false) return $this->_affected;
1038 $val = $this->_affectedrows();
1039 return ($val < 0) ? false : $val;
1042 if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
1043 return false;
1048 * @return the last error message
1050 function ErrorMsg()
1052 if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
1053 else return '';
1058 * @return the last error number. Normally 0 means no error.
1060 function ErrorNo()
1062 return ($this->_errorMsg) ? -1 : 0;
1065 function MetaError($err=false)
1067 include_once(ADODB_DIR."/adodb-error.inc.php");
1068 if ($err === false) $err = $this->ErrorNo();
1069 return adodb_error($this->dataProvider,$this->databaseType,$err);
1072 function MetaErrorMsg($errno)
1074 include_once(ADODB_DIR."/adodb-error.inc.php");
1075 return adodb_errormsg($errno);
1079 * @returns an array with the primary key columns in it.
1081 function MetaPrimaryKeys($table, $owner=false)
1083 // owner not used in base class - see oci8
1084 $p = array();
1085 $objs =& $this->MetaColumns($table);
1086 if ($objs) {
1087 foreach($objs as $v) {
1088 if (!empty($v->primary_key))
1089 $p[] = $v->name;
1092 if (sizeof($p)) return $p;
1093 if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
1094 return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
1095 return false;
1099 * @returns assoc array where keys are tables, and values are foreign keys
1101 function MetaForeignKeys($table, $owner=false, $upper=false)
1103 return false;
1106 * Choose a database to connect to. Many databases do not support this.
1108 * @param dbName is the name of the database to select
1109 * @return true or false
1111 function SelectDB($dbName)
1112 {return false;}
1116 * Will select, getting rows from $offset (1-based), for $nrows.
1117 * This simulates the MySQL "select * from table limit $offset,$nrows" , and
1118 * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
1119 * MySQL and PostgreSQL parameter ordering is the opposite of the other.
1120 * eg.
1121 * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
1122 * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
1124 * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
1125 * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
1127 * @param sql
1128 * @param [offset] is the row to start calculations from (1-based)
1129 * @param [nrows] is the number of rows to get
1130 * @param [inputarr] array of bind variables
1131 * @param [secs2cache] is a private parameter only used by jlim
1132 * @return the recordset ($rs->databaseType == 'array')
1134 function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
1136 if ($this->hasTop && $nrows > 0) {
1137 // suggested by Reinhard Balling. Access requires top after distinct
1138 // Informix requires first before distinct - F Riosa
1139 $ismssql = (strpos($this->databaseType,'mssql') !== false);
1140 if ($ismssql) $isaccess = false;
1141 else $isaccess = (strpos($this->databaseType,'access') !== false);
1143 if ($offset <= 0) {
1145 // access includes ties in result
1146 if ($isaccess) {
1147 $sql = preg_replace(
1148 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
1150 if ($secs2cache != 0) {
1151 $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
1152 } else {
1153 $ret =& $this->Execute($sql,$inputarr);
1155 return $ret; // PHP5 fix
1156 } else if ($ismssql){
1157 $sql = preg_replace(
1158 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
1159 } else {
1160 $sql = preg_replace(
1161 '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
1163 } else {
1164 $nn = $nrows + $offset;
1165 if ($isaccess || $ismssql) {
1166 $sql = preg_replace(
1167 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
1168 } else {
1169 $sql = preg_replace(
1170 '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
1175 // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
1176 // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
1177 global $ADODB_COUNTRECS;
1179 $savec = $ADODB_COUNTRECS;
1180 $ADODB_COUNTRECS = false;
1182 if ($offset>0){
1183 if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
1184 else $rs = &$this->Execute($sql,$inputarr);
1185 } else {
1186 if ($secs2cache != 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
1187 else $rs = &$this->Execute($sql,$inputarr);
1189 $ADODB_COUNTRECS = $savec;
1190 if ($rs && !$rs->EOF) {
1191 $rs =& $this->_rs2rs($rs,$nrows,$offset);
1193 //print_r($rs);
1194 return $rs;
1198 * Create serializable recordset. Breaks rs link to connection.
1200 * @param rs the recordset to serialize
1202 function &SerializableRS(&$rs)
1204 $rs2 =& $this->_rs2rs($rs);
1205 $ignore = false;
1206 $rs2->connection =& $ignore;
1208 return $rs2;
1212 * Convert database recordset to an array recordset
1213 * input recordset's cursor should be at beginning, and
1214 * old $rs will be closed.
1216 * @param rs the recordset to copy
1217 * @param [nrows] number of rows to retrieve (optional)
1218 * @param [offset] offset by number of rows (optional)
1219 * @return the new recordset
1221 function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
1223 if (! $rs) {
1224 $false = false;
1225 return $false;
1227 $dbtype = $rs->databaseType;
1228 if (!$dbtype) {
1229 $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
1230 return $rs;
1232 if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
1233 $rs->MoveFirst();
1234 $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
1235 return $rs;
1237 $flds = array();
1238 for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
1239 $flds[] = $rs->FetchField($i);
1242 $arr =& $rs->GetArrayLimit($nrows,$offset);
1243 //print_r($arr);
1244 if ($close) $rs->Close();
1246 $arrayClass = $this->arrayClass;
1248 $rs2 = new $arrayClass();
1249 $rs2->connection = &$this;
1250 $rs2->sql = $rs->sql;
1251 $rs2->dataProvider = $this->dataProvider;
1252 $rs2->InitArrayFields($arr,$flds);
1253 $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
1254 return $rs2;
1258 * Return all rows. Compat with PEAR DB
1260 function &GetAll($sql, $inputarr=false)
1262 $arr =& $this->GetArray($sql,$inputarr);
1263 return $arr;
1266 function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
1268 $rs =& $this->Execute($sql, $inputarr);
1269 if (!$rs) {
1270 $false = false;
1271 return $false;
1273 $arr =& $rs->GetAssoc($force_array,$first2cols);
1274 return $arr;
1277 function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
1279 if (!is_numeric($secs2cache)) {
1280 $first2cols = $force_array;
1281 $force_array = $inputarr;
1283 $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);
1284 if (!$rs) {
1285 $false = false;
1286 return $false;
1288 $arr =& $rs->GetAssoc($force_array,$first2cols);
1289 return $arr;
1293 * Return first element of first row of sql statement. Recordset is disposed
1294 * for you.
1296 * @param sql SQL statement
1297 * @param [inputarr] input bind array
1299 function GetOne($sql,$inputarr=false)
1301 global $ADODB_COUNTRECS;
1302 $crecs = $ADODB_COUNTRECS;
1303 $ADODB_COUNTRECS = false;
1305 $ret = false;
1306 $rs = &$this->Execute($sql,$inputarr);
1307 if ($rs) {
1308 if ($rs->EOF) $ret = null;
1309 else $ret = reset($rs->fields);
1311 $rs->Close();
1313 $ADODB_COUNTRECS = $crecs;
1314 return $ret;
1317 function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
1319 $ret = false;
1320 $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
1321 if ($rs) {
1322 if ($rs->EOF) $ret = null;
1323 else $ret = reset($rs->fields);
1324 $rs->Close();
1327 return $ret;
1330 function GetCol($sql, $inputarr = false, $trim = false)
1333 $rs = &$this->Execute($sql, $inputarr);
1334 if ($rs) {
1335 $rv = array();
1336 if ($trim) {
1337 while (!$rs->EOF) {
1338 $rv[] = trim(reset($rs->fields));
1339 $rs->MoveNext();
1341 } else {
1342 while (!$rs->EOF) {
1343 $rv[] = reset($rs->fields);
1344 $rs->MoveNext();
1347 $rs->Close();
1348 } else
1349 $rv = false;
1350 return $rv;
1353 function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
1355 $rs = &$this->CacheExecute($secs, $sql, $inputarr);
1356 if ($rs) {
1357 $rv = array();
1358 if ($trim) {
1359 while (!$rs->EOF) {
1360 $rv[] = trim(reset($rs->fields));
1361 $rs->MoveNext();
1363 } else {
1364 while (!$rs->EOF) {
1365 $rv[] = reset($rs->fields);
1366 $rs->MoveNext();
1369 $rs->Close();
1370 } else
1371 $rv = false;
1373 return $rv;
1376 function &Transpose(&$rs,$addfieldnames=true)
1378 $rs2 =& $this->_rs2rs($rs);
1379 $false = false;
1380 if (!$rs2) return $false;
1382 $rs2->_transpose($addfieldnames);
1383 return $rs2;
1387 Calculate the offset of a date for a particular database and generate
1388 appropriate SQL. Useful for calculating future/past dates and storing
1389 in a database.
1391 If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
1393 function OffsetDate($dayFraction,$date=false)
1395 if (!$date) $date = $this->sysDate;
1396 return '('.$date.'+'.$dayFraction.')';
1402 * @param sql SQL statement
1403 * @param [inputarr] input bind array
1405 function &GetArray($sql,$inputarr=false)
1407 global $ADODB_COUNTRECS;
1409 $savec = $ADODB_COUNTRECS;
1410 $ADODB_COUNTRECS = false;
1411 $rs =& $this->Execute($sql,$inputarr);
1412 $ADODB_COUNTRECS = $savec;
1413 if (!$rs)
1414 if (defined('ADODB_PEAR')) {
1415 $cls = ADODB_PEAR_Error();
1416 return $cls;
1417 } else {
1418 $false = false;
1419 return $false;
1421 $arr =& $rs->GetArray();
1422 $rs->Close();
1423 return $arr;
1426 function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
1428 $arr =& $this->CacheGetArray($secs2cache,$sql,$inputarr);
1429 return $arr;
1432 function &CacheGetArray($secs2cache,$sql=false,$inputarr=false)
1434 global $ADODB_COUNTRECS;
1436 $savec = $ADODB_COUNTRECS;
1437 $ADODB_COUNTRECS = false;
1438 $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
1439 $ADODB_COUNTRECS = $savec;
1441 if (!$rs)
1442 if (defined('ADODB_PEAR')) {
1443 $cls = ADODB_PEAR_Error();
1444 return $cls;
1445 } else {
1446 $false = false;
1447 return $false;
1449 $arr =& $rs->GetArray();
1450 $rs->Close();
1451 return $arr;
1454 function GetRandRow($sql, $arr= false)
1456 $rezarr = $this->GetAll($sql, $arr);
1457 $sz = sizeof($rez);
1458 return $rezarr[abs(rand()) % $sz];
1462 * Return one row of sql statement. Recordset is disposed for you.
1464 * @param sql SQL statement
1465 * @param [inputarr] input bind array
1467 function &GetRow($sql,$inputarr=false)
1469 global $ADODB_COUNTRECS;
1470 $crecs = $ADODB_COUNTRECS;
1471 $ADODB_COUNTRECS = false;
1473 $rs =& $this->Execute($sql,$inputarr);
1475 $ADODB_COUNTRECS = $crecs;
1476 if ($rs) {
1477 if (!$rs->EOF) $arr = $rs->fields;
1478 else $arr = array();
1479 $rs->Close();
1480 return $arr;
1483 $false = false;
1484 return $false;
1487 function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
1489 $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
1490 if ($rs) {
1491 $arr = array();
1492 if (!$rs->EOF) $arr = $rs->fields;
1493 $rs->Close();
1494 return $arr;
1496 $false = false;
1497 return $false;
1501 * Insert or replace a single record. Note: this is not the same as MySQL's replace.
1502 * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
1503 * Also note that no table locking is done currently, so it is possible that the
1504 * record be inserted twice by two programs...
1506 * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
1508 * $table table name
1509 * $fieldArray associative array of data (you must quote strings yourself).
1510 * $keyCol the primary key field name or if compound key, array of field names
1511 * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
1512 * but does not work with dates nor SQL functions.
1513 * has_autoinc the primary key is an auto-inc field, so skip in insert.
1515 * Currently blob replace not supported
1517 * returns 0 = fail, 1 = update, 2 = insert
1520 function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
1522 global $ADODB_INCLUDED_LIB;
1523 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
1525 return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
1530 * Will select, getting rows from $offset (1-based), for $nrows.
1531 * This simulates the MySQL "select * from table limit $offset,$nrows" , and
1532 * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
1533 * MySQL and PostgreSQL parameter ordering is the opposite of the other.
1534 * eg.
1535 * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
1536 * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
1538 * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
1540 * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
1541 * @param sql
1542 * @param [offset] is the row to start calculations from (1-based)
1543 * @param [nrows] is the number of rows to get
1544 * @param [inputarr] array of bind variables
1545 * @return the recordset ($rs->databaseType == 'array')
1547 function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
1549 if (!is_numeric($secs2cache)) {
1550 if ($sql === false) $sql = -1;
1551 if ($offset == -1) $offset = false;
1552 // sql, nrows, offset,inputarr
1553 $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
1554 } else {
1555 if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
1556 $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
1558 return $rs;
1563 * Flush cached recordsets that match a particular $sql statement.
1564 * If $sql == false, then we purge all files in the cache.
1568 * Flush cached recordsets that match a particular $sql statement.
1569 * If $sql == false, then we purge all files in the cache.
1571 function CacheFlush($sql=false,$inputarr=false)
1573 global $ADODB_CACHE_DIR;
1575 if ($this->memCache) {
1576 global $ADODB_INCLUDED_MEMCACHE;
1578 $key = false;
1579 if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
1580 if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true);
1581 FlushMemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug);
1582 return;
1585 if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
1586 /*if (strncmp(PHP_OS,'WIN',3) === 0)
1587 $dir = str_replace('/', '\\', $ADODB_CACHE_DIR);
1588 else */
1589 $dir = $ADODB_CACHE_DIR;
1591 if ($this->debug) {
1592 ADOConnection::outp( "CacheFlush: $dir<br><pre>\n". $this->_dirFlush($dir)."</pre>");
1593 } else {
1594 $this->_dirFlush($dir);
1596 return;
1599 global $ADODB_INCLUDED_CSV;
1600 if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
1602 $f = $this->_gencachename($sql.serialize($inputarr),false);
1603 adodb_write_file($f,''); // is adodb_write_file needed?
1604 if (!@unlink($f)) {
1605 if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
1610 * Private function to erase all of the files and subdirectories in a directory.
1612 * Just specify the directory, and tell it if you want to delete the directory or just clear it out.
1613 * Note: $kill_top_level is used internally in the function to flush subdirectories.
1615 function _dirFlush($dir, $kill_top_level = false)
1617 if(!$dh = @opendir($dir)) return;
1619 while (($obj = readdir($dh))) {
1620 if($obj=='.' || $obj=='..') continue;
1621 $f = $dir.'/'.$obj;
1623 if (strpos($obj,'.cache')) @unlink($f);
1624 if (is_dir($f)) $this->_dirFlush($f, true);
1626 if ($kill_top_level === true) @rmdir($dir);
1627 return true;
1631 function xCacheFlush($sql=false,$inputarr=false)
1633 global $ADODB_CACHE_DIR;
1635 if ($this->memCache) {
1636 global $ADODB_INCLUDED_MEMCACHE;
1637 $key = false;
1638 if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
1639 if ($sql) $key = $this->_gencachename($sql.serialize($inputarr),false,true);
1640 flushmemCache($key, $this->memCacheHost, $this->memCachePort, $this->debug);
1641 return;
1644 if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
1645 if (strncmp(PHP_OS,'WIN',3) === 0) {
1646 $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
1647 } else {
1648 //$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f';
1649 $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/';
1650 // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
1652 if ($this->debug) {
1653 ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
1654 } else {
1655 exec($cmd);
1657 return;
1660 global $ADODB_INCLUDED_CSV;
1661 if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
1663 $f = $this->_gencachename($sql.serialize($inputarr),false);
1664 adodb_write_file($f,''); // is adodb_write_file needed?
1665 if (!@unlink($f)) {
1666 if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
1671 * Private function to generate filename for caching.
1672 * Filename is generated based on:
1674 * - sql statement
1675 * - database type (oci8, ibase, ifx, etc)
1676 * - database name
1677 * - userid
1678 * - setFetchMode (adodb 4.23)
1680 * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
1681 * Assuming that we can have 50,000 files per directory with good performance,
1682 * then we can scale to 12.8 million unique cached recordsets. Wow!
1684 function _gencachename($sql,$createdir,$memcache=false)
1686 global $ADODB_CACHE_DIR;
1687 static $notSafeMode;
1689 if ($this->fetchMode === false) {
1690 global $ADODB_FETCH_MODE;
1691 $mode = $ADODB_FETCH_MODE;
1692 } else {
1693 $mode = $this->fetchMode;
1695 $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
1696 if ($memcache) return $m;
1698 if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode');
1699 $dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR;
1701 if ($createdir && $notSafeMode && !file_exists($dir)) {
1702 $oldu = umask(0);
1703 if (!@mkdir($dir,0771))
1704 if(!is_dir($dir) && $this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
1705 umask($oldu);
1707 return $dir.'/adodb_'.$m.'.cache';
1712 * Execute SQL, caching recordsets.
1714 * @param [secs2cache] seconds to cache data, set to 0 to force query.
1715 * This is an optional parameter.
1716 * @param sql SQL statement to execute
1717 * @param [inputarr] holds the input data to bind to
1718 * @return RecordSet or false
1720 function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
1724 if (!is_numeric($secs2cache)) {
1725 $inputarr = $sql;
1726 $sql = $secs2cache;
1727 $secs2cache = $this->cacheSecs;
1730 if (is_array($sql)) {
1731 $sqlparam = $sql;
1732 $sql = $sql[0];
1733 } else
1734 $sqlparam = $sql;
1736 if ($this->memCache) {
1737 global $ADODB_INCLUDED_MEMCACHE;
1738 if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
1739 $md5file = $this->_gencachename($sql.serialize($inputarr),false,true);
1740 } else {
1741 global $ADODB_INCLUDED_CSV;
1742 if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
1743 $md5file = $this->_gencachename($sql.serialize($inputarr),true);
1746 $err = '';
1748 if ($secs2cache > 0){
1749 if ($this->memCache)
1750 $rs = &getmemCache($md5file,$err,$secs2cache, $this->memCacheHost, $this->memCachePort);
1751 else
1752 $rs = &csv2rs($md5file,$err,$secs2cache,$this->arrayClass);
1753 $this->numCacheHits += 1;
1754 } else {
1755 $err='Timeout 1';
1756 $rs = false;
1757 $this->numCacheMisses += 1;
1759 if (!$rs) {
1760 // no cached rs found
1761 if ($this->debug) {
1762 if (get_magic_quotes_runtime() && !$this->memCache) {
1763 ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
1765 if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
1768 $rs = &$this->Execute($sqlparam,$inputarr);
1770 if ($rs && $this->memCache) {
1771 $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
1772 if(!putmemCache($md5file, $rs, $this->memCacheHost, $this->memCachePort, $this->memCacheCompress, $this->debug)) {
1773 if ($fn = $this->raiseErrorFn)
1774 $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
1775 if ($this->debug) ADOConnection::outp( " Cache write error");
1777 } else if ($rs) {
1778 $eof = $rs->EOF;
1779 $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
1780 $txt = _rs2serialize($rs,false,$sql); // serialize
1782 $ok = adodb_write_file($md5file,$txt,$this->debug);
1783 if (!$ok) {
1784 if ($ok === false) {
1785 $em = 'Cache write error';
1786 $en = -32000;
1788 if ($fn = $this->raiseErrorFn) {
1789 $fn($this->databaseType,'CacheExecute', $en, $em, $md5file,$sql,$this);
1791 } else {
1792 $em = 'Cache file locked warning';
1793 $en = -32001;
1794 // do not call error handling for just a warning
1797 if ($this->debug) ADOConnection::outp( " ".$em);
1799 if ($rs->EOF && !$eof) {
1800 $rs->MoveFirst();
1801 //$rs = &csv2rs($md5file,$err);
1802 $rs->connection = &$this; // Pablo suggestion
1805 } else
1806 if (!$this->memCache)
1807 @unlink($md5file);
1808 } else {
1809 $this->_errorMsg = '';
1810 $this->_errorCode = 0;
1812 if ($this->fnCacheExecute) {
1813 $fn = $this->fnCacheExecute;
1814 $fn($this, $secs2cache, $sql, $inputarr);
1816 // ok, set cached object found
1817 $rs->connection = &$this; // Pablo suggestion
1818 if ($this->debug){
1820 $inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
1821 $ttl = $rs->timeCreated + $secs2cache - time();
1822 $s = is_array($sql) ? $sql[0] : $sql;
1823 if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
1825 ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
1828 return $rs;
1833 Similar to PEAR DB's autoExecute(), except that
1834 $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
1835 If $mode == 'UPDATE', then $where is compulsory as a safety measure.
1837 $forceUpdate means that even if the data has not changed, perform update.
1839 function& AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false)
1841 $false = false;
1842 $sql = 'SELECT * FROM '.$table;
1843 if ($where!==FALSE) $sql .= ' WHERE '.$where;
1844 else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
1845 ADOConnection::outp('AutoExecute: Illegal mode=UPDATE with empty WHERE clause');
1846 return $false;
1849 $rs =& $this->SelectLimit($sql,1);
1850 if (!$rs) return $false; // table does not exist
1851 $rs->tableName = $table;
1853 switch((string) $mode) {
1854 case 'UPDATE':
1855 case '2':
1856 $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
1857 break;
1858 case 'INSERT':
1859 case '1':
1860 $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
1861 break;
1862 default:
1863 ADOConnection::outp("AutoExecute: Unknown mode=$mode");
1864 return $false;
1866 $ret = false;
1867 if ($sql) $ret = $this->Execute($sql);
1868 if ($ret) $ret = true;
1869 return $ret;
1874 * Generates an Update Query based on an existing recordset.
1875 * $arrFields is an associative array of fields with the value
1876 * that should be assigned.
1878 * Note: This function should only be used on a recordset
1879 * that is run against a single table and sql should only
1880 * be a simple select stmt with no groupby/orderby/limit
1882 * "Jonathan Younger" <jyounger@unilab.com>
1884 function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
1886 global $ADODB_INCLUDED_LIB;
1888 //********************************************************//
1889 //This is here to maintain compatibility
1890 //with older adodb versions. Sets force type to force nulls if $forcenulls is set.
1891 if (!isset($force)) {
1892 global $ADODB_FORCE_TYPE;
1893 $force = $ADODB_FORCE_TYPE;
1895 //********************************************************//
1897 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
1898 return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
1902 * Generates an Insert Query based on an existing recordset.
1903 * $arrFields is an associative array of fields with the value
1904 * that should be assigned.
1906 * Note: This function should only be used on a recordset
1907 * that is run against a single table.
1909 function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
1911 global $ADODB_INCLUDED_LIB;
1912 if (!isset($force)) {
1913 global $ADODB_FORCE_TYPE;
1914 $force = $ADODB_FORCE_TYPE;
1917 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
1918 return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
1923 * Update a blob column, given a where clause. There are more sophisticated
1924 * blob handling functions that we could have implemented, but all require
1925 * a very complex API. Instead we have chosen something that is extremely
1926 * simple to understand and use.
1928 * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
1930 * Usage to update a $blobvalue which has a primary key blob_id=1 into a
1931 * field blobtable.blobcolumn:
1933 * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
1935 * Insert example:
1937 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
1938 * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
1941 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
1943 return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
1947 * Usage:
1948 * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
1950 * $blobtype supports 'BLOB' and 'CLOB'
1952 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
1953 * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
1955 function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
1957 $fd = fopen($path,'rb');
1958 if ($fd === false) return false;
1959 $val = fread($fd,filesize($path));
1960 fclose($fd);
1961 return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
1964 function BlobDecode($blob)
1966 return $blob;
1969 function BlobEncode($blob)
1971 return $blob;
1974 function SetCharSet($charset)
1976 return false;
1979 function IfNull( $field, $ifNull )
1981 return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
1984 function LogSQL($enable=true)
1986 include_once(ADODB_DIR.'/adodb-perf.inc.php');
1988 if ($enable) $this->fnExecute = 'adodb_log_sql';
1989 else $this->fnExecute = false;
1991 $old = $this->_logsql;
1992 $this->_logsql = $enable;
1993 if ($enable && !$old) $this->_affected = false;
1994 return $old;
1997 function GetCharSet()
1999 return false;
2003 * Usage:
2004 * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
2006 * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
2007 * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
2009 function UpdateClob($table,$column,$val,$where)
2011 return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
2014 // not the fastest implementation - quick and dirty - jlim
2015 // for best performance, use the actual $rs->MetaType().
2016 function MetaType($t,$len=-1,$fieldobj=false)
2019 if (empty($this->_metars)) {
2020 $rsclass = $this->rsPrefix.$this->databaseType;
2021 $this->_metars = new $rsclass(false,$this->fetchMode);
2022 $this->_metars->connection =& $this;
2024 return $this->_metars->MetaType($t,$len,$fieldobj);
2029 * Change the SQL connection locale to a specified locale.
2030 * This is used to get the date formats written depending on the client locale.
2032 function SetDateLocale($locale = 'En')
2034 $this->locale = $locale;
2035 switch (strtoupper($locale))
2037 case 'EN':
2038 $this->fmtDate="'Y-m-d'";
2039 $this->fmtTimeStamp = "'Y-m-d H:i:s'";
2040 break;
2042 case 'US':
2043 $this->fmtDate = "'m-d-Y'";
2044 $this->fmtTimeStamp = "'m-d-Y H:i:s'";
2045 break;
2047 case 'PT_BR':
2048 case 'NL':
2049 case 'FR':
2050 case 'RO':
2051 case 'IT':
2052 $this->fmtDate="'d-m-Y'";
2053 $this->fmtTimeStamp = "'d-m-Y H:i:s'";
2054 break;
2056 case 'GE':
2057 $this->fmtDate="'d.m.Y'";
2058 $this->fmtTimeStamp = "'d.m.Y H:i:s'";
2059 break;
2061 default:
2062 $this->fmtDate="'Y-m-d'";
2063 $this->fmtTimeStamp = "'Y-m-d H:i:s'";
2064 break;
2068 function &GetActiveRecordsClass($class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false)
2070 global $_ADODB_ACTIVE_DBS;
2072 $save = $this->SetFetchMode(ADODB_FETCH_NUM);
2073 if (empty($whereOrderBy)) $whereOrderBy = '1=1';
2074 $rows = $this->GetAll("select * from ".$table.' WHERE '.$whereOrderBy,$bindarr);
2075 $this->SetFetchMode($save);
2077 $false = false;
2079 if ($rows === false) {
2080 return $false;
2084 if (!isset($_ADODB_ACTIVE_DBS)) {
2085 include(ADODB_DIR.'/adodb-active-record.inc.php');
2087 if (!class_exists($class)) {
2088 ADOConnection::outp("Unknown class $class in GetActiveRcordsClass()");
2089 return $false;
2091 $arr = array();
2092 foreach($rows as $row) {
2094 $obj = new $class($table,$primkeyArr,$this);
2095 if ($obj->ErrorMsg()){
2096 $this->_errorMsg = $obj->ErrorMsg();
2097 return $false;
2099 $obj->Set($row);
2100 $arr[] = $obj;
2102 return $arr;
2105 function &GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
2107 $arr =& $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
2108 return $arr;
2112 * Close Connection
2114 function Close()
2116 $rez = $this->_close();
2117 $this->_connectionID = false;
2118 return $rez;
2122 * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
2124 * @return true if succeeded or false if database does not support transactions
2126 function BeginTrans()
2128 if ($this->debug) ADOConnection::outp("BeginTrans: Transactions not supported for this driver");
2129 return false;
2132 /* set transaction mode */
2133 function SetTransactionMode( $transaction_mode )
2135 $transaction_mode = $this->MetaTransaction($transaction_mode, $this->dataProvider);
2136 $this->_transmode = $transaction_mode;
2139 http://msdn2.microsoft.com/en-US/ms173763.aspx
2140 http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-isolation.html
2141 http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html
2142 http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm
2144 function MetaTransaction($mode,$db)
2146 $mode = strtoupper($mode);
2147 $mode = str_replace('ISOLATION LEVEL ','',$mode);
2149 switch($mode) {
2151 case 'READ UNCOMMITTED':
2152 switch($db) {
2153 case 'oci8':
2154 case 'oracle':
2155 return 'ISOLATION LEVEL READ COMMITTED';
2156 default:
2157 return 'ISOLATION LEVEL READ UNCOMMITTED';
2159 break;
2161 case 'READ COMMITTED':
2162 return 'ISOLATION LEVEL READ COMMITTED';
2163 break;
2165 case 'REPEATABLE READ':
2166 switch($db) {
2167 case 'oci8':
2168 case 'oracle':
2169 return 'ISOLATION LEVEL SERIALIZABLE';
2170 default:
2171 return 'ISOLATION LEVEL REPEATABLE READ';
2173 break;
2175 case 'SERIALIZABLE':
2176 return 'ISOLATION LEVEL SERIALIZABLE';
2177 break;
2179 default:
2180 return $mode;
2185 * If database does not support transactions, always return true as data always commited
2187 * @param $ok set to false to rollback transaction, true to commit
2189 * @return true/false.
2191 function CommitTrans($ok=true)
2192 { return true;}
2196 * If database does not support transactions, rollbacks always fail, so return false
2198 * @return true/false.
2200 function RollbackTrans()
2201 { return false;}
2205 * return the databases that the driver can connect to.
2206 * Some databases will return an empty array.
2208 * @return an array of database names.
2210 function MetaDatabases()
2212 global $ADODB_FETCH_MODE;
2214 if ($this->metaDatabasesSQL) {
2215 $save = $ADODB_FETCH_MODE;
2216 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
2218 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
2220 $arr = $this->GetCol($this->metaDatabasesSQL);
2221 if (isset($savem)) $this->SetFetchMode($savem);
2222 $ADODB_FETCH_MODE = $save;
2224 return $arr;
2227 return false;
2232 * @param ttype can either be 'VIEW' or 'TABLE' or false.
2233 * If false, both views and tables are returned.
2234 * "VIEW" returns only views
2235 * "TABLE" returns only tables
2236 * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
2237 * @param mask is the input mask - only supported by oci8 and postgresql
2239 * @return array of tables for current database.
2241 function &MetaTables($ttype=false,$showSchema=false,$mask=false)
2243 global $ADODB_FETCH_MODE;
2246 $false = false;
2247 if ($mask) {
2248 return $false;
2250 if ($this->metaTablesSQL) {
2251 $save = $ADODB_FETCH_MODE;
2252 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
2254 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
2256 $rs = $this->Execute($this->metaTablesSQL);
2257 if (isset($savem)) $this->SetFetchMode($savem);
2258 $ADODB_FETCH_MODE = $save;
2260 if ($rs === false) return $false;
2261 $arr =& $rs->GetArray();
2262 $arr2 = array();
2264 if ($hast = ($ttype && isset($arr[0][1]))) {
2265 $showt = strncmp($ttype,'T',1);
2268 for ($i=0; $i < sizeof($arr); $i++) {
2269 if ($hast) {
2270 if ($showt == 0) {
2271 if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
2272 } else {
2273 if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
2275 } else
2276 $arr2[] = trim($arr[$i][0]);
2278 $rs->Close();
2279 return $arr2;
2281 return $false;
2285 function _findschema(&$table,&$schema)
2287 if (!$schema && ($at = strpos($table,'.')) !== false) {
2288 $schema = substr($table,0,$at);
2289 $table = substr($table,$at+1);
2294 * List columns in a database as an array of ADOFieldObjects.
2295 * See top of file for definition of object.
2297 * @param $table table name to query
2298 * @param $normalize makes table name case-insensitive (required by some databases)
2299 * @schema is optional database schema to use - not supported by all databases.
2301 * @return array of ADOFieldObjects for current table.
2303 function &MetaColumns($table,$normalize=true)
2305 global $ADODB_FETCH_MODE;
2307 $false = false;
2309 if (!empty($this->metaColumnsSQL)) {
2311 $schema = false;
2312 $this->_findschema($table,$schema);
2314 $save = $ADODB_FETCH_MODE;
2315 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
2316 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
2317 $rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table));
2318 if (isset($savem)) $this->SetFetchMode($savem);
2319 $ADODB_FETCH_MODE = $save;
2320 if ($rs === false || $rs->EOF) return $false;
2322 $retarr = array();
2323 while (!$rs->EOF) { //print_r($rs->fields);
2324 $fld = new ADOFieldObject();
2325 $fld->name = $rs->fields[0];
2326 $fld->type = $rs->fields[1];
2327 if (isset($rs->fields[3]) && $rs->fields[3]) {
2328 if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
2329 $fld->scale = $rs->fields[4];
2330 if ($fld->scale>0) $fld->max_length += 1;
2331 } else
2332 $fld->max_length = $rs->fields[2];
2334 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
2335 else $retarr[strtoupper($fld->name)] = $fld;
2336 $rs->MoveNext();
2338 $rs->Close();
2339 return $retarr;
2341 return $false;
2345 * List indexes on a table as an array.
2346 * @param table table name to query
2347 * @param primary true to only show primary keys. Not actually used for most databases
2349 * @return array of indexes on current table. Each element represents an index, and is itself an associative array.
2351 Array (
2352 [name_of_index] => Array
2354 [unique] => true or false
2355 [columns] => Array
2357 [0] => firstname
2358 [1] => lastname
2362 function &MetaIndexes($table, $primary = false, $owner = false)
2364 $false = false;
2365 return $false;
2369 * List columns names in a table as an array.
2370 * @param table table name to query
2372 * @return array of column names for current table.
2374 function &MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */)
2376 $objarr =& $this->MetaColumns($table);
2377 if (!is_array($objarr)) {
2378 $false = false;
2379 return $false;
2381 $arr = array();
2382 if ($numIndexes) {
2383 $i = 0;
2384 if ($useattnum) {
2385 foreach($objarr as $v)
2386 $arr[$v->attnum] = $v->name;
2388 } else
2389 foreach($objarr as $v) $arr[$i++] = $v->name;
2390 } else
2391 foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
2393 return $arr;
2397 * Different SQL databases used different methods to combine strings together.
2398 * This function provides a wrapper.
2400 * param s variable number of string parameters
2402 * Usage: $db->Concat($str1,$str2);
2404 * @return concatenated string
2406 function Concat()
2408 $arr = func_get_args();
2409 return implode($this->concat_operator, $arr);
2414 * Converts a date "d" to a string that the database can understand.
2416 * @param d a date in Unix date time format.
2418 * @return date string in database date format
2420 function DBDate($d)
2422 if (empty($d) && $d !== 0) return 'null';
2424 if (is_string($d) && !is_numeric($d)) {
2425 if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
2426 if ($this->isoDates) return "'$d'";
2427 $d = ADOConnection::UnixDate($d);
2430 return adodb_date($this->fmtDate,$d);
2433 function BindDate($d)
2435 $d = $this->DBDate($d);
2436 if (strncmp($d,"'",1)) return $d;
2438 return substr($d,1,strlen($d)-2);
2441 function BindTimeStamp($d)
2443 $d = $this->DBTimeStamp($d);
2444 if (strncmp($d,"'",1)) return $d;
2446 return substr($d,1,strlen($d)-2);
2451 * Converts a timestamp "ts" to a string that the database can understand.
2453 * @param ts a timestamp in Unix date time format.
2455 * @return timestamp string in database timestamp format
2457 function DBTimeStamp($ts)
2459 if (empty($ts) && $ts !== 0) return 'null';
2461 # strlen(14) allows YYYYMMDDHHMMSS format
2462 if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
2463 return adodb_date($this->fmtTimeStamp,$ts);
2465 if ($ts === 'null') return $ts;
2466 if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
2468 $ts = ADOConnection::UnixTimeStamp($ts);
2469 return adodb_date($this->fmtTimeStamp,$ts);
2473 * Also in ADORecordSet.
2474 * @param $v is a date string in YYYY-MM-DD format
2476 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2478 function UnixDate($v)
2480 if (is_object($v)) {
2481 // odbtp support
2482 //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
2483 return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
2486 if (is_numeric($v) && strlen($v) !== 8) return $v;
2487 if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
2488 ($v), $rr)) return false;
2490 if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
2491 // h-m-s-MM-DD-YY
2492 return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2497 * Also in ADORecordSet.
2498 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
2500 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2502 function UnixTimeStamp($v)
2504 if (is_object($v)) {
2505 // odbtp support
2506 //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
2507 return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
2510 if (!preg_match(
2511 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
2512 ($v), $rr)) return false;
2514 if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
2516 // h-m-s-MM-DD-YY
2517 if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2518 return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
2522 * Also in ADORecordSet.
2524 * Format database date based on user defined format.
2526 * @param v is the character date in YYYY-MM-DD format, returned by database
2527 * @param fmt is the format to apply to it, using date()
2529 * @return a date formated as user desires
2532 function UserDate($v,$fmt='Y-m-d',$gmt=false)
2534 $tt = $this->UnixDate($v);
2536 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2537 if (($tt === false || $tt == -1) && $v != false) return $v;
2538 else if ($tt == 0) return $this->emptyDate;
2539 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
2542 return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
2548 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
2549 * @param fmt is the format to apply to it, using date()
2551 * @return a timestamp formated as user desires
2553 function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false)
2555 if (!isset($v)) return $this->emptyTimeStamp;
2556 # strlen(14) allows YYYYMMDDHHMMSS format
2557 if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
2558 $tt = $this->UnixTimeStamp($v);
2559 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2560 if (($tt === false || $tt == -1) && $v != false) return $v;
2561 if ($tt == 0) return $this->emptyTimeStamp;
2562 return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
2565 function escape($s,$magic_quotes=false)
2567 return $this->addq($s,$magic_quotes);
2571 * Quotes a string, without prefixing nor appending quotes.
2573 function addq($s,$magic_quotes=false)
2575 if (!$magic_quotes) {
2577 if ($this->replaceQuote[0] == '\\'){
2578 // only since php 4.0.5
2579 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
2580 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
2582 return str_replace("'",$this->replaceQuote,$s);
2585 // undo magic quotes for "
2586 $s = str_replace('\\"','"',$s);
2588 // moodle change start - see readme_moodle.txt
2589 if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything
2590 // moodle change end - see readme_moodle.txt
2591 return $s;
2592 else {// change \' to '' for sybase/mssql
2593 $s = str_replace('\\\\','\\',$s);
2594 return str_replace("\\'",$this->replaceQuote,$s);
2599 * Correctly quotes a string so that all strings are escaped. We prefix and append
2600 * to the string single-quotes.
2601 * An example is $db->qstr("Don't bother",magic_quotes_runtime());
2603 * @param s the string to quote
2604 * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
2605 * This undoes the stupidity of magic quotes for GPC.
2607 * @return quoted string to be sent back to database
2609 function qstr($s,$magic_quotes=false)
2611 if (!$magic_quotes) {
2613 if ($this->replaceQuote[0] == '\\'){
2614 // only since php 4.0.5
2615 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
2616 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
2618 return "'".str_replace("'",$this->replaceQuote,$s)."'";
2621 // undo magic quotes for "
2622 $s = str_replace('\\"','"',$s);
2624 // moodle change start - see readme_moodle.txt
2625 if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything
2626 // moodle change end - see readme_moodle.txt
2627 return "'$s'";
2628 else {// change \' to '' for sybase/mssql
2629 $s = str_replace('\\\\','\\',$s);
2630 return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
2636 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
2637 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
2638 * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
2640 * See readme.htm#ex8 for an example of usage.
2642 * @param sql
2643 * @param nrows is the number of rows per page to get
2644 * @param page is the page number to get (1-based)
2645 * @param [inputarr] array of bind variables
2646 * @param [secs2cache] is a private parameter only used by jlim
2647 * @return the recordset ($rs->databaseType == 'array')
2649 * NOTE: phpLens uses a different algorithm and does not use PageExecute().
2652 function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0)
2654 global $ADODB_INCLUDED_LIB;
2655 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
2656 if ($this->pageExecuteCountRows) $rs =& _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
2657 else $rs =& _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
2658 return $rs;
2663 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
2664 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
2665 * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
2667 * @param secs2cache seconds to cache data, set to 0 to force query
2668 * @param sql
2669 * @param nrows is the number of rows per page to get
2670 * @param page is the page number to get (1-based)
2671 * @param [inputarr] array of bind variables
2672 * @return the recordset ($rs->databaseType == 'array')
2674 function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false)
2676 /*switch($this->dataProvider) {
2677 case 'postgres':
2678 case 'mysql':
2679 break;
2680 default: $secs2cache = 0; break;
2682 $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
2683 return $rs;
2686 } // end class ADOConnection
2690 //==============================================================================================
2691 // CLASS ADOFetchObj
2692 //==============================================================================================
2695 * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
2697 class ADOFetchObj {
2700 //==============================================================================================
2701 // CLASS ADORecordSet_empty
2702 //==============================================================================================
2705 * Lightweight recordset when there are no records to be returned
2707 class ADORecordSet_empty
2709 var $dataProvider = 'empty';
2710 var $databaseType = false;
2711 var $EOF = true;
2712 var $_numOfRows = 0;
2713 var $fields = false;
2714 var $connection = false;
2715 function RowCount() {return 0;}
2716 function RecordCount() {return 0;}
2717 function PO_RecordCount(){return 0;}
2718 function Close(){return true;}
2719 function FetchRow() {return false;}
2720 function FieldCount(){ return 0;}
2721 function Init() {}
2724 //==============================================================================================
2725 // DATE AND TIME FUNCTIONS
2726 //==============================================================================================
2727 if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR.'/adodb-time.inc.php');
2729 //==============================================================================================
2730 // CLASS ADORecordSet
2731 //==============================================================================================
2733 if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
2734 else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
2736 * RecordSet class that represents the dataset returned by the database.
2737 * To keep memory overhead low, this class holds only the current row in memory.
2738 * No prefetching of data is done, so the RecordCount() can return -1 ( which
2739 * means recordcount not known).
2741 class ADORecordSet extends ADODB_BASE_RS {
2743 * public variables
2745 var $dataProvider = "native";
2746 var $fields = false; /// holds the current row data
2747 var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
2748 /// in other words, we use a text area for editing.
2749 var $canSeek = false; /// indicates that seek is supported
2750 var $sql; /// sql text
2751 var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
2753 var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
2754 var $emptyDate = '&nbsp;'; /// what to display when $time==0
2755 var $debug = false;
2756 var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
2758 var $bind = false; /// used by Fields() to hold array - should be private?
2759 var $fetchMode; /// default fetch mode
2760 var $connection = false; /// the parent connection
2762 * private variables
2764 var $_numOfRows = -1; /** number of rows, or -1 */
2765 var $_numOfFields = -1; /** number of fields in recordset */
2766 var $_queryID = -1; /** This variable keeps the result link identifier. */
2767 var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
2768 var $_closed = false; /** has recordset been closed */
2769 var $_inited = false; /** Init() should only be called once */
2770 var $_obj; /** Used by FetchObj */
2771 var $_names; /** Used by FetchObj */
2773 var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */
2774 var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */
2775 var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */
2776 var $_lastPageNo = -1;
2777 var $_maxRecordCount = 0;
2778 var $datetime = false;
2781 * Constructor
2783 * @param queryID this is the queryID returned by ADOConnection->_query()
2786 function ADORecordSet($queryID)
2788 $this->_queryID = $queryID;
2793 function Init()
2795 if ($this->_inited) return;
2796 $this->_inited = true;
2797 if ($this->_queryID) @$this->_initrs();
2798 else {
2799 $this->_numOfRows = 0;
2800 $this->_numOfFields = 0;
2802 if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
2804 $this->_currentRow = 0;
2805 if ($this->EOF = ($this->_fetch() === false)) {
2806 $this->_numOfRows = 0; // _numOfRows could be -1
2808 } else {
2809 $this->EOF = true;
2815 * Generate a SELECT tag string from a recordset, and return the string.
2816 * If the recordset has 2 cols, we treat the 1st col as the containing
2817 * the text to display to the user, and 2nd col as the return value. Default
2818 * strings are compared with the FIRST column.
2820 * @param name name of SELECT tag
2821 * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
2822 * @param [blank1stItem] true to leave the 1st item in list empty
2823 * @param [multiple] true for listbox, false for popup
2824 * @param [size] #rows to show for listbox. not used by popup
2825 * @param [selectAttr] additional attributes to defined for SELECT tag.
2826 * useful for holding javascript onChange='...' handlers.
2827 & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
2828 * column 0 (1st col) if this is true. This is not documented.
2830 * @return HTML
2832 * changes by glen.davies@cce.ac.nz to support multiple hilited items
2834 function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
2835 $size=0, $selectAttr='',$compareFields0=true)
2837 global $ADODB_INCLUDED_LIB;
2838 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
2839 return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
2840 $size, $selectAttr,$compareFields0);
2846 * Generate a SELECT tag string from a recordset, and return the string.
2847 * If the recordset has 2 cols, we treat the 1st col as the containing
2848 * the text to display to the user, and 2nd col as the return value. Default
2849 * strings are compared with the SECOND column.
2852 function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
2854 return $this->GetMenu($name,$defstr,$blank1stItem,$multiple,
2855 $size, $selectAttr,false);
2859 Grouped Menu
2861 function GetMenu3($name,$defstr='',$blank1stItem=true,$multiple=false,
2862 $size=0, $selectAttr='')
2864 global $ADODB_INCLUDED_LIB;
2865 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
2866 return _adodb_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple,
2867 $size, $selectAttr,false);
2871 * return recordset as a 2-dimensional array.
2873 * @param [nRows] is the number of rows to return. -1 means every row.
2875 * @return an array indexed by the rows (0-based) from the recordset
2877 function &GetArray($nRows = -1)
2879 global $ADODB_EXTENSION; if ($ADODB_EXTENSION) {
2880 $results = adodb_getall($this,$nRows);
2881 return $results;
2883 $results = array();
2884 $cnt = 0;
2885 while (!$this->EOF && $nRows != $cnt) {
2886 $results[] = $this->fields;
2887 $this->MoveNext();
2888 $cnt++;
2890 return $results;
2893 function &GetAll($nRows = -1)
2895 $arr =& $this->GetArray($nRows);
2896 return $arr;
2900 * Some databases allow multiple recordsets to be returned. This function
2901 * will return true if there is a next recordset, or false if no more.
2903 function NextRecordSet()
2905 return false;
2909 * return recordset as a 2-dimensional array.
2910 * Helper function for ADOConnection->SelectLimit()
2912 * @param offset is the row to start calculations from (1-based)
2913 * @param [nrows] is the number of rows to return
2915 * @return an array indexed by the rows (0-based) from the recordset
2917 function &GetArrayLimit($nrows,$offset=-1)
2919 if ($offset <= 0) {
2920 $arr =& $this->GetArray($nrows);
2921 return $arr;
2924 $this->Move($offset);
2926 $results = array();
2927 $cnt = 0;
2928 while (!$this->EOF && $nrows != $cnt) {
2929 $results[$cnt++] = $this->fields;
2930 $this->MoveNext();
2933 return $results;
2938 * Synonym for GetArray() for compatibility with ADO.
2940 * @param [nRows] is the number of rows to return. -1 means every row.
2942 * @return an array indexed by the rows (0-based) from the recordset
2944 function &GetRows($nRows = -1)
2946 $arr =& $this->GetArray($nRows);
2947 return $arr;
2951 * return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
2952 * The first column is treated as the key and is not included in the array.
2953 * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
2954 * $force_array == true.
2956 * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
2957 * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
2958 * read the source.
2960 * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
2961 * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
2963 * @return an associative array indexed by the first column of the array,
2964 * or false if the data has less than 2 cols.
2966 function &GetAssoc($force_array = false, $first2cols = false)
2968 global $ADODB_EXTENSION;
2970 $cols = $this->_numOfFields;
2971 if ($cols < 2) {
2972 $false = false;
2973 return $false;
2975 $numIndex = isset($this->fields[0]);
2976 $results = array();
2978 if (!$first2cols && ($cols > 2 || $force_array)) {
2979 if ($ADODB_EXTENSION) {
2980 if ($numIndex) {
2981 while (!$this->EOF) {
2982 $results[trim($this->fields[0])] = array_slice($this->fields, 1);
2983 adodb_movenext($this);
2985 } else {
2986 while (!$this->EOF) {
2987 // Fix for array_slice re-numbering numeric associative keys
2988 $keys = array_slice(array_keys($this->fields), 1);
2989 $sliced_array = array();
2991 foreach($keys as $key) {
2992 $sliced_array[$key] = $this->fields[$key];
2995 $results[trim(reset($this->fields))] = $sliced_array;
2996 adodb_movenext($this);
2999 } else {
3000 if ($numIndex) {
3001 while (!$this->EOF) {
3002 $results[trim($this->fields[0])] = array_slice($this->fields, 1);
3003 $this->MoveNext();
3005 } else {
3006 while (!$this->EOF) {
3007 // Fix for array_slice re-numbering numeric associative keys
3008 $keys = array_slice(array_keys($this->fields), 1);
3009 $sliced_array = array();
3011 foreach($keys as $key) {
3012 $sliced_array[$key] = $this->fields[$key];
3015 $results[trim(reset($this->fields))] = $sliced_array;
3016 $this->MoveNext();
3020 } else {
3021 if ($ADODB_EXTENSION) {
3022 // return scalar values
3023 if ($numIndex) {
3024 while (!$this->EOF) {
3025 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3026 $results[trim(($this->fields[0]))] = $this->fields[1];
3027 adodb_movenext($this);
3029 } else {
3030 while (!$this->EOF) {
3031 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3032 $v1 = trim(reset($this->fields));
3033 $v2 = ''.next($this->fields);
3034 $results[$v1] = $v2;
3035 adodb_movenext($this);
3038 } else {
3039 if ($numIndex) {
3040 while (!$this->EOF) {
3041 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3042 $results[trim(($this->fields[0]))] = $this->fields[1];
3043 $this->MoveNext();
3045 } else {
3046 while (!$this->EOF) {
3047 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3048 $v1 = trim(reset($this->fields));
3049 $v2 = ''.next($this->fields);
3050 $results[$v1] = $v2;
3051 $this->MoveNext();
3057 $ref =& $results; # workaround accelerator incompat with PHP 4.4 :(
3058 return $ref;
3064 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
3065 * @param fmt is the format to apply to it, using date()
3067 * @return a timestamp formated as user desires
3069 function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
3071 if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
3072 $tt = $this->UnixTimeStamp($v);
3073 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
3074 if (($tt === false || $tt == -1) && $v != false) return $v;
3075 if ($tt === 0) return $this->emptyTimeStamp;
3076 return adodb_date($fmt,$tt);
3081 * @param v is the character date in YYYY-MM-DD format, returned by database
3082 * @param fmt is the format to apply to it, using date()
3084 * @return a date formated as user desires
3086 function UserDate($v,$fmt='Y-m-d')
3088 $tt = $this->UnixDate($v);
3089 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
3090 if (($tt === false || $tt == -1) && $v != false) return $v;
3091 else if ($tt == 0) return $this->emptyDate;
3092 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
3094 return adodb_date($fmt,$tt);
3099 * @param $v is a date string in YYYY-MM-DD format
3101 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
3103 function UnixDate($v)
3105 return ADOConnection::UnixDate($v);
3110 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
3112 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
3114 function UnixTimeStamp($v)
3116 return ADOConnection::UnixTimeStamp($v);
3121 * PEAR DB Compat - do not use internally
3123 function Free()
3125 return $this->Close();
3130 * PEAR DB compat, number of rows
3132 function NumRows()
3134 return $this->_numOfRows;
3139 * PEAR DB compat, number of cols
3141 function NumCols()
3143 return $this->_numOfFields;
3147 * Fetch a row, returning false if no more rows.
3148 * This is PEAR DB compat mode.
3150 * @return false or array containing the current record
3152 function &FetchRow()
3154 if ($this->EOF) {
3155 $false = false;
3156 return $false;
3158 $arr = $this->fields;
3159 $this->_currentRow++;
3160 if (!$this->_fetch()) $this->EOF = true;
3161 return $arr;
3166 * Fetch a row, returning PEAR_Error if no more rows.
3167 * This is PEAR DB compat mode.
3169 * @return DB_OK or error object
3171 function FetchInto(&$arr)
3173 if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
3174 $arr = $this->fields;
3175 $this->MoveNext();
3176 return 1; // DB_OK
3181 * Move to the first row in the recordset. Many databases do NOT support this.
3183 * @return true or false
3185 function MoveFirst()
3187 if ($this->_currentRow == 0) return true;
3188 return $this->Move(0);
3193 * Move to the last row in the recordset.
3195 * @return true or false
3197 function MoveLast()
3199 if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
3200 if ($this->EOF) return false;
3201 while (!$this->EOF) {
3202 $f = $this->fields;
3203 $this->MoveNext();
3205 $this->fields = $f;
3206 $this->EOF = false;
3207 return true;
3212 * Move to next record in the recordset.
3214 * @return true if there still rows available, or false if there are no more rows (EOF).
3216 function MoveNext()
3218 if (!$this->EOF) {
3219 $this->_currentRow++;
3220 if ($this->_fetch()) return true;
3222 $this->EOF = true;
3223 /* -- tested error handling when scrolling cursor -- seems useless.
3224 $conn = $this->connection;
3225 if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
3226 $fn = $conn->raiseErrorFn;
3227 $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
3230 return false;
3235 * Random access to a specific row in the recordset. Some databases do not support
3236 * access to previous rows in the databases (no scrolling backwards).
3238 * @param rowNumber is the row to move to (0-based)
3240 * @return true if there still rows available, or false if there are no more rows (EOF).
3242 function Move($rowNumber = 0)
3244 $this->EOF = false;
3245 if ($rowNumber == $this->_currentRow) return true;
3246 if ($rowNumber >= $this->_numOfRows)
3247 if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
3249 if ($this->canSeek) {
3251 if ($this->_seek($rowNumber)) {
3252 $this->_currentRow = $rowNumber;
3253 if ($this->_fetch()) {
3254 return true;
3256 } else {
3257 $this->EOF = true;
3258 return false;
3260 } else {
3261 if ($rowNumber < $this->_currentRow) return false;
3262 global $ADODB_EXTENSION;
3263 if ($ADODB_EXTENSION) {
3264 while (!$this->EOF && $this->_currentRow < $rowNumber) {
3265 adodb_movenext($this);
3267 } else {
3269 while (! $this->EOF && $this->_currentRow < $rowNumber) {
3270 $this->_currentRow++;
3272 if (!$this->_fetch()) $this->EOF = true;
3275 return !($this->EOF);
3278 $this->fields = false;
3279 $this->EOF = true;
3280 return false;
3285 * Get the value of a field in the current row by column name.
3286 * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
3288 * @param colname is the field to access
3290 * @return the value of $colname column
3292 function Fields($colname)
3294 return $this->fields[$colname];
3297 function GetAssocKeys($upper=true)
3299 $this->bind = array();
3300 for ($i=0; $i < $this->_numOfFields; $i++) {
3301 $o = $this->FetchField($i);
3302 if ($upper === 2) $this->bind[$o->name] = $i;
3303 else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
3308 * Use associative array to get fields array for databases that do not support
3309 * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it
3311 * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
3312 * before you execute your SQL statement, and access $rs->fields['col'] directly.
3314 * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
3316 function &GetRowAssoc($upper=1)
3318 $record = array();
3319 // if (!$this->fields) return $record;
3321 if (!$this->bind) {
3322 $this->GetAssocKeys($upper);
3325 foreach($this->bind as $k => $v) {
3326 $record[$k] = $this->fields[$v];
3329 return $record;
3334 * Clean up recordset
3336 * @return true or false
3338 function Close()
3340 // free connection object - this seems to globally free the object
3341 // and not merely the reference, so don't do this...
3342 // $this->connection = false;
3343 if (!$this->_closed) {
3344 $this->_closed = true;
3345 return $this->_close();
3346 } else
3347 return true;
3351 * synonyms RecordCount and RowCount
3353 * @return the number of rows or -1 if this is not supported
3355 function RecordCount() {return $this->_numOfRows;}
3359 * If we are using PageExecute(), this will return the maximum possible rows
3360 * that can be returned when paging a recordset.
3362 function MaxRecordCount()
3364 return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
3368 * synonyms RecordCount and RowCount
3370 * @return the number of rows or -1 if this is not supported
3372 function RowCount() {return $this->_numOfRows;}
3376 * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
3378 * @return the number of records from a previous SELECT. All databases support this.
3380 * But aware possible problems in multiuser environments. For better speed the table
3381 * must be indexed by the condition. Heavy test this before deploying.
3383 function PO_RecordCount($table="", $condition="") {
3385 $lnumrows = $this->_numOfRows;
3386 // the database doesn't support native recordcount, so we do a workaround
3387 if ($lnumrows == -1 && $this->connection) {
3388 IF ($table) {
3389 if ($condition) $condition = " WHERE " . $condition;
3390 $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
3391 if ($resultrows) $lnumrows = reset($resultrows->fields);
3394 return $lnumrows;
3399 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
3401 function CurrentRow() {return $this->_currentRow;}
3404 * synonym for CurrentRow -- for ADO compat
3406 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
3408 function AbsolutePosition() {return $this->_currentRow;}
3411 * @return the number of columns in the recordset. Some databases will set this to 0
3412 * if no records are returned, others will return the number of columns in the query.
3414 function FieldCount() {return $this->_numOfFields;}
3418 * Get the ADOFieldObject of a specific column.
3420 * @param fieldoffset is the column position to access(0-based).
3422 * @return the ADOFieldObject for that column, or false.
3424 function &FetchField($fieldoffset = -1)
3426 // must be defined by child class
3428 $false = false;
3429 return $false;
3433 * Get the ADOFieldObjects of all columns in an array.
3436 function& FieldTypesArray()
3438 $arr = array();
3439 for ($i=0, $max=$this->_numOfFields; $i < $max; $i++)
3440 $arr[] = $this->FetchField($i);
3441 return $arr;
3445 * Return the fields array of the current row as an object for convenience.
3446 * The default case is lowercase field names.
3448 * @return the object with the properties set to the fields of the current row
3450 function &FetchObj()
3452 $o =& $this->FetchObject(false);
3453 return $o;
3457 * Return the fields array of the current row as an object for convenience.
3458 * The default case is uppercase.
3460 * @param $isupper to set the object property names to uppercase
3462 * @return the object with the properties set to the fields of the current row
3464 function &FetchObject($isupper=true)
3466 if (empty($this->_obj)) {
3467 $this->_obj = new ADOFetchObj();
3468 $this->_names = array();
3469 for ($i=0; $i <$this->_numOfFields; $i++) {
3470 $f = $this->FetchField($i);
3471 $this->_names[] = $f->name;
3474 $i = 0;
3475 if (PHP_VERSION >= 5) $o = clone($this->_obj);
3476 else $o = $this->_obj;
3478 for ($i=0; $i <$this->_numOfFields; $i++) {
3479 $name = $this->_names[$i];
3480 if ($isupper) $n = strtoupper($name);
3481 else $n = $name;
3483 $o->$n = $this->Fields($name);
3485 return $o;
3489 * Return the fields array of the current row as an object for convenience.
3490 * The default is lower-case field names.
3492 * @return the object with the properties set to the fields of the current row,
3493 * or false if EOF
3495 * Fixed bug reported by tim@orotech.net
3497 function &FetchNextObj()
3499 $o =& $this->FetchNextObject(false);
3500 return $o;
3505 * Return the fields array of the current row as an object for convenience.
3506 * The default is upper case field names.
3508 * @param $isupper to set the object property names to uppercase
3510 * @return the object with the properties set to the fields of the current row,
3511 * or false if EOF
3513 * Fixed bug reported by tim@orotech.net
3515 function &FetchNextObject($isupper=true)
3517 $o = false;
3518 if ($this->_numOfRows != 0 && !$this->EOF) {
3519 $o = $this->FetchObject($isupper);
3520 $this->_currentRow++;
3521 if ($this->_fetch()) return $o;
3523 $this->EOF = true;
3524 return $o;
3528 * Get the metatype of the column. This is used for formatting. This is because
3529 * many databases use different names for the same type, so we transform the original
3530 * type to our standardised version which uses 1 character codes:
3532 * @param t is the type passed in. Normally is ADOFieldObject->type.
3533 * @param len is the maximum length of that field. This is because we treat character
3534 * fields bigger than a certain size as a 'B' (blob).
3535 * @param fieldobj is the field object returned by the database driver. Can hold
3536 * additional info (eg. primary_key for mysql).
3538 * @return the general type of the data:
3539 * C for character < 250 chars
3540 * X for teXt (>= 250 chars)
3541 * B for Binary
3542 * N for numeric or floating point
3543 * D for date
3544 * T for timestamp
3545 * L for logical/Boolean
3546 * I for integer
3547 * R for autoincrement counter/integer
3551 function MetaType($t,$len=-1,$fieldobj=false)
3553 if (is_object($t)) {
3554 $fieldobj = $t;
3555 $t = $fieldobj->type;
3556 $len = $fieldobj->max_length;
3558 // changed in 2.32 to hashing instead of switch stmt for speed...
3559 static $typeMap = array(
3560 'VARCHAR' => 'C',
3561 'VARCHAR2' => 'C',
3562 'CHAR' => 'C',
3563 'C' => 'C',
3564 'STRING' => 'C',
3565 'NCHAR' => 'C',
3566 'NVARCHAR' => 'C',
3567 'VARYING' => 'C',
3568 'BPCHAR' => 'C',
3569 'CHARACTER' => 'C',
3570 'INTERVAL' => 'C', # Postgres
3571 'MACADDR' => 'C', # postgres
3573 'LONGCHAR' => 'X',
3574 'TEXT' => 'X',
3575 'NTEXT' => 'X',
3576 'M' => 'X',
3577 'X' => 'X',
3578 'CLOB' => 'X',
3579 'NCLOB' => 'X',
3580 'LVARCHAR' => 'X',
3582 'BLOB' => 'B',
3583 'IMAGE' => 'B',
3584 'BINARY' => 'B',
3585 'VARBINARY' => 'B',
3586 'LONGBINARY' => 'B',
3587 'B' => 'B',
3589 'YEAR' => 'D', // mysql
3590 'DATE' => 'D',
3591 'D' => 'D',
3593 'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
3595 'TIME' => 'T',
3596 'TIMESTAMP' => 'T',
3597 'DATETIME' => 'T',
3598 'TIMESTAMPTZ' => 'T',
3599 'T' => 'T',
3600 'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
3602 'BOOL' => 'L',
3603 'BOOLEAN' => 'L',
3604 'BIT' => 'L',
3605 'L' => 'L',
3607 'COUNTER' => 'R',
3608 'R' => 'R',
3609 'SERIAL' => 'R', // ifx
3610 'INT IDENTITY' => 'R',
3612 'INT' => 'I',
3613 'INT2' => 'I',
3614 'INT4' => 'I',
3615 'INT8' => 'I',
3616 'INTEGER' => 'I',
3617 'INTEGER UNSIGNED' => 'I',
3618 'SHORT' => 'I',
3619 'TINYINT' => 'I',
3620 'SMALLINT' => 'I',
3621 'I' => 'I',
3623 'LONG' => 'N', // interbase is numeric, oci8 is blob
3624 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
3625 'DECIMAL' => 'N',
3626 'DEC' => 'N',
3627 'REAL' => 'N',
3628 'DOUBLE' => 'N',
3629 'DOUBLE PRECISION' => 'N',
3630 'SMALLFLOAT' => 'N',
3631 'FLOAT' => 'N',
3632 'NUMBER' => 'N',
3633 'NUM' => 'N',
3634 'NUMERIC' => 'N',
3635 'MONEY' => 'N',
3637 ## informix 9.2
3638 'SQLINT' => 'I',
3639 'SQLSERIAL' => 'I',
3640 'SQLSMINT' => 'I',
3641 'SQLSMFLOAT' => 'N',
3642 'SQLFLOAT' => 'N',
3643 'SQLMONEY' => 'N',
3644 'SQLDECIMAL' => 'N',
3645 'SQLDATE' => 'D',
3646 'SQLVCHAR' => 'C',
3647 'SQLCHAR' => 'C',
3648 'SQLDTIME' => 'T',
3649 'SQLINTERVAL' => 'N',
3650 'SQLBYTES' => 'B',
3651 'SQLTEXT' => 'X',
3652 ## informix 10
3653 "SQLINT8" => 'I8',
3654 "SQLSERIAL8" => 'I8',
3655 "SQLNCHAR" => 'C',
3656 "SQLNVCHAR" => 'C',
3657 "SQLLVARCHAR" => 'X',
3658 "SQLBOOL" => 'L'
3661 $tmap = false;
3662 $t = strtoupper($t);
3663 $tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
3664 switch ($tmap) {
3665 case 'C':
3667 // is the char field is too long, return as text field...
3668 if ($this->blobSize >= 0) {
3669 if ($len > $this->blobSize) return 'X';
3670 } else if ($len > 250) {
3671 return 'X';
3673 return 'C';
3675 case 'I':
3676 if (!empty($fieldobj->primary_key)) return 'R';
3677 return 'I';
3679 case false:
3680 return 'N';
3682 case 'B':
3683 if (isset($fieldobj->binary))
3684 return ($fieldobj->binary) ? 'B' : 'X';
3685 return 'B';
3687 case 'D':
3688 if (!empty($this->connection) && !empty($this->connection->datetime)) return 'T';
3689 return 'D';
3691 default:
3692 if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
3693 return $tmap;
3698 function _close() {}
3701 * set/returns the current recordset page when paginating
3703 function AbsolutePage($page=-1)
3705 if ($page != -1) $this->_currentPage = $page;
3706 return $this->_currentPage;
3710 * set/returns the status of the atFirstPage flag when paginating
3712 function AtFirstPage($status=false)
3714 if ($status != false) $this->_atFirstPage = $status;
3715 return $this->_atFirstPage;
3718 function LastPageNo($page = false)
3720 if ($page != false) $this->_lastPageNo = $page;
3721 return $this->_lastPageNo;
3725 * set/returns the status of the atLastPage flag when paginating
3727 function AtLastPage($status=false)
3729 if ($status != false) $this->_atLastPage = $status;
3730 return $this->_atLastPage;
3733 } // end class ADORecordSet
3735 //==============================================================================================
3736 // CLASS ADORecordSet_array
3737 //==============================================================================================
3740 * This class encapsulates the concept of a recordset created in memory
3741 * as an array. This is useful for the creation of cached recordsets.
3743 * Note that the constructor is different from the standard ADORecordSet
3746 class ADORecordSet_array extends ADORecordSet
3748 var $databaseType = 'array';
3750 var $_array; // holds the 2-dimensional data array
3751 var $_types; // the array of types of each column (C B I L M)
3752 var $_colnames; // names of each column in array
3753 var $_skiprow1; // skip 1st row because it holds column names
3754 var $_fieldobjects; // holds array of field objects
3755 var $canSeek = true;
3756 var $affectedrows = false;
3757 var $insertid = false;
3758 var $sql = '';
3759 var $compat = false;
3761 * Constructor
3764 function ADORecordSet_array($fakeid=1)
3766 global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
3768 // fetch() on EOF does not delete $this->fields
3769 $this->compat = !empty($ADODB_COMPAT_FETCH);
3770 $this->ADORecordSet($fakeid); // fake queryID
3771 $this->fetchMode = $ADODB_FETCH_MODE;
3774 function _transpose($addfieldnames=true)
3776 global $ADODB_INCLUDED_LIB;
3778 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
3779 $hdr = true;
3781 $fobjs = $addfieldnames ? $this->_fieldobjects : false;
3782 adodb_transpose($this->_array, $newarr, $hdr, $fobjs);
3783 //adodb_pr($newarr);
3785 $this->_skiprow1 = false;
3786 $this->_array =& $newarr;
3787 $this->_colnames = $hdr;
3789 adodb_probetypes($newarr,$this->_types);
3791 $this->_fieldobjects = array();
3793 foreach($hdr as $k => $name) {
3794 $f = new ADOFieldObject();
3795 $f->name = $name;
3796 $f->type = $this->_types[$k];
3797 $f->max_length = -1;
3798 $this->_fieldobjects[] = $f;
3800 $this->fields = reset($this->_array);
3802 $this->_initrs();
3807 * Setup the array.
3809 * @param array is a 2-dimensional array holding the data.
3810 * The first row should hold the column names
3811 * unless paramter $colnames is used.
3812 * @param typearr holds an array of types. These are the same types
3813 * used in MetaTypes (C,B,L,I,N).
3814 * @param [colnames] array of column names. If set, then the first row of
3815 * $array should not hold the column names.
3817 function InitArray($array,$typearr,$colnames=false)
3819 $this->_array = $array;
3820 $this->_types = $typearr;
3821 if ($colnames) {
3822 $this->_skiprow1 = false;
3823 $this->_colnames = $colnames;
3824 } else {
3825 $this->_skiprow1 = true;
3826 $this->_colnames = $array[0];
3828 $this->Init();
3831 * Setup the Array and datatype file objects
3833 * @param array is a 2-dimensional array holding the data.
3834 * The first row should hold the column names
3835 * unless paramter $colnames is used.
3836 * @param fieldarr holds an array of ADOFieldObject's.
3838 function InitArrayFields(&$array,&$fieldarr)
3840 $this->_array =& $array;
3841 $this->_skiprow1= false;
3842 if ($fieldarr) {
3843 $this->_fieldobjects =& $fieldarr;
3845 $this->Init();
3848 function &GetArray($nRows=-1)
3850 if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
3851 return $this->_array;
3852 } else {
3853 $arr =& ADORecordSet::GetArray($nRows);
3854 return $arr;
3858 function _initrs()
3860 $this->_numOfRows = sizeof($this->_array);
3861 if ($this->_skiprow1) $this->_numOfRows -= 1;
3863 $this->_numOfFields =(isset($this->_fieldobjects)) ?
3864 sizeof($this->_fieldobjects):sizeof($this->_types);
3867 /* Use associative array to get fields array */
3868 function Fields($colname)
3870 $mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode;
3872 if ($mode & ADODB_FETCH_ASSOC) {
3873 if (!isset($this->fields[$colname]) && !is_null($this->fields[$colname])) $colname = strtolower($colname);
3874 return $this->fields[$colname];
3876 if (!$this->bind) {
3877 $this->bind = array();
3878 for ($i=0; $i < $this->_numOfFields; $i++) {
3879 $o = $this->FetchField($i);
3880 $this->bind[strtoupper($o->name)] = $i;
3883 return $this->fields[$this->bind[strtoupper($colname)]];
3886 function &FetchField($fieldOffset = -1)
3888 if (isset($this->_fieldobjects)) {
3889 return $this->_fieldobjects[$fieldOffset];
3891 $o = new ADOFieldObject();
3892 $o->name = $this->_colnames[$fieldOffset];
3893 $o->type = $this->_types[$fieldOffset];
3894 $o->max_length = -1; // length not known
3896 return $o;
3899 function _seek($row)
3901 if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
3902 $this->_currentRow = $row;
3903 if ($this->_skiprow1) $row += 1;
3904 $this->fields = $this->_array[$row];
3905 return true;
3907 return false;
3910 function MoveNext()
3912 if (!$this->EOF) {
3913 $this->_currentRow++;
3915 $pos = $this->_currentRow;
3917 if ($this->_numOfRows <= $pos) {
3918 if (!$this->compat) $this->fields = false;
3919 } else {
3920 if ($this->_skiprow1) $pos += 1;
3921 $this->fields = $this->_array[$pos];
3922 return true;
3924 $this->EOF = true;
3927 return false;
3930 function _fetch()
3932 $pos = $this->_currentRow;
3934 if ($this->_numOfRows <= $pos) {
3935 if (!$this->compat) $this->fields = false;
3936 return false;
3938 if ($this->_skiprow1) $pos += 1;
3939 $this->fields = $this->_array[$pos];
3940 return true;
3943 function _close()
3945 return true;
3948 } // ADORecordSet_array
3950 //==============================================================================================
3951 // HELPER FUNCTIONS
3952 //==============================================================================================
3955 * Synonym for ADOLoadCode. Private function. Do not use.
3957 * @deprecated
3959 function ADOLoadDB($dbType)
3961 return ADOLoadCode($dbType);
3965 * Load the code for a specific database driver. Private function. Do not use.
3967 function ADOLoadCode($dbType)
3969 global $ADODB_LASTDB;
3971 if (!$dbType) return false;
3972 $db = strtolower($dbType);
3973 switch ($db) {
3974 case 'ado':
3975 if (PHP_VERSION >= 5) $db = 'ado5';
3976 $class = 'ado';
3977 break;
3978 case 'ifx':
3979 case 'maxsql': $class = $db = 'mysqlt'; break;
3980 case 'postgres':
3981 case 'postgres8':
3982 case 'pgsql': $class = $db = 'postgres7'; break;
3983 default:
3984 $class = $db; break;
3987 $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
3988 @include_once($file);
3989 $ADODB_LASTDB = $class;
3990 if (class_exists("ADODB_" . $class)) return $class;
3992 //ADOConnection::outp(adodb_pr(get_declared_classes(),true));
3993 if (!file_exists($file)) ADOConnection::outp("Missing file: $file");
3994 else ADOConnection::outp("Syntax error in file: $file");
3995 return false;
3999 * synonym for ADONewConnection for people like me who cannot remember the correct name
4001 function &NewADOConnection($db='')
4003 $tmp =& ADONewConnection($db);
4004 return $tmp;
4008 * Instantiate a new Connection class for a specific database driver.
4010 * @param [db] is the database Connection object to create. If undefined,
4011 * use the last database driver that was loaded by ADOLoadCode().
4013 * @return the freshly created instance of the Connection class.
4015 function &ADONewConnection($db='')
4017 GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
4019 if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
4020 $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
4021 $false = false;
4022 if ($at = strpos($db,'://')) {
4023 $origdsn = $db;
4024 if (PHP_VERSION < 5) $dsna = @parse_url($db);
4025 else {
4026 $fakedsn = 'fake'.substr($db,$at);
4027 $dsna = @parse_url($fakedsn);
4028 $dsna['scheme'] = substr($db,0,$at);
4030 if (strncmp($db,'pdo',3) == 0) {
4031 $sch = explode('_',$dsna['scheme']);
4032 if (sizeof($sch)>1) {
4033 $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
4034 $dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host']));
4035 $dsna['scheme'] = 'pdo';
4040 if (!$dsna) {
4041 // special handling of oracle, which might not have host
4042 $db = str_replace('@/','@adodb-fakehost/',$db);
4043 $dsna = parse_url($db);
4044 if (!$dsna) return $false;
4045 $dsna['host'] = '';
4047 $db = @$dsna['scheme'];
4048 if (!$db) return $false;
4049 $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
4050 $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : '';
4051 $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : '';
4052 $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial /
4054 if (isset($dsna['query'])) {
4055 $opt1 = explode('&',$dsna['query']);
4056 foreach($opt1 as $k => $v) {
4057 $arr = explode('=',$v);
4058 $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1;
4060 } else $opt = array();
4063 * phptype: Database backend used in PHP (mysql, odbc etc.)
4064 * dbsyntax: Database used with regards to SQL syntax etc.
4065 * protocol: Communication protocol to use (tcp, unix etc.)
4066 * hostspec: Host specification (hostname[:port])
4067 * database: Database to use on the DBMS server
4068 * username: User name for login
4069 * password: Password for login
4071 if (!empty($ADODB_NEWCONNECTION)) {
4072 $obj = $ADODB_NEWCONNECTION($db);
4074 } else {
4076 if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
4077 if (empty($db)) $db = $ADODB_LASTDB;
4079 if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
4081 if (!$db) {
4082 if (isset($origdsn)) $db = $origdsn;
4083 if ($errorfn) {
4084 // raise an error
4085 $ignore = false;
4086 $errorfn('ADONewConnection', 'ADONewConnection', -998,
4087 "could not load the database driver for '$db'",
4088 $db,false,$ignore);
4089 } else
4090 ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
4092 return $false;
4095 $cls = 'ADODB_'.$db;
4096 if (!class_exists($cls)) {
4097 adodb_backtrace();
4098 return $false;
4101 $obj = new $cls();
4104 # constructor should not fail
4105 if ($obj) {
4106 if ($errorfn) $obj->raiseErrorFn = $errorfn;
4107 if (isset($dsna)) {
4108 if (isset($dsna['port'])) $obj->port = $dsna['port'];
4109 foreach($opt as $k => $v) {
4110 switch(strtolower($k)) {
4111 case 'new':
4112 $nconnect = true; $persist = true; break;
4113 case 'persist':
4114 case 'persistent': $persist = $v; break;
4115 case 'debug': $obj->debug = (integer) $v; break;
4116 #ibase
4117 case 'role': $obj->role = $v; break;
4118 case 'dialect': $obj->dialect = (integer) $v; break;
4119 case 'charset': $obj->charset = $v; $obj->charSet=$v; break;
4120 case 'buffers': $obj->buffers = $v; break;
4121 case 'fetchmode': $obj->SetFetchMode($v); break;
4122 #ado
4123 case 'charpage': $obj->charPage = $v; break;
4124 #mysql, mysqli
4125 case 'clientflags': $obj->clientFlags = $v; break;
4126 #mysql, mysqli, postgres
4127 case 'port': $obj->port = $v; break;
4128 #mysqli
4129 case 'socket': $obj->socket = $v; break;
4130 #oci8
4131 case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break;
4134 if (empty($persist))
4135 $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
4136 else if (empty($nconnect))
4137 $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
4138 else
4139 $ok = $obj->NConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
4141 if (!$ok) return $false;
4144 return $obj;
4149 // $perf == true means called by NewPerfMonitor(), otherwise for data dictionary
4150 function _adodb_getdriver($provider,$drivername,$perf=false)
4152 switch ($provider) {
4153 case 'odbtp': if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6);
4154 case 'odbc' : if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5);
4155 case 'ado' : if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4);
4156 case 'native': break;
4157 default:
4158 return $provider;
4161 switch($drivername) {
4162 case 'mysqlt':
4163 case 'mysqli':
4164 $drivername='mysql';
4165 break;
4166 case 'postgres7':
4167 case 'postgres8':
4168 $drivername = 'postgres';
4169 break;
4170 case 'firebird15': $drivername = 'firebird'; break;
4171 case 'oracle': $drivername = 'oci8'; break;
4172 case 'access': if ($perf) $drivername = ''; break;
4173 case 'db2' : break;
4174 case 'sapdb' : break;
4175 default:
4176 $drivername = 'generic';
4177 break;
4179 return $drivername;
4182 function &NewPerfMonitor(&$conn)
4184 $false = false;
4185 $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
4186 if (!$drivername || $drivername == 'generic') return $false;
4187 include_once(ADODB_DIR.'/adodb-perf.inc.php');
4188 @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
4189 $class = "Perf_$drivername";
4190 if (!class_exists($class)) return $false;
4191 $perf = new $class($conn);
4193 return $perf;
4196 function &NewDataDictionary(&$conn,$drivername=false)
4198 $false = false;
4199 if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
4201 include_once(ADODB_DIR.'/adodb-lib.inc.php');
4202 include_once(ADODB_DIR.'/adodb-datadict.inc.php');
4203 $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
4205 if (!file_exists($path)) {
4206 ADOConnection::outp("Dictionary driver '$path' not available");
4207 return $false;
4209 include_once($path);
4210 $class = "ADODB2_$drivername";
4211 $dict = new $class();
4212 $dict->dataProvider = $conn->dataProvider;
4213 $dict->connection = &$conn;
4214 $dict->upperName = strtoupper($drivername);
4215 $dict->quote = $conn->nameQuote;
4216 if (!empty($conn->_connectionID))
4217 $dict->serverInfo = $conn->ServerInfo();
4219 return $dict;
4225 Perform a print_r, with pre tags for better formatting.
4227 function adodb_pr($var,$as_string=false)
4229 if ($as_string) ob_start();
4231 if (isset($_SERVER['HTTP_USER_AGENT'])) {
4232 echo " <pre>\n";print_r($var);echo "</pre>\n";
4233 } else
4234 print_r($var);
4236 if ($as_string) {
4237 $s = ob_get_contents();
4238 ob_end_clean();
4239 return $s;
4244 Perform a stack-crawl and pretty print it.
4246 @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
4247 @param levels Number of levels to display
4249 function adodb_backtrace($printOrArr=true,$levels=9999)
4251 global $ADODB_INCLUDED_LIB;
4252 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
4253 return _adodb_backtrace($printOrArr,$levels);