added ending dates of service
[openemr.git] / library / adodb / adodb.inc.php
blob4a0efd204e95826d4338743f5e0c815a237bfc51
1 <?php
2 /*
3 * Set tabs to 4 for best viewing.
4 *
5 * Latest version is available at http://php.weblogs.com/adodb
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.20 22 Feb 2004 (c) 2000-2004 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://php.weblogs.com/adodb<br>
32 Manual is at http://php.weblogs.com/adodb_manual
36 if (!defined('_ADODB_LAYER')) {
37 define('_ADODB_LAYER',1);
39 //==============================================================================================
40 // CONSTANT DEFINITIONS
41 //==============================================================================================
44 /**
45 * Set ADODB_DIR to the directory where this file resides...
46 * This constant was formerly called $ADODB_RootPath
48 if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
50 //==============================================================================================
51 // GLOBAL VARIABLES
52 //==============================================================================================
54 GLOBAL
55 $ADODB_vers, // database version
56 $ADODB_COUNTRECS, // count number of records returned - slows down query
57 $ADODB_CACHE_DIR, // directory to cache recordsets
58 $ADODB_EXTENSION, // ADODB extension installed
59 $ADODB_COMPAT_PATCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
60 $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
62 //==============================================================================================
63 // GLOBAL SETUP
64 //==============================================================================================
66 $ADODB_EXTENSION = defined('ADODB_EXTENSION');
67 if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
69 define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
71 // allow [ ] @ ` " and . in table names
72 define('ADODB_TABLE_REGEX','([]0-9a-z_\"\`\.\@\[-]*)');
74 // prefetching used by oracle
75 if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
79 Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
80 This currently works only with mssql, odbc, oci8po and ibase derived drivers.
82 0 = assoc lowercase field names. $rs->fields['orderid']
83 1 = assoc uppercase field names. $rs->fields['ORDERID']
84 2 = use native-case field names. $rs->fields['OrderID']
87 define('ADODB_FETCH_DEFAULT',0);
88 define('ADODB_FETCH_NUM',1);
89 define('ADODB_FETCH_ASSOC',2);
90 define('ADODB_FETCH_BOTH',3);
92 if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
94 if (strnatcmp(PHP_VERSION,'4.3.0')>=0) {
95 define('ADODB_PHPVER',0x4300);
96 } else if (strnatcmp(PHP_VERSION,'4.2.0')>=0) {
97 define('ADODB_PHPVER',0x4200);
98 } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
99 define('ADODB_PHPVER',0x4050);
100 } else {
101 define('ADODB_PHPVER',0x4000);
105 //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
109 Accepts $src and $dest arrays, replacing string $data
111 function ADODB_str_replace($src, $dest, $data)
113 if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
115 $s = reset($src);
116 $d = reset($dest);
117 while ($s !== false) {
118 $data = str_replace($s,$d,$data);
119 $s = next($src);
120 $d = next($dest);
122 return $data;
125 function ADODB_Setup()
127 GLOBAL
128 $ADODB_vers, // database version
129 $ADODB_COUNTRECS, // count number of records returned - slows down query
130 $ADODB_CACHE_DIR, // directory to cache recordsets
131 $ADODB_FETCH_MODE;
133 $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
135 if (!isset($ADODB_CACHE_DIR)) {
136 $ADODB_CACHE_DIR = '/tmp';
137 } else {
138 // do not accept url based paths, eg. http:/ or ftp:/
139 if (strpos($ADODB_CACHE_DIR,'://') !== false)
140 die("Illegal path http:// or ftp://");
144 // Initialize random number generator for randomizing cache flushes
145 srand(((double)microtime())*1000000);
148 * ADODB version as a string.
150 $ADODB_vers = 'V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
153 * Determines whether recordset->RecordCount() is used.
154 * Set to false for highest performance -- RecordCount() will always return -1 then
155 * for databases that provide "virtual" recordcounts...
157 if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
161 //==============================================================================================
162 // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
163 //==============================================================================================
165 ADODB_Setup();
167 //==============================================================================================
168 // CLASS ADOFieldObject
169 //==============================================================================================
171 * Helper class for FetchFields -- holds info on a column
173 class ADOFieldObject {
174 var $name = '';
175 var $max_length=0;
176 var $type="";
178 // additional fields by dannym... (danny_milo@yahoo.com)
179 var $not_null = false;
180 // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
181 // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
183 var $has_default = false; // this one I have done only in mysql and postgres for now ...
184 // others to come (dannym)
185 var $default_value; // default, if any, and supported. Check has_default first.
190 function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
192 //print "Errorno ($fn errno=$errno m=$errmsg) ";
193 $thisConnection->_transOK = false;
194 if ($thisConnection->_oldRaiseFn) {
195 $fn = $thisConnection->_oldRaiseFn;
196 $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
200 //==============================================================================================
201 // CLASS ADOConnection
202 //==============================================================================================
205 * Connection object. For connecting to databases, and executing queries.
207 class ADOConnection {
209 // PUBLIC VARS
211 var $dataProvider = 'native';
212 var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
213 var $database = ''; /// Name of database to be used.
214 var $host = ''; /// The hostname of the database server
215 var $user = ''; /// The username which is used to connect to the database server.
216 var $password = ''; /// Password for the username. For security, we no longer store it.
217 var $debug = false; /// if set to true will output sql statements
218 var $maxblobsize = 256000; /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro
219 var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
220 var $substr = 'substr'; /// substring operator
221 var $length = 'length'; /// string length operator
222 var $random = 'rand()'; /// random function
223 var $upperCase = false; /// uppercase function
224 var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
225 var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
226 var $true = '1'; /// string that represents TRUE for a database
227 var $false = '0'; /// string that represents FALSE for a database
228 var $replaceQuote = "\\'"; /// string to use to replace quotes
229 var $nameQuote = '"'; /// string to use to quote identifiers and names
230 var $charSet=false; /// character set to use - only for interbase
231 var $metaDatabasesSQL = '';
232 var $metaTablesSQL = '';
233 var $uniqueOrderBy = false; /// All order by columns have to be unique
234 var $emptyDate = '&nbsp;';
235 var $emptyTimeStamp = '&nbsp;';
236 var $lastInsID = false;
237 //--
238 var $hasInsertID = false; /// supports autoincrement ID?
239 var $hasAffectedRows = false; /// supports affected rows for update/delete?
240 var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
241 var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
242 var $readOnly = false; /// this is a readonly database - used by phpLens
243 var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
244 var $hasGenID = false; /// can generate sequences using GenID();
245 var $hasTransactions = true; /// has transactions
246 //--
247 var $genID = 0; /// sequence id used by GenID();
248 var $raiseErrorFn = false; /// error function to call
249 var $isoDates = false; /// accepts dates in ISO format
250 var $cacheSecs = 3600; /// cache for 1 hour
251 var $sysDate = false; /// name of function that returns the current date
252 var $sysTimeStamp = false; /// name of function that returns the current timestamp
253 var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
255 var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
256 var $numCacheHits = 0;
257 var $numCacheMisses = 0;
258 var $pageExecuteCountRows = true;
259 var $uniqueSort = false; /// indicates that all fields in order by must be unique
260 var $leftOuter = false; /// operator to use for left outer join in WHERE clause
261 var $rightOuter = false; /// operator to use for right outer join in WHERE clause
262 var $ansiOuter = false; /// whether ansi outer join syntax supported
263 var $autoRollback = false; // autoRollback on PConnect().
264 var $poorAffectedRows = false; // affectedRows not working or unreliable
266 var $fnExecute = false;
267 var $fnCacheExecute = false;
268 var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
269 var $rsPrefix = "ADORecordSet_";
271 var $autoCommit = true; /// do not modify this yourself - actually private
272 var $transOff = 0; /// temporarily disable transactions
273 var $transCnt = 0; /// count of nested transactions
275 var $fetchMode=false;
277 // PRIVATE VARS
279 var $_oldRaiseFn = false;
280 var $_transOK = null;
281 var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
282 var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
283 /// then returned by the errorMsg() function
284 var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
285 var $_queryID = false; /// This variable keeps the last created result link identifier
287 var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
288 var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
289 var $_evalAll = false;
290 var $_affected = false;
291 var $_logsql = false;
296 * Constructor
298 function ADOConnection()
300 die('Virtual Class -- cannot instantiate');
304 Get server version info...
306 @returns An array with 2 elements: $arr['string'] is the description string,
307 and $arr[version] is the version (also a string).
309 function ServerInfo()
311 return array('description' => '', 'version' => '');
314 function _findvers($str)
316 if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
317 else return '';
321 * All error messages go through this bottleneck function.
322 * You can define your own handler by defining the function name in ADODB_OUTP.
324 function outp($msg,$newline=true)
326 global $HTTP_SERVER_VARS,$ADODB_FLUSH;
328 if (defined('ADODB_OUTP')) {
329 $fn = ADODB_OUTP;
330 $fn($msg,$newline);
331 return;
334 if ($newline) $msg .= "<br>\n";
336 if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg;
337 else echo strip_tags($msg);
338 if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // dp not flush if output buffering enabled - useless - thx to Jesse Mullan
343 * Connect to database
345 * @param [argHostname] Host to connect to
346 * @param [argUsername] Userid to login
347 * @param [argPassword] Associated password
348 * @param [argDatabaseName] database
349 * @param [forceNew] force new connection
351 * @return true or false
353 function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
355 if ($argHostname != "") $this->host = $argHostname;
356 if ($argUsername != "") $this->user = $argUsername;
357 if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
358 if ($argDatabaseName != "") $this->database = $argDatabaseName;
360 $this->_isPersistentConnection = false;
361 if ($fn = $this->raiseErrorFn) {
362 if ($forceNew) {
363 if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
364 } else {
365 if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
367 $err = $this->ErrorMsg();
368 if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
369 $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
370 } else {
371 if ($forceNew) {
372 if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
373 } else {
374 if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
377 if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());
378 return false;
381 function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
383 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
388 * Always force a new connection to database - currently only works with oracle
390 * @param [argHostname] Host to connect to
391 * @param [argUsername] Userid to login
392 * @param [argPassword] Associated password
393 * @param [argDatabaseName] database
395 * @return true or false
397 function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
399 return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
403 * Establish persistent connect to database
405 * @param [argHostname] Host to connect to
406 * @param [argUsername] Userid to login
407 * @param [argPassword] Associated password
408 * @param [argDatabaseName] database
410 * @return return true or false
412 function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
414 if (defined('ADODB_NEVER_PERSIST'))
415 return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
417 if ($argHostname != "") $this->host = $argHostname;
418 if ($argUsername != "") $this->user = $argUsername;
419 if ($argPassword != "") $this->password = $argPassword;
420 if ($argDatabaseName != "") $this->database = $argDatabaseName;
422 $this->_isPersistentConnection = true;
424 if ($fn = $this->raiseErrorFn) {
425 if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
426 $err = $this->ErrorMsg();
427 if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
428 $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
429 } else
430 if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
432 if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());
433 return false;
436 // Format date column in sql string given an input format that understands Y M D
437 function SQLDate($fmt, $col=false)
439 if (!$col) $col = $this->sysDate;
440 return $col; // child class implement
444 * Should prepare the sql statement and return the stmt resource.
445 * For databases that do not support this, we return the $sql. To ensure
446 * compatibility with databases that do not support prepare:
448 * $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
449 * $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
450 * $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
452 * @param sql SQL to send to database
454 * @return return FALSE, or the prepared statement, or the original sql if
455 * if the database does not support prepare.
458 function Prepare($sql)
460 return $sql;
464 * Some databases, eg. mssql require a different function for preparing
465 * stored procedures. So we cannot use Prepare().
467 * Should prepare the stored procedure and return the stmt resource.
468 * For databases that do not support this, we return the $sql. To ensure
469 * compatibility with databases that do not support prepare:
471 * @param sql SQL to send to database
473 * @return return FALSE, or the prepared statement, or the original sql if
474 * if the database does not support prepare.
477 function PrepareSP($sql,$param=false)
479 return $this->Prepare($sql,$param);
483 * PEAR DB Compat
485 function Quote($s)
487 return $this->qstr($s,false);
491 Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
493 function QMagic($s)
495 return $this->qstr($s,get_magic_quotes_gpc());
498 function q(&$s)
500 $s = $this->qstr($s,false);
504 * PEAR DB Compat - do not use internally.
506 function ErrorNative()
508 return $this->ErrorNo();
513 * PEAR DB Compat - do not use internally.
515 function nextId($seq_name)
517 return $this->GenID($seq_name);
521 * Lock a row, will escalate and lock the table if row locking not supported
522 * will normally free the lock at the end of the transaction
524 * @param $table name of table to lock
525 * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
527 function RowLock($table,$where)
529 return false;
532 function CommitLock($table)
534 return $this->CommitTrans();
537 function RollbackLock($table)
539 return $this->RollbackTrans();
543 * PEAR DB Compat - do not use internally.
545 * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
546 * for easy porting :-)
548 * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
549 * @returns The previous fetch mode
551 function SetFetchMode($mode)
553 $old = $this->fetchMode;
554 $this->fetchMode = $mode;
556 if ($old === false) {
557 global $ADODB_FETCH_MODE;
558 return $ADODB_FETCH_MODE;
560 return $old;
565 * PEAR DB Compat - do not use internally.
567 function &Query($sql, $inputarr=false)
569 $rs = &$this->Execute($sql, $inputarr);
570 if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
571 return $rs;
576 * PEAR DB Compat - do not use internally
578 function &LimitQuery($sql, $offset, $count, $params=false)
580 $rs = &$this->SelectLimit($sql, $count, $offset, $params);
581 if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
582 return $rs;
587 * PEAR DB Compat - do not use internally
589 function Disconnect()
591 return $this->Close();
595 Returns placeholder for parameter, eg.
596 $DB->Param('a')
598 will return ':a' for Oracle, and '?' for most other databases...
600 For databases that require positioned params, eg $1, $2, $3 for postgresql,
601 pass in Param(false) before setting the first parameter.
603 function Param($name)
605 return '?';
609 InParameter and OutParameter are self-documenting versions of Parameter().
611 function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
613 return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
618 function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
620 return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
625 Usage in oracle
626 $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
627 $db->Parameter($stmt,$id,'myid');
628 $db->Parameter($stmt,$group,'group',64);
629 $db->Execute();
631 @param $stmt Statement returned by Prepare() or PrepareSP().
632 @param $var PHP variable to bind to
633 @param $name Name of stored procedure variable name to bind to.
634 @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
635 @param [$maxLen] Holds an maximum length of the variable.
636 @param [$type] The data type of $var. Legal values depend on driver.
639 function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
641 return false;
645 Improved method of initiating a transaction. Used together with CompleteTrans().
646 Advantages include:
648 a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
649 Only the outermost block is treated as a transaction.<br>
650 b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
651 c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
652 are disabled, making it backward compatible.
654 function StartTrans($errfn = 'ADODB_TransMonitor')
656 if ($this->transOff > 0) {
657 $this->transOff += 1;
658 return;
661 $this->_oldRaiseFn = $this->raiseErrorFn;
662 $this->raiseErrorFn = $errfn;
663 $this->_transOK = true;
665 if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
666 $this->BeginTrans();
667 $this->transOff = 1;
671 Used together with StartTrans() to end a transaction. Monitors connection
672 for sql errors, and will commit or rollback as appropriate.
674 @autoComplete if true, monitor sql errors and commit and rollback as appropriate,
675 and if set to false force rollback even if no SQL error detected.
676 @returns true on commit, false on rollback.
678 function CompleteTrans($autoComplete = true)
680 if ($this->transOff > 1) {
681 $this->transOff -= 1;
682 return true;
684 $this->raiseErrorFn = $this->_oldRaiseFn;
686 $this->transOff = 0;
687 if ($this->_transOK && $autoComplete) {
688 if (!$this->CommitTrans()) {
689 $this->_transOK = false;
690 if ($this->debug) ADOConnection::outp("Smart Commit failed");
691 } else
692 if ($this->debug) ADOConnection::outp("Smart Commit occurred");
693 } else {
694 $this->RollbackTrans();
695 if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
698 return $this->_transOK;
702 At the end of a StartTrans/CompleteTrans block, perform a rollback.
704 function FailTrans()
706 if ($this->debug)
707 if ($this->transOff == 0) {
708 ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
709 } else {
710 ADOConnection::outp("FailTrans was called");
711 adodb_backtrace();
713 $this->_transOK = false;
717 Check if transaction has failed, only for Smart Transactions.
719 function HasFailedTrans()
721 if ($this->transOff > 0) return $this->_transOK == false;
722 return false;
726 * Execute SQL
728 * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
729 * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
730 * @return RecordSet or false
732 function &Execute($sql,$inputarr=false)
734 if ($this->fnExecute) {
735 $fn = $this->fnExecute;
736 $ret =& $fn($this,$sql,$inputarr);
737 if (isset($ret)) return $ret;
739 if ($inputarr && is_array($inputarr)) {
740 $element0 = reset($inputarr);
741 # is_object check is because oci8 descriptors can be passed in
742 $array_2d = is_array($element0) && !is_object(reset($element0));
744 if (!is_array($sql) && !$this->_bindInputArray) {
745 $sqlarr = explode('?',$sql);
747 if (!$array_2d) $inputarr = array($inputarr);
748 foreach($inputarr as $arr) {
749 $sql = ''; $i = 0;
750 foreach($arr as $v) {
751 $sql .= $sqlarr[$i];
752 // from Ron Baldwin <ron.baldwin@sourceprose.com>
753 // Only quote string types
754 if (gettype($v) == 'string')
755 $sql .= $this->qstr($v);
756 else if ($v === null)
757 $sql .= 'NULL';
758 else
759 $sql .= $v;
760 $i += 1;
762 $sql .= $sqlarr[$i];
764 if ($i+1 != sizeof($sqlarr))
765 ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
767 $ret =& $this->_Execute($sql,false);
768 if (!$ret) return $ret;
770 } else {
771 if ($array_2d) {
772 $stmt = $this->Prepare($sql);
773 foreach($inputarr as $arr) {
774 $ret =& $this->_Execute($stmt,$arr);
775 if (!$ret) return $ret;
777 } else
778 $ret =& $this->_Execute($sql,$inputarr);
780 } else {
781 $ret =& $this->_Execute($sql,false);
784 return $ret;
787 function& _Execute($sql,$inputarr=false)
789 // debug version of query
790 if ($this->debug) {
791 global $HTTP_SERVER_VARS;
792 $ss = '';
793 if ($inputarr) {
794 foreach($inputarr as $kk=>$vv) {
795 if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
796 $ss .= "($kk=>'$vv') ";
798 $ss = "[ $ss ]";
800 $sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql);
802 // check if running from browser or command-line
803 $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
805 if ($inBrowser)
806 if ($this->debug === -1)
807 ADOConnection::outp( "<br>\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<br>\n",false);
808 else ADOConnection::outp( "<hr />\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<hr />\n",false);
809 else
810 ADOConnection::outp( "=----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false);
812 $this->_queryID = $this->_query($sql,$inputarr);
814 Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
815 because ErrorNo() calls Execute('SELECT @ERROR'), causing recure
817 if ($this->databaseType == 'mssql') {
818 // ErrorNo is a slow function call in mssql, and not reliable
819 // in PHP 4.0.6
820 if($emsg = $this->ErrorMsg()) {
821 $err = $this->ErrorNo();
822 if ($err) {
823 ADOConnection::outp($err.': '.$emsg);
826 } else
827 if (!$this->_queryID) {
828 $e = $this->ErrorNo();
829 $m = $this->ErrorMsg();
830 ADOConnection::outp($e .': '. $m );
832 } else {
833 // non-debug version of query
835 $this->_queryID =@$this->_query($sql,$inputarr);
838 /************************
839 OK, query executed
840 *************************/
841 // error handling if query fails
842 if ($this->_queryID === false) {
843 if ($this->debug == 99) adodb_backtrace(true,5);
844 $fn = $this->raiseErrorFn;
845 if ($fn) {
846 $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
849 return false;
850 } else if ($this->_queryID === true) {
851 // return simplified empty recordset for inserts/updates/deletes with lower overhead
852 $rs =& new ADORecordSet_empty();
853 return $rs;
856 // return real recordset from select statement
857 $rsclass = $this->rsPrefix.$this->databaseType;
858 $rs =& new $rsclass($this->_queryID,$this->fetchMode); // &new not supported by older PHP versions
859 $rs->connection = &$this; // Pablo suggestion
860 $rs->Init();
861 if (is_array($sql)) $rs->sql = $sql[0];
862 else $rs->sql = $sql;
863 if ($rs->_numOfRows <= 0) {
864 global $ADODB_COUNTRECS;
866 if ($ADODB_COUNTRECS) {
867 if (!$rs->EOF){
868 $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
869 $rs->_queryID = $this->_queryID;
870 } else
871 $rs->_numOfRows = 0;
874 return $rs;
877 function CreateSequence($seqname='adodbseq',$startID=1)
879 if (empty($this->_genSeqSQL)) return false;
880 return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
883 function DropSequence($seqname)
885 if (empty($this->_dropSeqSQL)) return false;
886 return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
890 * Generates a sequence id and stores it in $this->genID;
891 * GenID is only available if $this->hasGenID = true;
893 * @param seqname name of sequence to use
894 * @param startID if sequence does not exist, start at this ID
895 * @return 0 if not supported, otherwise a sequence id
897 function GenID($seqname='adodbseq',$startID=1)
899 if (!$this->hasGenID) {
900 return 0; // formerly returns false pre 1.60
903 $getnext = sprintf($this->_genIDSQL,$seqname);
905 $holdtransOK = $this->_transOK;
906 $rs = @$this->Execute($getnext);
907 if (!$rs) {
908 $this->_transOK = $holdtransOK; //if the status was ok before reset
909 $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
910 $rs = $this->Execute($getnext);
912 if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
913 else $this->genID = 0; // false
915 if ($rs) $rs->Close();
917 return $this->genID;
921 * @return the last inserted ID. Not all databases support this.
923 function Insert_ID()
925 if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
926 if ($this->hasInsertID) return $this->_insertid();
927 if ($this->debug) {
928 ADOConnection::outp( '<p>Insert_ID error</p>');
929 adodb_backtrace();
931 return false;
936 * Portable Insert ID. Pablo Roca <pabloroca@mvps.org>
938 * @return the last inserted ID. All databases support this. But aware possible
939 * problems in multiuser environments. Heavy test this before deploying.
941 function PO_Insert_ID($table="", $id="")
943 if ($this->hasInsertID){
944 return $this->Insert_ID();
945 } else {
946 return $this->GetOne("SELECT MAX($id) FROM $table");
951 * @return # rows affected by UPDATE/DELETE
953 function Affected_Rows()
955 if ($this->hasAffectedRows) {
956 if ($this->fnExecute === 'adodb_log_sql') {
957 if ($this->_logsql && $this->_affected !== false) return $this->_affected;
959 $val = $this->_affectedrows();
960 return ($val < 0) ? false : $val;
963 if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
964 return false;
969 * @return the last error message
971 function ErrorMsg()
973 return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
978 * @return the last error number. Normally 0 means no error.
980 function ErrorNo()
982 return ($this->_errorMsg) ? -1 : 0;
985 function MetaError($err=false)
987 include_once(ADODB_DIR."/adodb-error.inc.php");
988 if ($err === false) $err = $this->ErrorNo();
989 return adodb_error($this->dataProvider,$this->databaseType,$err);
992 function MetaErrorMsg($errno)
994 include_once(ADODB_DIR."/adodb-error.inc.php");
995 return adodb_errormsg($errno);
999 * @returns an array with the primary key columns in it.
1001 function MetaPrimaryKeys($table, $owner=false)
1003 // owner not used in base class - see oci8
1004 $p = array();
1005 $objs =& $this->MetaColumns($table);
1006 if ($objs) {
1007 foreach($objs as $v) {
1008 if (!empty($v->primary_key))
1009 $p[] = $v->name;
1012 if (sizeof($p)) return $p;
1013 if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
1014 return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
1015 return false;
1019 * @returns assoc array where keys are tables, and values are foreign keys
1021 function MetaForeignKeys($table, $owner=false, $upper=false)
1023 return false;
1026 * Choose a database to connect to. Many databases do not support this.
1028 * @param dbName is the name of the database to select
1029 * @return true or false
1031 function SelectDB($dbName)
1032 {return false;}
1036 * Will select, getting rows from $offset (1-based), for $nrows.
1037 * This simulates the MySQL "select * from table limit $offset,$nrows" , and
1038 * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
1039 * MySQL and PostgreSQL parameter ordering is the opposite of the other.
1040 * eg.
1041 * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
1042 * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
1044 * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
1045 * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
1047 * @param sql
1048 * @param [offset] is the row to start calculations from (1-based)
1049 * @param [nrows] is the number of rows to get
1050 * @param [inputarr] array of bind variables
1051 * @param [secs2cache] is a private parameter only used by jlim
1052 * @return the recordset ($rs->databaseType == 'array')
1054 function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
1056 if ($this->hasTop && $nrows > 0) {
1057 // suggested by Reinhard Balling. Access requires top after distinct
1058 // Informix requires first before distinct - F Riosa
1059 $ismssql = (strpos($this->databaseType,'mssql') !== false);
1060 if ($ismssql) $isaccess = false;
1061 else $isaccess = (strpos($this->databaseType,'access') !== false);
1063 if ($offset <= 0) {
1065 // access includes ties in result
1066 if ($isaccess) {
1067 $sql = preg_replace(
1068 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
1070 if ($secs2cache>0) {
1071 $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
1072 } else {
1073 $ret =& $this->Execute($sql,$inputarr);
1075 return $ret; // PHP5 fix
1076 } else if ($ismssql){
1077 $sql = preg_replace(
1078 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
1079 } else {
1080 $sql = preg_replace(
1081 '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
1083 } else {
1084 $nn = $nrows + $offset;
1085 if ($isaccess || $ismssql) {
1086 $sql = preg_replace(
1087 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
1088 } else {
1089 $sql = preg_replace(
1090 '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
1095 // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
1096 // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
1097 global $ADODB_COUNTRECS;
1099 $savec = $ADODB_COUNTRECS;
1100 $ADODB_COUNTRECS = false;
1102 if ($offset>0){
1103 if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
1104 else $rs = &$this->Execute($sql,$inputarr);
1105 } else {
1106 if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
1107 else $rs = &$this->Execute($sql,$inputarr);
1109 $ADODB_COUNTRECS = $savec;
1110 if ($rs && !$rs->EOF) {
1111 $rs =& $this->_rs2rs($rs,$nrows,$offset);
1113 //print_r($rs);
1114 return $rs;
1118 * Create serializable recordset. Breaks rs link to connection.
1120 * @param rs the recordset to serialize
1122 function &SerializableRS(&$rs)
1124 $rs2 =& $this->_rs2rs($rs);
1125 $ignore = false;
1126 $rs2->connection =& $ignore;
1128 return $rs2;
1132 * Convert database recordset to an array recordset
1133 * input recordset's cursor should be at beginning, and
1134 * old $rs will be closed.
1136 * @param rs the recordset to copy
1137 * @param [nrows] number of rows to retrieve (optional)
1138 * @param [offset] offset by number of rows (optional)
1139 * @return the new recordset
1141 function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
1143 if (! $rs) return false;
1145 $dbtype = $rs->databaseType;
1146 if (!$dbtype) {
1147 $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
1148 return $rs;
1150 if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
1151 $rs->MoveFirst();
1152 $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
1153 return $rs;
1155 $flds = array();
1156 for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
1157 $flds[] = $rs->FetchField($i);
1159 $arr =& $rs->GetArrayLimit($nrows,$offset);
1160 //print_r($arr);
1161 if ($close) $rs->Close();
1163 $arrayClass = $this->arrayClass;
1165 $rs2 =& new $arrayClass();
1166 $rs2->connection = &$this;
1167 $rs2->sql = $rs->sql;
1168 $rs2->dataProvider = $this->dataProvider;
1169 $rs2->InitArrayFields($arr,$flds);
1170 return $rs2;
1174 * Return all rows. Compat with PEAR DB
1176 function &GetAll($sql, $inputarr=false)
1178 $arr =& $this->GetArray($sql,$inputarr);
1179 return $arr;
1182 function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
1184 $rs =& $this->Execute($sql, $inputarr);
1185 if (!$rs) return false;
1187 $arr =& $rs->GetAssoc($force_array,$first2cols);
1188 return $arr;
1191 function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
1193 if (!is_numeric($secs2cache)) {
1194 $first2cols = $force_array;
1195 $force_array = $inputarr;
1197 $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);
1198 if (!$rs) return false;
1200 $arr =& $rs->GetAssoc($force_array,$first2cols);
1201 return $arr;
1205 * Return first element of first row of sql statement. Recordset is disposed
1206 * for you.
1208 * @param sql SQL statement
1209 * @param [inputarr] input bind array
1211 function GetOne($sql,$inputarr=false)
1213 global $ADODB_COUNTRECS;
1214 $crecs = $ADODB_COUNTRECS;
1215 $ADODB_COUNTRECS = false;
1217 $ret = false;
1218 $rs = &$this->Execute($sql,$inputarr);
1219 if ($rs) {
1220 if (!$rs->EOF) $ret = reset($rs->fields);
1221 $rs->Close();
1223 $ADODB_COUNTRECS = $crecs;
1224 return $ret;
1227 function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
1229 $ret = false;
1230 $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
1231 if ($rs) {
1232 if (!$rs->EOF) $ret = reset($rs->fields);
1233 $rs->Close();
1236 return $ret;
1239 function GetCol($sql, $inputarr = false, $trim = false)
1241 $rv = false;
1242 $rs = &$this->Execute($sql, $inputarr);
1243 if ($rs) {
1244 $rv = array();
1245 if ($trim) {
1246 while (!$rs->EOF) {
1247 $rv[] = trim(reset($rs->fields));
1248 $rs->MoveNext();
1250 } else {
1251 while (!$rs->EOF) {
1252 $rv[] = reset($rs->fields);
1253 $rs->MoveNext();
1256 $rs->Close();
1258 return $rv;
1261 function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
1263 $rv = false;
1264 $rs = &$this->CacheExecute($secs, $sql, $inputarr);
1265 if ($rs) {
1266 if ($trim) {
1267 while (!$rs->EOF) {
1268 $rv[] = trim(reset($rs->fields));
1269 $rs->MoveNext();
1271 } else {
1272 while (!$rs->EOF) {
1273 $rv[] = reset($rs->fields);
1274 $rs->MoveNext();
1277 $rs->Close();
1279 return $rv;
1283 Calculate the offset of a date for a particular database and generate
1284 appropriate SQL. Useful for calculating future/past dates and storing
1285 in a database.
1287 If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
1289 function OffsetDate($dayFraction,$date=false)
1291 if (!$date) $date = $this->sysDate;
1292 return '('.$date.'+'.$dayFraction.')';
1298 * @param sql SQL statement
1299 * @param [inputarr] input bind array
1301 function &GetArray($sql,$inputarr=false)
1303 global $ADODB_COUNTRECS;
1305 $savec = $ADODB_COUNTRECS;
1306 $ADODB_COUNTRECS = false;
1307 $rs =& $this->Execute($sql,$inputarr);
1308 $ADODB_COUNTRECS = $savec;
1309 if (!$rs)
1310 if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
1311 else return false;
1312 $arr =& $rs->GetArray();
1313 $rs->Close();
1314 return $arr;
1317 function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
1319 global $ADODB_COUNTRECS;
1321 $savec = $ADODB_COUNTRECS;
1322 $ADODB_COUNTRECS = false;
1323 $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
1324 $ADODB_COUNTRECS = $savec;
1326 if (!$rs)
1327 if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
1328 else return false;
1330 $arr =& $rs->GetArray();
1331 $rs->Close();
1332 return $arr;
1338 * Return one row of sql statement. Recordset is disposed for you.
1340 * @param sql SQL statement
1341 * @param [inputarr] input bind array
1343 function &GetRow($sql,$inputarr=false)
1345 global $ADODB_COUNTRECS;
1346 $crecs = $ADODB_COUNTRECS;
1347 $ADODB_COUNTRECS = false;
1349 $rs =& $this->Execute($sql,$inputarr);
1351 $ADODB_COUNTRECS = $crecs;
1352 if ($rs) {
1353 if (!$rs->EOF) $arr = $rs->fields;
1354 else $arr = array();
1355 $rs->Close();
1356 return $arr;
1359 return false;
1362 function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
1364 $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
1365 if ($rs) {
1366 $arr = false;
1367 if (!$rs->EOF) $arr = $rs->fields;
1368 $rs->Close();
1369 return $arr;
1371 return false;
1375 * Insert or replace a single record. Note: this is not the same as MySQL's replace.
1376 * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
1377 * Also note that no table locking is done currently, so it is possible that the
1378 * record be inserted twice by two programs...
1380 * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
1382 * $table table name
1383 * $fieldArray associative array of data (you must quote strings yourself).
1384 * $keyCol the primary key field name or if compound key, array of field names
1385 * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
1386 * but does not work with dates nor SQL functions.
1387 * has_autoinc the primary key is an auto-inc field, so skip in insert.
1389 * Currently blob replace not supported
1391 * returns 0 = fail, 1 = update, 2 = insert
1394 function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
1396 global $ADODB_INCLUDED_LIB;
1397 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
1399 return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
1404 * Will select, getting rows from $offset (1-based), for $nrows.
1405 * This simulates the MySQL "select * from table limit $offset,$nrows" , and
1406 * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
1407 * MySQL and PostgreSQL parameter ordering is the opposite of the other.
1408 * eg.
1409 * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
1410 * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
1412 * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
1414 * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
1415 * @param sql
1416 * @param [offset] is the row to start calculations from (1-based)
1417 * @param [nrows] is the number of rows to get
1418 * @param [inputarr] array of bind variables
1419 * @return the recordset ($rs->databaseType == 'array')
1421 function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
1423 if (!is_numeric($secs2cache)) {
1424 if ($sql === false) $sql = -1;
1425 if ($offset == -1) $offset = false;
1426 // sql, nrows, offset,inputarr
1427 $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
1428 } else {
1429 if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
1430 $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
1432 return $rs;
1436 * Flush cached recordsets that match a particular $sql statement.
1437 * If $sql == false, then we purge all files in the cache.
1439 function CacheFlush($sql=false,$inputarr=false)
1441 global $ADODB_CACHE_DIR;
1443 if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
1444 if (strncmp(PHP_OS,'WIN',3) === 0) {
1445 $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
1446 } else {
1447 $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache';
1448 // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
1450 if ($this->debug) {
1451 ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
1452 } else {
1453 exec($cmd);
1455 return;
1457 $f = $this->_gencachename($sql.serialize($inputarr),false);
1458 adodb_write_file($f,''); // is adodb_write_file needed?
1459 if (!@unlink($f)) {
1460 if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
1465 * Private function to generate filename for caching.
1466 * Filename is generated based on:
1468 * - sql statement
1469 * - database type (oci8, ibase, ifx, etc)
1470 * - database name
1471 * - userid
1473 * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
1474 * Assuming that we can have 50,000 files per directory with good performance,
1475 * then we can scale to 12.8 million unique cached recordsets. Wow!
1477 function _gencachename($sql,$createdir)
1479 global $ADODB_CACHE_DIR;
1481 $m = md5($sql.$this->databaseType.$this->database.$this->user);
1482 $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2);
1483 if ($createdir && !file_exists($dir)) {
1484 $oldu = umask(0);
1485 if (!mkdir($dir,0771))
1486 if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
1487 umask($oldu);
1489 return $dir.'/adodb_'.$m.'.cache';
1494 * Execute SQL, caching recordsets.
1496 * @param [secs2cache] seconds to cache data, set to 0 to force query.
1497 * This is an optional parameter.
1498 * @param sql SQL statement to execute
1499 * @param [inputarr] holds the input data to bind to
1500 * @return RecordSet or false
1502 function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
1504 if (!is_numeric($secs2cache)) {
1505 $inputarr = $sql;
1506 $sql = $secs2cache;
1507 $secs2cache = $this->cacheSecs;
1509 global $ADODB_INCLUDED_CSV;
1510 if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
1512 if (is_array($sql)) $sql = $sql[0];
1514 $md5file = $this->_gencachename($sql.serialize($inputarr),true);
1515 $err = '';
1517 if ($secs2cache > 0){
1518 $rs = &csv2rs($md5file,$err,$secs2cache);
1519 $this->numCacheHits += 1;
1520 } else {
1521 $err='Timeout 1';
1522 $rs = false;
1523 $this->numCacheMisses += 1;
1525 if (!$rs) {
1526 // no cached rs found
1527 if ($this->debug) {
1528 if (get_magic_quotes_runtime()) {
1529 ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
1531 if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
1533 $rs = &$this->Execute($sql,$inputarr);
1534 if ($rs) {
1535 $eof = $rs->EOF;
1536 $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
1537 $txt = _rs2serialize($rs,false,$sql); // serialize
1539 if (!adodb_write_file($md5file,$txt,$this->debug)) {
1540 if ($fn = $this->raiseErrorFn) {
1541 $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
1543 if ($this->debug) ADOConnection::outp( " Cache write error");
1545 if ($rs->EOF && !$eof) {
1546 $rs->MoveFirst();
1547 //$rs = &csv2rs($md5file,$err);
1548 $rs->connection = &$this; // Pablo suggestion
1551 } else
1552 @unlink($md5file);
1553 } else {
1554 $this->_errorMsg = '';
1555 $this->_errorCode = 0;
1557 if ($this->fnCacheExecute) {
1558 $fn = $this->fnCacheExecute;
1559 $fn($this, $secs2cache, $sql, $inputarr);
1561 // ok, set cached object found
1562 $rs->connection = &$this; // Pablo suggestion
1563 if ($this->debug){
1564 global $HTTP_SERVER_VARS;
1566 $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
1567 $ttl = $rs->timeCreated + $secs2cache - time();
1568 $s = is_array($sql) ? $sql[0] : $sql;
1569 if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
1571 ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
1574 return $rs;
1579 * Generates an Update Query based on an existing recordset.
1580 * $arrFields is an associative array of fields with the value
1581 * that should be assigned.
1583 * Note: This function should only be used on a recordset
1584 * that is run against a single table and sql should only
1585 * be a simple select stmt with no groupby/orderby/limit
1587 * "Jonathan Younger" <jyounger@unilab.com>
1589 function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false)
1591 global $ADODB_INCLUDED_LIB;
1592 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
1593 return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq);
1598 * Generates an Insert Query based on an existing recordset.
1599 * $arrFields is an associative array of fields with the value
1600 * that should be assigned.
1602 * Note: This function should only be used on a recordset
1603 * that is run against a single table.
1605 function GetInsertSQL(&$rs, $arrFields,$magicq=false)
1607 global $ADODB_INCLUDED_LIB;
1608 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
1609 return _adodb_getinsertsql($this,$rs,$arrFields,$magicq);
1614 * Update a blob column, given a where clause. There are more sophisticated
1615 * blob handling functions that we could have implemented, but all require
1616 * a very complex API. Instead we have chosen something that is extremely
1617 * simple to understand and use.
1619 * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
1621 * Usage to update a $blobvalue which has a primary key blob_id=1 into a
1622 * field blobtable.blobcolumn:
1624 * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
1626 * Insert example:
1628 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
1629 * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
1632 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
1634 return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
1638 * Usage:
1639 * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
1641 * $blobtype supports 'BLOB' and 'CLOB'
1643 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
1644 * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
1646 function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
1648 $fd = fopen($path,'rb');
1649 if ($fd === false) return false;
1650 $val = fread($fd,filesize($path));
1651 fclose($fd);
1652 return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
1655 function BlobDecode($blob)
1657 return $blob;
1660 function BlobEncode($blob)
1662 return $blob;
1665 function SetCharSet($charset)
1667 return false;
1670 function IfNull( $field, $ifNull )
1672 return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
1675 function LogSQL($enable=true)
1677 include_once(ADODB_DIR.'/adodb-perf.inc.php');
1679 if ($enable) $this->fnExecute = 'adodb_log_sql';
1680 else $this->fnExecute = false;
1682 $old = $this->_logsql;
1683 $this->_logsql = $enable;
1684 if ($enable && !$old) $this->_affected = false;
1685 return $old;
1688 function GetCharSet()
1690 return false;
1694 * Usage:
1695 * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
1697 * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
1698 * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
1700 function UpdateClob($table,$column,$val,$where)
1702 return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
1707 * Change the SQL connection locale to a specified locale.
1708 * This is used to get the date formats written depending on the client locale.
1710 function SetDateLocale($locale = 'En')
1712 $this->locale = $locale;
1713 switch ($locale)
1715 default:
1716 case 'En':
1717 $this->fmtDate="Y-m-d";
1718 $this->fmtTimeStamp = "Y-m-d H:i:s";
1719 break;
1721 case 'Fr':
1722 case 'Ro':
1723 case 'It':
1724 $this->fmtDate="d-m-Y";
1725 $this->fmtTimeStamp = "d-m-Y H:i:s";
1726 break;
1728 case 'Ge':
1729 $this->fmtDate="d.m.Y";
1730 $this->fmtTimeStamp = "d.m.Y H:i:s";
1731 break;
1737 * $meta contains the desired type, which could be...
1738 * C for character. You will have to define the precision yourself.
1739 * X for teXt. For unlimited character lengths.
1740 * B for Binary
1741 * F for floating point, with no need to define scale and precision
1742 * N for decimal numbers, you will have to define the (scale, precision) yourself
1743 * D for date
1744 * T for timestamp
1745 * L for logical/Boolean
1746 * I for integer
1747 * R for autoincrement counter/integer
1748 * and if you want to use double-byte, add a 2 to the end, like C2 or X2.
1751 * @return the actual type of the data or false if no such type available
1753 function ActualType($meta)
1755 switch($meta) {
1756 case 'C':
1757 case 'X':
1758 return 'VARCHAR';
1759 case 'B':
1761 case 'D':
1762 case 'T':
1763 case 'L':
1765 case 'R':
1767 case 'I':
1768 case 'N':
1769 return false;
1775 * Close Connection
1777 function Close()
1779 return $this->_close();
1781 // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need
1782 // to be closed too!
1783 //if ($this->_isPersistentConnection != true) return $this->_close();
1784 //else return true;
1788 * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
1790 * @return true if succeeded or false if database does not support transactions
1792 function BeginTrans() {return false;}
1796 * If database does not support transactions, always return true as data always commited
1798 * @param $ok set to false to rollback transaction, true to commit
1800 * @return true/false.
1802 function CommitTrans($ok=true)
1803 { return true;}
1807 * If database does not support transactions, rollbacks always fail, so return false
1809 * @return true/false.
1811 function RollbackTrans()
1812 { return false;}
1816 * return the databases that the driver can connect to.
1817 * Some databases will return an empty array.
1819 * @return an array of database names.
1821 function MetaDatabases()
1823 global $ADODB_FETCH_MODE;
1825 if ($this->metaDatabasesSQL) {
1826 $save = $ADODB_FETCH_MODE;
1827 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
1829 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
1831 $arr = $this->GetCol($this->metaDatabasesSQL);
1832 if (isset($savem)) $this->SetFetchMode($savem);
1833 $ADODB_FETCH_MODE = $save;
1835 return $arr;
1838 return false;
1842 * @param ttype can either be 'VIEW' or 'TABLE' or false.
1843 * If false, both views and tables are returned.
1844 * "VIEW" returns only views
1845 * "TABLE" returns only tables
1846 * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
1847 * @param mask is the input mask - only supported by oci8 and postgresql
1849 * @return array of tables for current database.
1851 function &MetaTables($ttype=false,$showSchema=false,$mask=false)
1853 global $ADODB_FETCH_MODE;
1855 if ($mask) return false;
1857 if ($this->metaTablesSQL) {
1858 // complicated state saving by the need for backward compat
1859 $save = $ADODB_FETCH_MODE;
1860 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
1862 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
1864 $rs = $this->Execute($this->metaTablesSQL);
1865 if (isset($savem)) $this->SetFetchMode($savem);
1866 $ADODB_FETCH_MODE = $save;
1868 if ($rs === false) return false;
1869 $arr =& $rs->GetArray();
1870 $arr2 = array();
1872 if ($hast = ($ttype && isset($arr[0][1]))) {
1873 $showt = strncmp($ttype,'T',1);
1876 for ($i=0; $i < sizeof($arr); $i++) {
1877 if ($hast) {
1878 if ($showt == 0) {
1879 if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
1880 } else {
1881 if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
1883 } else
1884 $arr2[] = trim($arr[$i][0]);
1886 $rs->Close();
1887 return $arr2;
1889 return false;
1893 function _findschema(&$table,&$schema)
1895 if (!$schema && ($at = strpos($table,'.')) !== false) {
1896 $schema = substr($table,0,$at);
1897 $table = substr($table,$at+1);
1902 * List columns in a database as an array of ADOFieldObjects.
1903 * See top of file for definition of object.
1905 * @param table table name to query
1906 * @param upper uppercase table name (required by some databases)
1907 * @schema is optional database schema to use - not supported by all databases.
1909 * @return array of ADOFieldObjects for current table.
1911 function &MetaColumns($table,$upper=true)
1913 global $ADODB_FETCH_MODE;
1915 if (!empty($this->metaColumnsSQL)) {
1917 $schema = false;
1918 $this->_findschema($table,$schema);
1920 $save = $ADODB_FETCH_MODE;
1921 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
1922 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
1923 $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table));
1924 if (isset($savem)) $this->SetFetchMode($savem);
1925 $ADODB_FETCH_MODE = $save;
1926 if ($rs === false) return false;
1928 $retarr = array();
1929 while (!$rs->EOF) { //print_r($rs->fields);
1930 $fld =& new ADOFieldObject();
1931 $fld->name = $rs->fields[0];
1932 $fld->type = $rs->fields[1];
1933 if (isset($rs->fields[3]) && $rs->fields[3]) {
1934 if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
1935 $fld->scale = $rs->fields[4];
1936 if ($fld->scale>0) $fld->max_length += 1;
1937 } else
1938 $fld->max_length = $rs->fields[2];
1940 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
1941 else $retarr[strtoupper($fld->name)] = $fld;
1942 $rs->MoveNext();
1944 $rs->Close();
1945 return $retarr;
1947 return false;
1951 * List indexes on a table as an array.
1952 * @param table table name to query
1953 * @param primary include primary keys.
1955 * @return array of indexes on current table.
1957 function &MetaIndexes($table, $primary = false, $owner = false)
1959 return FALSE;
1963 * List columns names in a table as an array.
1964 * @param table table name to query
1966 * @return array of column names for current table.
1968 function &MetaColumnNames($table)
1970 $objarr =& $this->MetaColumns($table);
1971 if (!is_array($objarr)) return false;
1973 $arr = array();
1974 foreach($objarr as $v) {
1975 $arr[] = $v->name;
1977 return $arr;
1981 * Different SQL databases used different methods to combine strings together.
1982 * This function provides a wrapper.
1984 * param s variable number of string parameters
1986 * Usage: $db->Concat($str1,$str2);
1988 * @return concatenated string
1990 function Concat()
1992 $arr = func_get_args();
1993 return implode($this->concat_operator, $arr);
1998 * Converts a date "d" to a string that the database can understand.
2000 * @param d a date in Unix date time format.
2002 * @return date string in database date format
2004 function DBDate($d)
2006 if (empty($d) && $d !== 0) return 'null';
2008 if (is_string($d) && !is_numeric($d)) {
2009 if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
2010 if ($this->isoDates) return "'$d'";
2011 $d = ADOConnection::UnixDate($d);
2014 return adodb_date($this->fmtDate,$d);
2019 * Converts a timestamp "ts" to a string that the database can understand.
2021 * @param ts a timestamp in Unix date time format.
2023 * @return timestamp string in database timestamp format
2025 function DBTimeStamp($ts)
2027 if (empty($ts) && $ts !== 0) return 'null';
2029 # strlen(14) allows YYYYMMDDHHMMSS format
2030 if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
2031 return adodb_date($this->fmtTimeStamp,$ts);
2033 if ($ts === 'null') return $ts;
2034 if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
2036 $ts = ADOConnection::UnixTimeStamp($ts);
2037 return adodb_date($this->fmtTimeStamp,$ts);
2041 * Also in ADORecordSet.
2042 * @param $v is a date string in YYYY-MM-DD format
2044 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2046 function UnixDate($v)
2048 if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
2049 ($v), $rr)) return false;
2051 if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
2052 // h-m-s-MM-DD-YY
2053 return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2058 * Also in ADORecordSet.
2059 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
2061 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2063 function UnixTimeStamp($v)
2065 if (!preg_match(
2066 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
2067 ($v), $rr)) return false;
2069 if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
2071 // h-m-s-MM-DD-YY
2072 if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2073 return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
2077 * Also in ADORecordSet.
2079 * Format database date based on user defined format.
2081 * @param v is the character date in YYYY-MM-DD format, returned by database
2082 * @param fmt is the format to apply to it, using date()
2084 * @return a date formated as user desires
2087 function UserDate($v,$fmt='Y-m-d')
2089 $tt = $this->UnixDate($v);
2090 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2091 if (($tt === false || $tt == -1) && $v != false) return $v;
2092 else if ($tt == 0) return $this->emptyDate;
2093 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
2096 return adodb_date($fmt,$tt);
2102 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
2103 * @param fmt is the format to apply to it, using date()
2105 * @return a timestamp formated as user desires
2107 function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
2109 # strlen(14) allows YYYYMMDDHHMMSS format
2110 if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
2111 $tt = $this->UnixTimeStamp($v);
2112 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2113 if (($tt === false || $tt == -1) && $v != false) return $v;
2114 if ($tt == 0) return $this->emptyTimeStamp;
2115 return adodb_date($fmt,$tt);
2119 * Quotes a string, without prefixing nor appending quotes.
2121 function addq($s,$magicq=false)
2123 if (!$magic_quotes) {
2125 if ($this->replaceQuote[0] == '\\'){
2126 // only since php 4.0.5
2127 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
2128 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
2130 return str_replace("'",$this->replaceQuote,$s);
2133 // undo magic quotes for "
2134 $s = str_replace('\\"','"',$s);
2136 if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
2137 return $s;
2138 else {// change \' to '' for sybase/mssql
2139 $s = str_replace('\\\\','\\',$s);
2140 return str_replace("\\'",$this->replaceQuote,$s);
2145 * Correctly quotes a string so that all strings are escaped. We prefix and append
2146 * to the string single-quotes.
2147 * An example is $db->qstr("Don't bother",magic_quotes_runtime());
2149 * @param s the string to quote
2150 * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
2151 * This undoes the stupidity of magic quotes for GPC.
2153 * @return quoted string to be sent back to database
2155 function qstr($s,$magic_quotes=false)
2157 if (!$magic_quotes) {
2159 if ($this->replaceQuote[0] == '\\'){
2160 // only since php 4.0.5
2161 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
2162 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
2164 return "'".str_replace("'",$this->replaceQuote,$s)."'";
2167 // undo magic quotes for "
2168 $s = str_replace('\\"','"',$s);
2170 if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
2171 return "'$s'";
2172 else {// change \' to '' for sybase/mssql
2173 $s = str_replace('\\\\','\\',$s);
2174 return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
2180 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
2181 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
2182 * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
2184 * See readme.htm#ex8 for an example of usage.
2186 * @param sql
2187 * @param nrows is the number of rows per page to get
2188 * @param page is the page number to get (1-based)
2189 * @param [inputarr] array of bind variables
2190 * @param [secs2cache] is a private parameter only used by jlim
2191 * @return the recordset ($rs->databaseType == 'array')
2193 * NOTE: phpLens uses a different algorithm and does not use PageExecute().
2196 function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0)
2198 global $ADODB_INCLUDED_LIB;
2199 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
2200 if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
2201 return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
2207 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
2208 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
2209 * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
2211 * @param secs2cache seconds to cache data, set to 0 to force query
2212 * @param sql
2213 * @param nrows is the number of rows per page to get
2214 * @param page is the page number to get (1-based)
2215 * @param [inputarr] array of bind variables
2216 * @return the recordset ($rs->databaseType == 'array')
2218 function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false)
2220 /*switch($this->dataProvider) {
2221 case 'postgres':
2222 case 'mysql':
2223 break;
2224 default: $secs2cache = 0; break;
2226 $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
2227 return $rs;
2230 } // end class ADOConnection
2234 //==============================================================================================
2235 // CLASS ADOFetchObj
2236 //==============================================================================================
2239 * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
2241 class ADOFetchObj {
2244 //==============================================================================================
2245 // CLASS ADORecordSet_empty
2246 //==============================================================================================
2249 * Lightweight recordset when there are no records to be returned
2251 class ADORecordSet_empty
2253 var $dataProvider = 'empty';
2254 var $databaseType = false;
2255 var $EOF = true;
2256 var $_numOfRows = 0;
2257 var $fields = false;
2258 var $connection = false;
2259 function RowCount() {return 0;}
2260 function RecordCount() {return 0;}
2261 function PO_RecordCount(){return 0;}
2262 function Close(){return true;}
2263 function FetchRow() {return false;}
2264 function FieldCount(){ return 0;}
2267 //==============================================================================================
2268 // DATE AND TIME FUNCTIONS
2269 //==============================================================================================
2270 include_once(ADODB_DIR.'/adodb-time.inc.php');
2272 //==============================================================================================
2273 // CLASS ADORecordSet
2274 //==============================================================================================
2276 if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
2277 else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
2279 * RecordSet class that represents the dataset returned by the database.
2280 * To keep memory overhead low, this class holds only the current row in memory.
2281 * No prefetching of data is done, so the RecordCount() can return -1 ( which
2282 * means recordcount not known).
2284 class ADORecordSet extends ADODB_BASE_RS {
2286 * public variables
2288 var $dataProvider = "native";
2289 var $fields = false; /// holds the current row data
2290 var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
2291 /// in other words, we use a text area for editing.
2292 var $canSeek = false; /// indicates that seek is supported
2293 var $sql; /// sql text
2294 var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
2296 var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
2297 var $emptyDate = '&nbsp;'; /// what to display when $time==0
2298 var $debug = false;
2299 var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
2301 var $bind = false; /// used by Fields() to hold array - should be private?
2302 var $fetchMode; /// default fetch mode
2303 var $connection = false; /// the parent connection
2305 * private variables
2307 var $_numOfRows = -1; /** number of rows, or -1 */
2308 var $_numOfFields = -1; /** number of fields in recordset */
2309 var $_queryID = -1; /** This variable keeps the result link identifier. */
2310 var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
2311 var $_closed = false; /** has recordset been closed */
2312 var $_inited = false; /** Init() should only be called once */
2313 var $_obj; /** Used by FetchObj */
2314 var $_names; /** Used by FetchObj */
2316 var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */
2317 var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */
2318 var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */
2319 var $_lastPageNo = -1;
2320 var $_maxRecordCount = 0;
2321 var $datetime = false;
2324 * Constructor
2326 * @param queryID this is the queryID returned by ADOConnection->_query()
2329 function ADORecordSet($queryID)
2331 $this->_queryID = $queryID;
2336 function Init()
2338 if ($this->_inited) return;
2339 $this->_inited = true;
2340 if ($this->_queryID) @$this->_initrs();
2341 else {
2342 $this->_numOfRows = 0;
2343 $this->_numOfFields = 0;
2345 if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
2347 $this->_currentRow = 0;
2348 if ($this->EOF = ($this->_fetch() === false)) {
2349 $this->_numOfRows = 0; // _numOfRows could be -1
2351 } else {
2352 $this->EOF = true;
2358 * Generate a SELECT tag string from a recordset, and return the string.
2359 * If the recordset has 2 cols, we treat the 1st col as the containing
2360 * the text to display to the user, and 2nd col as the return value. Default
2361 * strings are compared with the FIRST column.
2363 * @param name name of SELECT tag
2364 * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
2365 * @param [blank1stItem] true to leave the 1st item in list empty
2366 * @param [multiple] true for listbox, false for popup
2367 * @param [size] #rows to show for listbox. not used by popup
2368 * @param [selectAttr] additional attributes to defined for SELECT tag.
2369 * useful for holding javascript onChange='...' handlers.
2370 & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
2371 * column 0 (1st col) if this is true. This is not documented.
2373 * @return HTML
2375 * changes by glen.davies@cce.ac.nz to support multiple hilited items
2377 function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
2378 $size=0, $selectAttr='',$compareFields0=true)
2380 global $ADODB_INCLUDED_LIB;
2381 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
2382 return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
2383 $size, $selectAttr,$compareFields0);
2387 * Generate a SELECT tag string from a recordset, and return the string.
2388 * If the recordset has 2 cols, we treat the 1st col as the containing
2389 * the text to display to the user, and 2nd col as the return value. Default
2390 * strings are compared with the SECOND column.
2393 function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
2395 global $ADODB_INCLUDED_LIB;
2396 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
2397 return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple,
2398 $size, $selectAttr,false);
2403 * return recordset as a 2-dimensional array.
2405 * @param [nRows] is the number of rows to return. -1 means every row.
2407 * @return an array indexed by the rows (0-based) from the recordset
2409 function &GetArray($nRows = -1)
2411 global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows);
2413 $results = array();
2414 $cnt = 0;
2415 while (!$this->EOF && $nRows != $cnt) {
2416 $results[] = $this->fields;
2417 $this->MoveNext();
2418 $cnt++;
2420 return $results;
2423 function &GetAll($nRows = -1)
2425 $arr =& $this->GetArray($nRows);
2426 return $arr;
2430 * Some databases allow multiple recordsets to be returned. This function
2431 * will return true if there is a next recordset, or false if no more.
2433 function NextRecordSet()
2435 return false;
2439 * return recordset as a 2-dimensional array.
2440 * Helper function for ADOConnection->SelectLimit()
2442 * @param offset is the row to start calculations from (1-based)
2443 * @param [nrows] is the number of rows to return
2445 * @return an array indexed by the rows (0-based) from the recordset
2447 function &GetArrayLimit($nrows,$offset=-1)
2449 if ($offset <= 0) {
2450 $arr =& $this->GetArray($nrows);
2451 return $arr;
2454 $this->Move($offset);
2456 $results = array();
2457 $cnt = 0;
2458 while (!$this->EOF && $nrows != $cnt) {
2459 $results[$cnt++] = $this->fields;
2460 $this->MoveNext();
2463 return $results;
2468 * Synonym for GetArray() for compatibility with ADO.
2470 * @param [nRows] is the number of rows to return. -1 means every row.
2472 * @return an array indexed by the rows (0-based) from the recordset
2474 function &GetRows($nRows = -1)
2476 $arr =& $this->GetArray($nRows);
2477 return $arr;
2481 * return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
2482 * The first column is treated as the key and is not included in the array.
2483 * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
2484 * $force_array == true.
2486 * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
2487 * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
2488 * read the source.
2490 * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
2491 * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
2493 * @return an associative array indexed by the first column of the array,
2494 * or false if the data has less than 2 cols.
2496 function &GetAssoc($force_array = false, $first2cols = false) {
2497 $cols = $this->_numOfFields;
2498 if ($cols < 2) {
2499 return false;
2501 $numIndex = isset($this->fields[0]);
2502 $results = array();
2504 if (!$first2cols && ($cols > 2 || $force_array)) {
2505 if ($numIndex) {
2506 while (!$this->EOF) {
2507 $results[trim($this->fields[0])] = array_slice($this->fields, 1);
2508 $this->MoveNext();
2510 } else {
2511 while (!$this->EOF) {
2512 $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
2513 $this->MoveNext();
2516 } else {
2517 // return scalar values
2518 if ($numIndex) {
2519 while (!$this->EOF) {
2520 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
2521 $results[trim(($this->fields[0]))] = $this->fields[1];
2522 $this->MoveNext();
2524 } else {
2525 while (!$this->EOF) {
2526 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
2527 $v1 = trim(reset($this->fields));
2528 $v2 = ''.next($this->fields);
2529 $results[$v1] = $v2;
2530 $this->MoveNext();
2534 return $results;
2540 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
2541 * @param fmt is the format to apply to it, using date()
2543 * @return a timestamp formated as user desires
2545 function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
2547 if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
2548 $tt = $this->UnixTimeStamp($v);
2549 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2550 if (($tt === false || $tt == -1) && $v != false) return $v;
2551 if ($tt === 0) return $this->emptyTimeStamp;
2552 return adodb_date($fmt,$tt);
2557 * @param v is the character date in YYYY-MM-DD format, returned by database
2558 * @param fmt is the format to apply to it, using date()
2560 * @return a date formated as user desires
2562 function UserDate($v,$fmt='Y-m-d')
2564 $tt = $this->UnixDate($v);
2565 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2566 if (($tt === false || $tt == -1) && $v != false) return $v;
2567 else if ($tt == 0) return $this->emptyDate;
2568 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
2570 return adodb_date($fmt,$tt);
2576 * @param $v is a date string in YYYY-MM-DD format
2578 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2580 function UnixDate($v)
2583 if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
2584 ($v), $rr)) return false;
2586 if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
2587 // h-m-s-MM-DD-YY
2588 return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2593 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
2595 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2597 function UnixTimeStamp($v)
2600 if (!preg_match(
2601 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
2602 ($v), $rr)) return false;
2603 if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
2605 // h-m-s-MM-DD-YY
2606 if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2607 return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
2612 * PEAR DB Compat - do not use internally
2614 function Free()
2616 return $this->Close();
2621 * PEAR DB compat, number of rows
2623 function NumRows()
2625 return $this->_numOfRows;
2630 * PEAR DB compat, number of cols
2632 function NumCols()
2634 return $this->_numOfFields;
2638 * Fetch a row, returning false if no more rows.
2639 * This is PEAR DB compat mode.
2641 * @return false or array containing the current record
2643 function FetchRow()
2645 if ($this->EOF) return false;
2646 $arr = $this->fields;
2647 $this->_currentRow++;
2648 if (!$this->_fetch()) $this->EOF = true;
2649 return $arr;
2654 * Fetch a row, returning PEAR_Error if no more rows.
2655 * This is PEAR DB compat mode.
2657 * @return DB_OK or error object
2659 function FetchInto(&$arr)
2661 if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
2662 $arr = $this->fields;
2663 $this->MoveNext();
2664 return 1; // DB_OK
2669 * Move to the first row in the recordset. Many databases do NOT support this.
2671 * @return true or false
2673 function MoveFirst()
2675 if ($this->_currentRow == 0) return true;
2676 return $this->Move(0);
2681 * Move to the last row in the recordset.
2683 * @return true or false
2685 function MoveLast()
2687 if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
2688 if ($this->EOF) return false;
2689 while (!$this->EOF) {
2690 $f = $this->fields;
2691 $this->MoveNext();
2693 $this->fields = $f;
2694 $this->EOF = false;
2695 return true;
2700 * Move to next record in the recordset.
2702 * @return true if there still rows available, or false if there are no more rows (EOF).
2704 function MoveNext()
2706 if (!$this->EOF) {
2707 $this->_currentRow++;
2708 if ($this->_fetch()) return true;
2710 $this->EOF = true;
2711 /* -- tested error handling when scrolling cursor -- seems useless.
2712 $conn = $this->connection;
2713 if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
2714 $fn = $conn->raiseErrorFn;
2715 $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
2718 return false;
2722 * Random access to a specific row in the recordset. Some databases do not support
2723 * access to previous rows in the databases (no scrolling backwards).
2725 * @param rowNumber is the row to move to (0-based)
2727 * @return true if there still rows available, or false if there are no more rows (EOF).
2729 function Move($rowNumber = 0)
2731 $this->EOF = false;
2732 if ($rowNumber == $this->_currentRow) return true;
2733 if ($rowNumber >= $this->_numOfRows)
2734 if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
2736 if ($this->canSeek) {
2738 if ($this->_seek($rowNumber)) {
2739 $this->_currentRow = $rowNumber;
2740 if ($this->_fetch()) {
2741 return true;
2743 } else {
2744 $this->EOF = true;
2745 return false;
2747 } else {
2748 if ($rowNumber < $this->_currentRow) return false;
2749 global $ADODB_EXTENSION;
2750 if ($ADODB_EXTENSION) {
2751 while (!$this->EOF && $this->_currentRow < $rowNumber) {
2752 adodb_movenext($this);
2754 } else {
2756 while (! $this->EOF && $this->_currentRow < $rowNumber) {
2757 $this->_currentRow++;
2759 if (!$this->_fetch()) $this->EOF = true;
2762 return !($this->EOF);
2765 $this->fields = false;
2766 $this->EOF = true;
2767 return false;
2772 * Get the value of a field in the current row by column name.
2773 * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
2775 * @param colname is the field to access
2777 * @return the value of $colname column
2779 function Fields($colname)
2781 return $this->fields[$colname];
2784 function GetAssocKeys($upper=true)
2786 $this->bind = array();
2787 for ($i=0; $i < $this->_numOfFields; $i++) {
2788 $o =& $this->FetchField($i);
2789 if ($upper === 2) $this->bind[$o->name] = $i;
2790 else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
2795 * Use associative array to get fields array for databases that do not support
2796 * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it
2798 * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
2799 * before you execute your SQL statement, and access $rs->fields['col'] directly.
2801 * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
2803 function &GetRowAssoc($upper=1)
2805 $record = array();
2806 // if (!$this->fields) return $record;
2808 if (!$this->bind) {
2809 $this->GetAssocKeys($upper);
2812 foreach($this->bind as $k => $v) {
2813 $record[$k] = $this->fields[$v];
2816 return $record;
2821 * Clean up recordset
2823 * @return true or false
2825 function Close()
2827 // free connection object - this seems to globally free the object
2828 // and not merely the reference, so don't do this...
2829 // $this->connection = false;
2830 if (!$this->_closed) {
2831 $this->_closed = true;
2832 return $this->_close();
2833 } else
2834 return true;
2838 * synonyms RecordCount and RowCount
2840 * @return the number of rows or -1 if this is not supported
2842 function RecordCount() {return $this->_numOfRows;}
2846 * If we are using PageExecute(), this will return the maximum possible rows
2847 * that can be returned when paging a recordset.
2849 function MaxRecordCount()
2851 return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
2855 * synonyms RecordCount and RowCount
2857 * @return the number of rows or -1 if this is not supported
2859 function RowCount() {return $this->_numOfRows;}
2863 * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
2865 * @return the number of records from a previous SELECT. All databases support this.
2867 * But aware possible problems in multiuser environments. For better speed the table
2868 * must be indexed by the condition. Heavy test this before deploying.
2870 function PO_RecordCount($table="", $condition="") {
2872 $lnumrows = $this->_numOfRows;
2873 // the database doesn't support native recordcount, so we do a workaround
2874 if ($lnumrows == -1 && $this->connection) {
2875 IF ($table) {
2876 if ($condition) $condition = " WHERE " . $condition;
2877 $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
2878 if ($resultrows) $lnumrows = reset($resultrows->fields);
2881 return $lnumrows;
2885 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
2887 function CurrentRow() {return $this->_currentRow;}
2890 * synonym for CurrentRow -- for ADO compat
2892 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
2894 function AbsolutePosition() {return $this->_currentRow;}
2897 * @return the number of columns in the recordset. Some databases will set this to 0
2898 * if no records are returned, others will return the number of columns in the query.
2900 function FieldCount() {return $this->_numOfFields;}
2904 * Get the ADOFieldObject of a specific column.
2906 * @param fieldoffset is the column position to access(0-based).
2908 * @return the ADOFieldObject for that column, or false.
2910 function &FetchField($fieldoffset)
2912 // must be defined by child class
2916 * Get the ADOFieldObjects of all columns in an array.
2919 function FieldTypesArray()
2921 $arr = array();
2922 for ($i=0, $max=$this->_numOfFields; $i < $max; $i++)
2923 $arr[] = $this->FetchField($i);
2924 return $arr;
2928 * Return the fields array of the current row as an object for convenience.
2929 * The default case is lowercase field names.
2931 * @return the object with the properties set to the fields of the current row
2933 function &FetchObj()
2935 $o =& $this->FetchObject(false);
2936 return $o;
2940 * Return the fields array of the current row as an object for convenience.
2941 * The default case is uppercase.
2943 * @param $isupper to set the object property names to uppercase
2945 * @return the object with the properties set to the fields of the current row
2947 function &FetchObject($isupper=true)
2949 if (empty($this->_obj)) {
2950 $this->_obj =& new ADOFetchObj();
2951 $this->_names = array();
2952 for ($i=0; $i <$this->_numOfFields; $i++) {
2953 $f = $this->FetchField($i);
2954 $this->_names[] = $f->name;
2957 $i = 0;
2958 $o = &$this->_obj;
2959 for ($i=0; $i <$this->_numOfFields; $i++) {
2960 $name = $this->_names[$i];
2961 if ($isupper) $n = strtoupper($name);
2962 else $n = $name;
2964 $o->$n = $this->Fields($name);
2966 return $o;
2970 * Return the fields array of the current row as an object for convenience.
2971 * The default is lower-case field names.
2973 * @return the object with the properties set to the fields of the current row,
2974 * or false if EOF
2976 * Fixed bug reported by tim@orotech.net
2978 function &FetchNextObj()
2980 return $this->FetchNextObject(false);
2985 * Return the fields array of the current row as an object for convenience.
2986 * The default is upper case field names.
2988 * @param $isupper to set the object property names to uppercase
2990 * @return the object with the properties set to the fields of the current row,
2991 * or false if EOF
2993 * Fixed bug reported by tim@orotech.net
2995 function &FetchNextObject($isupper=true)
2997 $o = false;
2998 if ($this->_numOfRows != 0 && !$this->EOF) {
2999 $o = $this->FetchObject($isupper);
3000 $this->_currentRow++;
3001 if ($this->_fetch()) return $o;
3003 $this->EOF = true;
3004 return $o;
3008 * Get the metatype of the column. This is used for formatting. This is because
3009 * many databases use different names for the same type, so we transform the original
3010 * type to our standardised version which uses 1 character codes:
3012 * @param t is the type passed in. Normally is ADOFieldObject->type.
3013 * @param len is the maximum length of that field. This is because we treat character
3014 * fields bigger than a certain size as a 'B' (blob).
3015 * @param fieldobj is the field object returned by the database driver. Can hold
3016 * additional info (eg. primary_key for mysql).
3018 * @return the general type of the data:
3019 * C for character < 200 chars
3020 * X for teXt (>= 200 chars)
3021 * B for Binary
3022 * N for numeric floating point
3023 * D for date
3024 * T for timestamp
3025 * L for logical/Boolean
3026 * I for integer
3027 * R for autoincrement counter/integer
3031 function MetaType($t,$len=-1,$fieldobj=false)
3033 if (is_object($t)) {
3034 $fieldobj = $t;
3035 $t = $fieldobj->type;
3036 $len = $fieldobj->max_length;
3038 // changed in 2.32 to hashing instead of switch stmt for speed...
3039 static $typeMap = array(
3040 'VARCHAR' => 'C',
3041 'VARCHAR2' => 'C',
3042 'CHAR' => 'C',
3043 'C' => 'C',
3044 'STRING' => 'C',
3045 'NCHAR' => 'C',
3046 'NVARCHAR' => 'C',
3047 'VARYING' => 'C',
3048 'BPCHAR' => 'C',
3049 'CHARACTER' => 'C',
3050 'INTERVAL' => 'C', # Postgres
3052 'LONGCHAR' => 'X',
3053 'TEXT' => 'X',
3054 'NTEXT' => 'X',
3055 'M' => 'X',
3056 'X' => 'X',
3057 'CLOB' => 'X',
3058 'NCLOB' => 'X',
3059 'LVARCHAR' => 'X',
3061 'BLOB' => 'B',
3062 'IMAGE' => 'B',
3063 'BINARY' => 'B',
3064 'VARBINARY' => 'B',
3065 'LONGBINARY' => 'B',
3066 'B' => 'B',
3068 'YEAR' => 'D', // mysql
3069 'DATE' => 'D',
3070 'D' => 'D',
3072 'TIME' => 'T',
3073 'TIMESTAMP' => 'T',
3074 'DATETIME' => 'T',
3075 'TIMESTAMPTZ' => 'T',
3076 'T' => 'T',
3078 'BOOL' => 'L',
3079 'BOOLEAN' => 'L',
3080 'BIT' => 'L',
3081 'L' => 'L',
3083 'COUNTER' => 'R',
3084 'R' => 'R',
3085 'SERIAL' => 'R', // ifx
3086 'INT IDENTITY' => 'R',
3088 'INT' => 'I',
3089 'INTEGER' => 'I',
3090 'INTEGER UNSIGNED' => 'I',
3091 'SHORT' => 'I',
3092 'TINYINT' => 'I',
3093 'SMALLINT' => 'I',
3094 'I' => 'I',
3096 'LONG' => 'N', // interbase is numeric, oci8 is blob
3097 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
3098 'DECIMAL' => 'N',
3099 'DEC' => 'N',
3100 'REAL' => 'N',
3101 'DOUBLE' => 'N',
3102 'DOUBLE PRECISION' => 'N',
3103 'SMALLFLOAT' => 'N',
3104 'FLOAT' => 'N',
3105 'NUMBER' => 'N',
3106 'NUM' => 'N',
3107 'NUMERIC' => 'N',
3108 'MONEY' => 'N',
3110 ## informix 9.2
3111 'SQLINT' => 'I',
3112 'SQLSERIAL' => 'I',
3113 'SQLSMINT' => 'I',
3114 'SQLSMFLOAT' => 'N',
3115 'SQLFLOAT' => 'N',
3116 'SQLMONEY' => 'N',
3117 'SQLDECIMAL' => 'N',
3118 'SQLDATE' => 'D',
3119 'SQLVCHAR' => 'C',
3120 'SQLCHAR' => 'C',
3121 'SQLDTIME' => 'T',
3122 'SQLINTERVAL' => 'N',
3123 'SQLBYTES' => 'B',
3124 'SQLTEXT' => 'X'
3127 $tmap = false;
3128 $t = strtoupper($t);
3129 $tmap = @$typeMap[$t];
3130 switch ($tmap) {
3131 case 'C':
3133 // is the char field is too long, return as text field...
3134 if ($this->blobSize >= 0) {
3135 if ($len > $this->blobSize) return 'X';
3136 } else if ($len > 250) {
3137 return 'X';
3139 return 'C';
3141 case 'I':
3142 if (!empty($fieldobj->primary_key)) return 'R';
3143 return 'I';
3145 case false:
3146 return 'N';
3148 case 'B':
3149 if (isset($fieldobj->binary))
3150 return ($fieldobj->binary) ? 'B' : 'X';
3151 return 'B';
3153 case 'D':
3154 if (!empty($this->datetime)) return 'T';
3155 return 'D';
3157 default:
3158 if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
3159 return $tmap;
3163 function _close() {}
3166 * set/returns the current recordset page when paginating
3168 function AbsolutePage($page=-1)
3170 if ($page != -1) $this->_currentPage = $page;
3171 return $this->_currentPage;
3175 * set/returns the status of the atFirstPage flag when paginating
3177 function AtFirstPage($status=false)
3179 if ($status != false) $this->_atFirstPage = $status;
3180 return $this->_atFirstPage;
3183 function LastPageNo($page = false)
3185 if ($page != false) $this->_lastPageNo = $page;
3186 return $this->_lastPageNo;
3190 * set/returns the status of the atLastPage flag when paginating
3192 function AtLastPage($status=false)
3194 if ($status != false) $this->_atLastPage = $status;
3195 return $this->_atLastPage;
3198 } // end class ADORecordSet
3200 //==============================================================================================
3201 // CLASS ADORecordSet_array
3202 //==============================================================================================
3205 * This class encapsulates the concept of a recordset created in memory
3206 * as an array. This is useful for the creation of cached recordsets.
3208 * Note that the constructor is different from the standard ADORecordSet
3211 class ADORecordSet_array extends ADORecordSet
3213 var $databaseType = 'array';
3215 var $_array; // holds the 2-dimensional data array
3216 var $_types; // the array of types of each column (C B I L M)
3217 var $_colnames; // names of each column in array
3218 var $_skiprow1; // skip 1st row because it holds column names
3219 var $_fieldarr; // holds array of field objects
3220 var $canSeek = true;
3221 var $affectedrows = false;
3222 var $insertid = false;
3223 var $sql = '';
3224 var $compat = false;
3226 * Constructor
3229 function ADORecordSet_array($fakeid=1)
3231 global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
3233 // fetch() on EOF does not delete $this->fields
3234 $this->compat = !empty($ADODB_COMPAT_FETCH);
3235 $this->ADORecordSet($fakeid); // fake queryID
3236 $this->fetchMode = $ADODB_FETCH_MODE;
3241 * Setup the array.
3243 * @param array is a 2-dimensional array holding the data.
3244 * The first row should hold the column names
3245 * unless paramter $colnames is used.
3246 * @param typearr holds an array of types. These are the same types
3247 * used in MetaTypes (C,B,L,I,N).
3248 * @param [colnames] array of column names. If set, then the first row of
3249 * $array should not hold the column names.
3251 function InitArray($array,$typearr,$colnames=false)
3253 $this->_array = $array;
3254 $this->_types = $typearr;
3255 if ($colnames) {
3256 $this->_skiprow1 = false;
3257 $this->_colnames = $colnames;
3258 } else {
3259 $this->_skiprow1 = true;
3260 $this->_colnames = $array[0];
3262 $this->Init();
3265 * Setup the Array and datatype file objects
3267 * @param array is a 2-dimensional array holding the data.
3268 * The first row should hold the column names
3269 * unless paramter $colnames is used.
3270 * @param fieldarr holds an array of ADOFieldObject's.
3272 function InitArrayFields($array,$fieldarr)
3274 $this->_array = $array;
3275 $this->_skiprow1= false;
3276 if ($fieldarr) {
3277 $this->_fieldobjects = $fieldarr;
3279 $this->Init();
3282 function &GetArray($nRows=-1)
3284 if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
3285 return $this->_array;
3286 } else {
3287 $arr =& ADORecordSet::GetArray($nRows);
3288 return $arr;
3292 function _initrs()
3294 $this->_numOfRows = sizeof($this->_array);
3295 if ($this->_skiprow1) $this->_numOfRows -= 1;
3297 $this->_numOfFields =(isset($this->_fieldobjects)) ?
3298 sizeof($this->_fieldobjects):sizeof($this->_types);
3301 /* Use associative array to get fields array */
3302 function Fields($colname)
3304 if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
3306 if (!$this->bind) {
3307 $this->bind = array();
3308 for ($i=0; $i < $this->_numOfFields; $i++) {
3309 $o = $this->FetchField($i);
3310 $this->bind[strtoupper($o->name)] = $i;
3313 return $this->fields[$this->bind[strtoupper($colname)]];
3316 function &FetchField($fieldOffset = -1)
3318 if (isset($this->_fieldobjects)) {
3319 return $this->_fieldobjects[$fieldOffset];
3321 $o = new ADOFieldObject();
3322 $o->name = $this->_colnames[$fieldOffset];
3323 $o->type = $this->_types[$fieldOffset];
3324 $o->max_length = -1; // length not known
3326 return $o;
3329 function _seek($row)
3331 if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
3332 $this->_currentRow = $row;
3333 if ($this->_skiprow1) $row += 1;
3334 $this->fields = $this->_array[$row];
3335 return true;
3337 return false;
3340 function MoveNext()
3342 if (!$this->EOF) {
3343 $this->_currentRow++;
3345 $pos = $this->_currentRow;
3347 if ($this->_numOfRows <= $pos) {
3348 if (!$this->compat) $this->fields = false;
3349 } else {
3350 if ($this->_skiprow1) $pos += 1;
3351 $this->fields = $this->_array[$pos];
3352 return true;
3354 $this->EOF = true;
3357 return false;
3360 function _fetch()
3362 $pos = $this->_currentRow;
3364 if ($this->_numOfRows <= $pos) {
3365 if (!$this->compat) $this->fields = false;
3366 return false;
3368 if ($this->_skiprow1) $pos += 1;
3369 $this->fields = $this->_array[$pos];
3370 return true;
3373 function _close()
3375 return true;
3378 } // ADORecordSet_array
3380 //==============================================================================================
3381 // HELPER FUNCTIONS
3382 //==============================================================================================
3385 * Synonym for ADOLoadCode. Private function. Do not use.
3387 * @deprecated
3389 function ADOLoadDB($dbType)
3391 return ADOLoadCode($dbType);
3395 * Load the code for a specific database driver. Private function. Do not use.
3397 function ADOLoadCode($dbType)
3399 global $ADODB_LASTDB;
3401 if (!$dbType) return false;
3402 $db = strtolower($dbType);
3403 switch ($db) {
3404 case 'maxsql': $db = 'mysqlt'; break;
3405 case 'postgres':
3406 case 'pgsql': $db = 'postgres7'; break;
3408 @include_once(ADODB_DIR."/drivers/adodb-".$db.".inc.php");
3409 $ADODB_LASTDB = $db;
3411 $ok = class_exists("ADODB_" . $db);
3412 if ($ok) return $db;
3414 $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
3415 if (file_exists($file)) ADOConnection::outp("Missing file: $file");
3416 else ADOConnection::outp("Syntax error in file: $file");
3417 return false;
3421 * synonym for ADONewConnection for people like me who cannot remember the correct name
3423 function &NewADOConnection($db='')
3425 $tmp =& ADONewConnection($db);
3426 return $tmp;
3430 * Instantiate a new Connection class for a specific database driver.
3432 * @param [db] is the database Connection object to create. If undefined,
3433 * use the last database driver that was loaded by ADOLoadCode().
3435 * @return the freshly created instance of the Connection class.
3437 function &ADONewConnection($db='')
3439 GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
3441 if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
3442 $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
3444 if (!empty($ADODB_NEWCONNECTION)) {
3445 $obj = $ADODB_NEWCONNECTION($db);
3446 if ($obj) {
3447 if ($errorfn) $obj->raiseErrorFn = $errorfn;
3448 return $obj;
3452 if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
3453 if (empty($db)) $db = $ADODB_LASTDB;
3455 if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
3457 if (!$db) {
3458 if ($errorfn) {
3459 // raise an error
3460 $ignore = false;
3461 $errorfn('ADONewConnection', 'ADONewConnection', -998,
3462 "could not load the database driver for '$db",
3463 $db,false,$ignore);
3464 } else
3465 ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
3467 return false;
3470 $cls = 'ADODB_'.$db;
3471 if (!class_exists($cls)) {
3472 adodb_backtrace();
3473 return false;
3476 $obj =& new $cls();
3477 if ($errorfn) $obj->raiseErrorFn = $errorfn;
3479 return $obj;
3482 // $perf == true means called by NewPerfMonitor()
3483 function _adodb_getdriver($provider,$drivername,$perf=false)
3485 if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado')
3486 $drivername = $provider;
3487 else {
3488 if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5);
3489 else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4);
3490 else
3491 switch($drivername) {
3492 case 'oracle': $drivername = 'oci8';break;
3493 //case 'sybase': $drivername = 'mssql';break;
3494 case 'access':
3495 if ($perf) $drivername = '';
3496 break;
3497 case 'db2':
3498 break;
3499 default:
3500 $drivername = 'generic';
3501 break;
3505 return $drivername;
3508 function &NewPerfMonitor(&$conn)
3510 $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
3511 if (!$drivername || $drivername == 'generic') return false;
3512 include_once(ADODB_DIR.'/adodb-perf.inc.php');
3513 @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
3514 $class = "Perf_$drivername";
3515 if (!class_exists($class)) return false;
3516 $perf =& new $class($conn);
3518 return $perf;
3521 function &NewDataDictionary(&$conn)
3523 $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
3525 include_once(ADODB_DIR.'/adodb-lib.inc.php');
3526 include_once(ADODB_DIR.'/adodb-datadict.inc.php');
3527 $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
3529 if (!file_exists($path)) {
3530 ADOConnection::outp("Database driver '$path' not available");
3531 return false;
3533 include_once($path);
3534 $class = "ADODB2_$drivername";
3535 $dict =& new $class();
3536 $dict->dataProvider = $conn->dataProvider;
3537 $dict->connection = &$conn;
3538 $dict->upperName = strtoupper($drivername);
3539 $dict->quote = $conn->nameQuote;
3540 if (is_resource($conn->_connectionID))
3541 $dict->serverInfo = $conn->ServerInfo();
3543 return $dict;
3548 * Save a file $filename and its $contents (normally for caching) with file locking
3550 function adodb_write_file($filename, $contents,$debug=false)
3552 # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows
3553 # So to simulate locking, we assume that rename is an atomic operation.
3554 # First we delete $filename, then we create a $tempfile write to it and
3555 # rename to the desired $filename. If the rename works, then we successfully
3556 # modified the file exclusively.
3557 # What a stupid need - having to simulate locking.
3558 # Risks:
3559 # 1. $tempfile name is not unique -- very very low
3560 # 2. unlink($filename) fails -- ok, rename will fail
3561 # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs
3562 # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated
3563 if (strncmp(PHP_OS,'WIN',3) === 0) {
3564 // skip the decimal place
3565 $mtime = substr(str_replace(' ','_',microtime()),2);
3566 // getmypid() actually returns 0 on Win98 - never mind!
3567 $tmpname = $filename.uniqid($mtime).getmypid();
3568 if (!($fd = fopen($tmpname,'a'))) return false;
3569 $ok = ftruncate($fd,0);
3570 if (!fwrite($fd,$contents)) $ok = false;
3571 fclose($fd);
3572 chmod($tmpname,0644);
3573 // the tricky moment
3574 @unlink($filename);
3575 if (!@rename($tmpname,$filename)) {
3576 unlink($tmpname);
3577 $ok = false;
3579 if (!$ok) {
3580 if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));
3582 return $ok;
3584 if (!($fd = fopen($filename, 'a'))) return false;
3585 if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {
3586 $ok = fwrite( $fd, $contents );
3587 fclose($fd);
3588 chmod($filename,0644);
3589 }else {
3590 fclose($fd);
3591 if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");
3592 $ok = false;
3595 return $ok;
3599 Perform a print_r, with pre tags for better formatting.
3601 function adodb_pr($var)
3603 if (isset($_SERVER['HTTP_USER_AGENT'])) {
3604 echo " <pre>\n";print_r($var);echo "</pre>\n";
3605 } else
3606 print_r($var);
3610 Perform a stack-crawl and pretty print it.
3612 @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
3613 @param levels Number of levels to display
3615 function adodb_backtrace($printOrArr=true,$levels=9999)
3617 $s = '';
3618 if (PHPVERSION() < 4.3) return;
3620 $html = (isset($_SERVER['HTTP_USER_AGENT']));
3621 $fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
3623 $MAXSTRLEN = 64;
3625 $s = ($html) ? '<pre align=left>' : '';
3627 if (is_array($printOrArr)) $traceArr = $printOrArr;
3628 else $traceArr = debug_backtrace();
3629 array_shift($traceArr);
3630 $tabs = sizeof($traceArr)-1;
3632 foreach ($traceArr as $arr) {
3633 $levels -= 1;
3634 if ($levels < 0) break;
3636 $args = array();
3637 for ($i=0; $i < $tabs; $i++) $s .= ($html) ? ' &nbsp; ' : "\t";
3638 $tabs -= 1;
3639 if ($html) $s .= '<font face="Courier New,Courier">';
3640 if (isset($arr['class'])) $s .= $arr['class'].'.';
3641 if (isset($arr['args']))
3642 foreach($arr['args'] as $v) {
3643 if (is_null($v)) $args[] = 'null';
3644 else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
3645 else if (is_object($v)) $args[] = 'Object:'.get_class($v);
3646 else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
3647 else {
3648 $v = (string) @$v;
3649 $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
3650 if (strlen($v) > $MAXSTRLEN) $str .= '...';
3651 $args[] = $str;
3654 $s .= $arr['function'].'('.implode(', ',$args).')';
3657 $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
3659 $s .= "\n";
3661 if ($html) $s .= '</pre>';
3662 if ($printOrArr) print $s;
3664 return $s;
3667 } // defined