Fixed path to convert files using imagemagick
[openemr.git] / library / adodb / adodb.inc.php
blob43d745e5b63bfafb59e22571eb5541f3bb2ae3d6
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 include_once(dirname(__FILE__) . "/../log.inc");
735 if ($this->fnExecute) {
736 $fn = $this->fnExecute;
737 $ret =& $fn($this,$sql,$inputarr);
738 if (isset($ret)) return $ret;
740 if ($inputarr && is_array($inputarr)) {
741 $element0 = reset($inputarr);
742 # is_object check is because oci8 descriptors can be passed in
743 $array_2d = is_array($element0) && !is_object(reset($element0));
745 if (!is_array($sql) && !$this->_bindInputArray) {
746 $sqlarr = explode('?',$sql);
748 if (!$array_2d) $inputarr = array($inputarr);
749 foreach($inputarr as $arr) {
750 $sql = ''; $i = 0;
751 foreach($arr as $v) {
752 $sql .= $sqlarr[$i];
753 // from Ron Baldwin <ron.baldwin@sourceprose.com>
754 // Only quote string types
755 if (gettype($v) == 'string')
756 $sql .= $this->qstr($v);
757 else if ($v === null)
758 $sql .= 'NULL';
759 else
760 $sql .= $v;
761 $i += 1;
763 $sql .= $sqlarr[$i];
765 if ($i+1 != sizeof($sqlarr))
766 ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
768 $ret =& $this->_Execute($sql,false);
769 if (!$ret) return $ret;
771 } else {
772 if ($array_2d) {
773 $stmt = $this->Prepare($sql);
774 foreach($inputarr as $arr) {
775 $ret =& $this->_Execute($stmt,$arr);
776 if (!$ret) return $ret;
778 } else
779 $ret =& $this->_Execute($sql,$inputarr);
781 } else {
782 $ret =& $this->_Execute($sql,false);
785 // Added for the OpenEMR audit engine
786 if ($ret === false) {
787 auditSQLEvent($sql,false);
789 else {
790 auditSQLEvent($sql,true);
793 return $ret;
796 function& _Execute($sql,$inputarr=false)
798 // debug version of query
799 if ($this->debug) {
800 global $HTTP_SERVER_VARS;
801 $ss = '';
802 if ($inputarr) {
803 foreach($inputarr as $kk=>$vv) {
804 if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
805 $ss .= "($kk=>'$vv') ";
807 $ss = "[ $ss ]";
809 $sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql);
811 // check if running from browser or command-line
812 $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
814 if ($inBrowser)
815 if ($this->debug === -1)
816 ADOConnection::outp( "<br>\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<br>\n",false);
817 else ADOConnection::outp( "<hr />\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<hr />\n",false);
818 else
819 ADOConnection::outp( "=----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false);
821 $this->_queryID = $this->_query($sql,$inputarr);
823 Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
824 because ErrorNo() calls Execute('SELECT @ERROR'), causing recure
826 if ($this->databaseType == 'mssql') {
827 // ErrorNo is a slow function call in mssql, and not reliable
828 // in PHP 4.0.6
829 if($emsg = $this->ErrorMsg()) {
830 $err = $this->ErrorNo();
831 if ($err) {
832 ADOConnection::outp($err.': '.$emsg);
835 } else
836 if (!$this->_queryID) {
837 $e = $this->ErrorNo();
838 $m = $this->ErrorMsg();
839 ADOConnection::outp($e .': '. $m );
841 } else {
842 // non-debug version of query
844 $this->_queryID =@$this->_query($sql,$inputarr);
847 /************************
848 OK, query executed
849 *************************/
850 // error handling if query fails
851 if ($this->_queryID === false) {
852 if ($this->debug == 99) adodb_backtrace(true,5);
853 $fn = $this->raiseErrorFn;
854 if ($fn) {
855 $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
858 return false;
859 } else if ($this->_queryID === true) {
860 // return simplified empty recordset for inserts/updates/deletes with lower overhead
861 $rs =& new ADORecordSet_empty();
862 return $rs;
865 // return real recordset from select statement
866 $rsclass = $this->rsPrefix.$this->databaseType;
867 $rs =& new $rsclass($this->_queryID,$this->fetchMode); // &new not supported by older PHP versions
868 $rs->connection = &$this; // Pablo suggestion
869 $rs->Init();
870 if (is_array($sql)) $rs->sql = $sql[0];
871 else $rs->sql = $sql;
872 if ($rs->_numOfRows <= 0) {
873 global $ADODB_COUNTRECS;
875 if ($ADODB_COUNTRECS) {
876 if (!$rs->EOF){
877 $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
878 $rs->_queryID = $this->_queryID;
879 } else
880 $rs->_numOfRows = 0;
884 return $rs;
887 function CreateSequence($seqname='adodbseq',$startID=1)
889 if (empty($this->_genSeqSQL)) return false;
890 return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
893 function DropSequence($seqname)
895 if (empty($this->_dropSeqSQL)) return false;
896 return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
900 * Generates a sequence id and stores it in $this->genID;
901 * GenID is only available if $this->hasGenID = true;
903 * @param seqname name of sequence to use
904 * @param startID if sequence does not exist, start at this ID
905 * @return 0 if not supported, otherwise a sequence id
907 function GenID($seqname='adodbseq',$startID=1)
909 if (!$this->hasGenID) {
910 return 0; // formerly returns false pre 1.60
913 $getnext = sprintf($this->_genIDSQL,$seqname);
915 $holdtransOK = $this->_transOK;
916 $rs = @$this->Execute($getnext);
917 if (!$rs) {
918 $this->_transOK = $holdtransOK; //if the status was ok before reset
919 $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
920 $rs = $this->Execute($getnext);
922 if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
923 else $this->genID = 0; // false
925 if ($rs) $rs->Close();
927 return $this->genID;
931 * @return the last inserted ID. Not all databases support this.
933 function Insert_ID()
935 if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
936 if ($this->hasInsertID) return $this->_insertid();
937 if ($this->debug) {
938 ADOConnection::outp( '<p>Insert_ID error</p>');
939 adodb_backtrace();
941 return false;
946 * Portable Insert ID. Pablo Roca <pabloroca@mvps.org>
948 * @return the last inserted ID. All databases support this. But aware possible
949 * problems in multiuser environments. Heavy test this before deploying.
951 function PO_Insert_ID($table="", $id="")
953 if ($this->hasInsertID){
954 return $this->Insert_ID();
955 } else {
956 return $this->GetOne("SELECT MAX($id) FROM $table");
961 * @return # rows affected by UPDATE/DELETE
963 function Affected_Rows()
965 if ($this->hasAffectedRows) {
966 if ($this->fnExecute === 'adodb_log_sql') {
967 if ($this->_logsql && $this->_affected !== false) return $this->_affected;
969 $val = $this->_affectedrows();
970 return ($val < 0) ? false : $val;
973 if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
974 return false;
979 * @return the last error message
981 function ErrorMsg()
983 return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
988 * @return the last error number. Normally 0 means no error.
990 function ErrorNo()
992 return ($this->_errorMsg) ? -1 : 0;
995 function MetaError($err=false)
997 include_once(ADODB_DIR."/adodb-error.inc.php");
998 if ($err === false) $err = $this->ErrorNo();
999 return adodb_error($this->dataProvider,$this->databaseType,$err);
1002 function MetaErrorMsg($errno)
1004 include_once(ADODB_DIR."/adodb-error.inc.php");
1005 return adodb_errormsg($errno);
1009 * @returns an array with the primary key columns in it.
1011 function MetaPrimaryKeys($table, $owner=false)
1013 // owner not used in base class - see oci8
1014 $p = array();
1015 $objs =& $this->MetaColumns($table);
1016 if ($objs) {
1017 foreach($objs as $v) {
1018 if (!empty($v->primary_key))
1019 $p[] = $v->name;
1022 if (sizeof($p)) return $p;
1023 if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
1024 return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
1025 return false;
1029 * @returns assoc array where keys are tables, and values are foreign keys
1031 function MetaForeignKeys($table, $owner=false, $upper=false)
1033 return false;
1036 * Choose a database to connect to. Many databases do not support this.
1038 * @param dbName is the name of the database to select
1039 * @return true or false
1041 function SelectDB($dbName)
1042 {return false;}
1046 * Will select, getting rows from $offset (1-based), for $nrows.
1047 * This simulates the MySQL "select * from table limit $offset,$nrows" , and
1048 * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
1049 * MySQL and PostgreSQL parameter ordering is the opposite of the other.
1050 * eg.
1051 * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
1052 * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
1054 * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
1055 * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
1057 * @param sql
1058 * @param [offset] is the row to start calculations from (1-based)
1059 * @param [nrows] is the number of rows to get
1060 * @param [inputarr] array of bind variables
1061 * @param [secs2cache] is a private parameter only used by jlim
1062 * @return the recordset ($rs->databaseType == 'array')
1064 function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
1066 if ($this->hasTop && $nrows > 0) {
1067 // suggested by Reinhard Balling. Access requires top after distinct
1068 // Informix requires first before distinct - F Riosa
1069 $ismssql = (strpos($this->databaseType,'mssql') !== false);
1070 if ($ismssql) $isaccess = false;
1071 else $isaccess = (strpos($this->databaseType,'access') !== false);
1073 if ($offset <= 0) {
1075 // access includes ties in result
1076 if ($isaccess) {
1077 $sql = preg_replace(
1078 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
1080 if ($secs2cache>0) {
1081 $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
1082 } else {
1083 $ret =& $this->Execute($sql,$inputarr);
1085 return $ret; // PHP5 fix
1086 } else if ($ismssql){
1087 $sql = preg_replace(
1088 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
1089 } else {
1090 $sql = preg_replace(
1091 '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
1093 } else {
1094 $nn = $nrows + $offset;
1095 if ($isaccess || $ismssql) {
1096 $sql = preg_replace(
1097 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
1098 } else {
1099 $sql = preg_replace(
1100 '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
1105 // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
1106 // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
1107 global $ADODB_COUNTRECS;
1109 $savec = $ADODB_COUNTRECS;
1110 $ADODB_COUNTRECS = false;
1112 if ($offset>0){
1113 if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
1114 else $rs = &$this->Execute($sql,$inputarr);
1115 } else {
1116 if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
1117 else $rs = &$this->Execute($sql,$inputarr);
1119 $ADODB_COUNTRECS = $savec;
1120 if ($rs && !$rs->EOF) {
1121 $rs =& $this->_rs2rs($rs,$nrows,$offset);
1123 //print_r($rs);
1124 return $rs;
1128 * Create serializable recordset. Breaks rs link to connection.
1130 * @param rs the recordset to serialize
1132 function &SerializableRS(&$rs)
1134 $rs2 =& $this->_rs2rs($rs);
1135 $ignore = false;
1136 $rs2->connection =& $ignore;
1138 return $rs2;
1142 * Convert database recordset to an array recordset
1143 * input recordset's cursor should be at beginning, and
1144 * old $rs will be closed.
1146 * @param rs the recordset to copy
1147 * @param [nrows] number of rows to retrieve (optional)
1148 * @param [offset] offset by number of rows (optional)
1149 * @return the new recordset
1151 function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
1153 if (! $rs) return false;
1155 $dbtype = $rs->databaseType;
1156 if (!$dbtype) {
1157 $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
1158 return $rs;
1160 if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
1161 $rs->MoveFirst();
1162 $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
1163 return $rs;
1165 $flds = array();
1166 for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
1167 $flds[] = $rs->FetchField($i);
1169 $arr =& $rs->GetArrayLimit($nrows,$offset);
1170 //print_r($arr);
1171 if ($close) $rs->Close();
1173 $arrayClass = $this->arrayClass;
1175 $rs2 =& new $arrayClass();
1176 $rs2->connection = &$this;
1177 $rs2->sql = $rs->sql;
1178 $rs2->dataProvider = $this->dataProvider;
1179 $rs2->InitArrayFields($arr,$flds);
1180 return $rs2;
1184 * Return all rows. Compat with PEAR DB
1186 function &GetAll($sql, $inputarr=false)
1188 $arr =& $this->GetArray($sql,$inputarr);
1189 return $arr;
1192 function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
1194 $rs =& $this->Execute($sql, $inputarr);
1195 if (!$rs) return false;
1197 $arr =& $rs->GetAssoc($force_array,$first2cols);
1198 return $arr;
1201 function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
1203 if (!is_numeric($secs2cache)) {
1204 $first2cols = $force_array;
1205 $force_array = $inputarr;
1207 $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);
1208 if (!$rs) return false;
1210 $arr =& $rs->GetAssoc($force_array,$first2cols);
1211 return $arr;
1215 * Return first element of first row of sql statement. Recordset is disposed
1216 * for you.
1218 * @param sql SQL statement
1219 * @param [inputarr] input bind array
1221 function GetOne($sql,$inputarr=false)
1223 global $ADODB_COUNTRECS;
1224 $crecs = $ADODB_COUNTRECS;
1225 $ADODB_COUNTRECS = false;
1227 $ret = false;
1228 $rs = &$this->Execute($sql,$inputarr);
1229 if ($rs) {
1230 if (!$rs->EOF) $ret = reset($rs->fields);
1231 $rs->Close();
1233 $ADODB_COUNTRECS = $crecs;
1234 return $ret;
1237 function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
1239 $ret = false;
1240 $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
1241 if ($rs) {
1242 if (!$rs->EOF) $ret = reset($rs->fields);
1243 $rs->Close();
1246 return $ret;
1249 function GetCol($sql, $inputarr = false, $trim = false)
1251 $rv = false;
1252 $rs = &$this->Execute($sql, $inputarr);
1253 if ($rs) {
1254 $rv = array();
1255 if ($trim) {
1256 while (!$rs->EOF) {
1257 $rv[] = trim(reset($rs->fields));
1258 $rs->MoveNext();
1260 } else {
1261 while (!$rs->EOF) {
1262 $rv[] = reset($rs->fields);
1263 $rs->MoveNext();
1266 $rs->Close();
1268 return $rv;
1271 function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
1273 $rv = false;
1274 $rs = &$this->CacheExecute($secs, $sql, $inputarr);
1275 if ($rs) {
1276 if ($trim) {
1277 while (!$rs->EOF) {
1278 $rv[] = trim(reset($rs->fields));
1279 $rs->MoveNext();
1281 } else {
1282 while (!$rs->EOF) {
1283 $rv[] = reset($rs->fields);
1284 $rs->MoveNext();
1287 $rs->Close();
1289 return $rv;
1293 Calculate the offset of a date for a particular database and generate
1294 appropriate SQL. Useful for calculating future/past dates and storing
1295 in a database.
1297 If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
1299 function OffsetDate($dayFraction,$date=false)
1301 if (!$date) $date = $this->sysDate;
1302 return '('.$date.'+'.$dayFraction.')';
1308 * @param sql SQL statement
1309 * @param [inputarr] input bind array
1311 function &GetArray($sql,$inputarr=false)
1313 global $ADODB_COUNTRECS;
1315 $savec = $ADODB_COUNTRECS;
1316 $ADODB_COUNTRECS = false;
1317 $rs =& $this->Execute($sql,$inputarr);
1318 $ADODB_COUNTRECS = $savec;
1319 if (!$rs)
1320 if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
1321 else return false;
1322 $arr =& $rs->GetArray();
1323 $rs->Close();
1324 return $arr;
1327 function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
1329 global $ADODB_COUNTRECS;
1331 $savec = $ADODB_COUNTRECS;
1332 $ADODB_COUNTRECS = false;
1333 $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
1334 $ADODB_COUNTRECS = $savec;
1336 if (!$rs)
1337 if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
1338 else return false;
1340 $arr =& $rs->GetArray();
1341 $rs->Close();
1342 return $arr;
1348 * Return one row of sql statement. Recordset is disposed for you.
1350 * @param sql SQL statement
1351 * @param [inputarr] input bind array
1353 function &GetRow($sql,$inputarr=false)
1355 global $ADODB_COUNTRECS;
1356 $crecs = $ADODB_COUNTRECS;
1357 $ADODB_COUNTRECS = false;
1359 $rs =& $this->Execute($sql,$inputarr);
1361 $ADODB_COUNTRECS = $crecs;
1362 if ($rs) {
1363 if (!$rs->EOF) $arr = $rs->fields;
1364 else $arr = array();
1365 $rs->Close();
1366 return $arr;
1369 return false;
1372 function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
1374 $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
1375 if ($rs) {
1376 $arr = false;
1377 if (!$rs->EOF) $arr = $rs->fields;
1378 $rs->Close();
1379 return $arr;
1381 return false;
1385 * Insert or replace a single record. Note: this is not the same as MySQL's replace.
1386 * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
1387 * Also note that no table locking is done currently, so it is possible that the
1388 * record be inserted twice by two programs...
1390 * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
1392 * $table table name
1393 * $fieldArray associative array of data (you must quote strings yourself).
1394 * $keyCol the primary key field name or if compound key, array of field names
1395 * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
1396 * but does not work with dates nor SQL functions.
1397 * has_autoinc the primary key is an auto-inc field, so skip in insert.
1399 * Currently blob replace not supported
1401 * returns 0 = fail, 1 = update, 2 = insert
1404 function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
1406 global $ADODB_INCLUDED_LIB;
1407 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
1409 return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
1414 * Will select, getting rows from $offset (1-based), for $nrows.
1415 * This simulates the MySQL "select * from table limit $offset,$nrows" , and
1416 * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
1417 * MySQL and PostgreSQL parameter ordering is the opposite of the other.
1418 * eg.
1419 * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
1420 * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
1422 * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
1424 * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
1425 * @param sql
1426 * @param [offset] is the row to start calculations from (1-based)
1427 * @param [nrows] is the number of rows to get
1428 * @param [inputarr] array of bind variables
1429 * @return the recordset ($rs->databaseType == 'array')
1431 function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
1433 if (!is_numeric($secs2cache)) {
1434 if ($sql === false) $sql = -1;
1435 if ($offset == -1) $offset = false;
1436 // sql, nrows, offset,inputarr
1437 $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
1438 } else {
1439 if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
1440 $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
1442 return $rs;
1446 * Flush cached recordsets that match a particular $sql statement.
1447 * If $sql == false, then we purge all files in the cache.
1449 function CacheFlush($sql=false,$inputarr=false)
1451 global $ADODB_CACHE_DIR;
1453 if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
1454 if (strncmp(PHP_OS,'WIN',3) === 0) {
1455 $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
1456 } else {
1457 $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache';
1458 // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
1460 if ($this->debug) {
1461 ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
1462 } else {
1463 exec($cmd);
1465 return;
1467 $f = $this->_gencachename($sql.serialize($inputarr),false);
1468 adodb_write_file($f,''); // is adodb_write_file needed?
1469 if (!@unlink($f)) {
1470 if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
1475 * Private function to generate filename for caching.
1476 * Filename is generated based on:
1478 * - sql statement
1479 * - database type (oci8, ibase, ifx, etc)
1480 * - database name
1481 * - userid
1483 * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
1484 * Assuming that we can have 50,000 files per directory with good performance,
1485 * then we can scale to 12.8 million unique cached recordsets. Wow!
1487 function _gencachename($sql,$createdir)
1489 global $ADODB_CACHE_DIR;
1491 $m = md5($sql.$this->databaseType.$this->database.$this->user);
1492 $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2);
1493 if ($createdir && !file_exists($dir)) {
1494 $oldu = umask(0);
1495 if (!mkdir($dir,0771))
1496 if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
1497 umask($oldu);
1499 return $dir.'/adodb_'.$m.'.cache';
1504 * Execute SQL, caching recordsets.
1506 * @param [secs2cache] seconds to cache data, set to 0 to force query.
1507 * This is an optional parameter.
1508 * @param sql SQL statement to execute
1509 * @param [inputarr] holds the input data to bind to
1510 * @return RecordSet or false
1512 function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
1514 if (!is_numeric($secs2cache)) {
1515 $inputarr = $sql;
1516 $sql = $secs2cache;
1517 $secs2cache = $this->cacheSecs;
1519 global $ADODB_INCLUDED_CSV;
1520 if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
1522 if (is_array($sql)) $sql = $sql[0];
1524 $md5file = $this->_gencachename($sql.serialize($inputarr),true);
1525 $err = '';
1527 if ($secs2cache > 0){
1528 $rs = &csv2rs($md5file,$err,$secs2cache);
1529 $this->numCacheHits += 1;
1530 } else {
1531 $err='Timeout 1';
1532 $rs = false;
1533 $this->numCacheMisses += 1;
1535 if (!$rs) {
1536 // no cached rs found
1537 if ($this->debug) {
1538 if (get_magic_quotes_runtime()) {
1539 ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
1541 if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
1543 $rs = &$this->Execute($sql,$inputarr);
1544 if ($rs) {
1545 $eof = $rs->EOF;
1546 $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
1547 $txt = _rs2serialize($rs,false,$sql); // serialize
1549 if (!adodb_write_file($md5file,$txt,$this->debug)) {
1550 if ($fn = $this->raiseErrorFn) {
1551 $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
1553 if ($this->debug) ADOConnection::outp( " Cache write error");
1555 if ($rs->EOF && !$eof) {
1556 $rs->MoveFirst();
1557 //$rs = &csv2rs($md5file,$err);
1558 $rs->connection = &$this; // Pablo suggestion
1561 } else
1562 @unlink($md5file);
1563 } else {
1564 $this->_errorMsg = '';
1565 $this->_errorCode = 0;
1567 if ($this->fnCacheExecute) {
1568 $fn = $this->fnCacheExecute;
1569 $fn($this, $secs2cache, $sql, $inputarr);
1571 // ok, set cached object found
1572 $rs->connection = &$this; // Pablo suggestion
1573 if ($this->debug){
1574 global $HTTP_SERVER_VARS;
1576 $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
1577 $ttl = $rs->timeCreated + $secs2cache - time();
1578 $s = is_array($sql) ? $sql[0] : $sql;
1579 if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
1581 ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
1584 return $rs;
1589 * Generates an Update Query based on an existing recordset.
1590 * $arrFields is an associative array of fields with the value
1591 * that should be assigned.
1593 * Note: This function should only be used on a recordset
1594 * that is run against a single table and sql should only
1595 * be a simple select stmt with no groupby/orderby/limit
1597 * "Jonathan Younger" <jyounger@unilab.com>
1599 function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false)
1601 global $ADODB_INCLUDED_LIB;
1602 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
1603 return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq);
1608 * Generates an Insert Query based on an existing recordset.
1609 * $arrFields is an associative array of fields with the value
1610 * that should be assigned.
1612 * Note: This function should only be used on a recordset
1613 * that is run against a single table.
1615 function GetInsertSQL(&$rs, $arrFields,$magicq=false)
1617 global $ADODB_INCLUDED_LIB;
1618 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
1619 return _adodb_getinsertsql($this,$rs,$arrFields,$magicq);
1624 * Update a blob column, given a where clause. There are more sophisticated
1625 * blob handling functions that we could have implemented, but all require
1626 * a very complex API. Instead we have chosen something that is extremely
1627 * simple to understand and use.
1629 * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
1631 * Usage to update a $blobvalue which has a primary key blob_id=1 into a
1632 * field blobtable.blobcolumn:
1634 * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
1636 * Insert example:
1638 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
1639 * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
1642 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
1644 return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
1648 * Usage:
1649 * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
1651 * $blobtype supports 'BLOB' and 'CLOB'
1653 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
1654 * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
1656 function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
1658 $fd = fopen($path,'rb');
1659 if ($fd === false) return false;
1660 $val = fread($fd,filesize($path));
1661 fclose($fd);
1662 return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
1665 function BlobDecode($blob)
1667 return $blob;
1670 function BlobEncode($blob)
1672 return $blob;
1675 function SetCharSet($charset)
1677 return false;
1680 function IfNull( $field, $ifNull )
1682 return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
1685 function LogSQL($enable=true)
1687 include_once(ADODB_DIR.'/adodb-perf.inc.php');
1689 if ($enable) $this->fnExecute = 'adodb_log_sql';
1690 else $this->fnExecute = false;
1692 $old = $this->_logsql;
1693 $this->_logsql = $enable;
1694 if ($enable && !$old) $this->_affected = false;
1695 return $old;
1698 function GetCharSet()
1700 return false;
1704 * Usage:
1705 * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
1707 * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
1708 * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
1710 function UpdateClob($table,$column,$val,$where)
1712 return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
1717 * Change the SQL connection locale to a specified locale.
1718 * This is used to get the date formats written depending on the client locale.
1720 function SetDateLocale($locale = 'En')
1722 $this->locale = $locale;
1723 switch ($locale)
1725 default:
1726 case 'En':
1727 $this->fmtDate="Y-m-d";
1728 $this->fmtTimeStamp = "Y-m-d H:i:s";
1729 break;
1731 case 'Fr':
1732 case 'Ro':
1733 case 'It':
1734 $this->fmtDate="d-m-Y";
1735 $this->fmtTimeStamp = "d-m-Y H:i:s";
1736 break;
1738 case 'Ge':
1739 $this->fmtDate="d.m.Y";
1740 $this->fmtTimeStamp = "d.m.Y H:i:s";
1741 break;
1747 * $meta contains the desired type, which could be...
1748 * C for character. You will have to define the precision yourself.
1749 * X for teXt. For unlimited character lengths.
1750 * B for Binary
1751 * F for floating point, with no need to define scale and precision
1752 * N for decimal numbers, you will have to define the (scale, precision) yourself
1753 * D for date
1754 * T for timestamp
1755 * L for logical/Boolean
1756 * I for integer
1757 * R for autoincrement counter/integer
1758 * and if you want to use double-byte, add a 2 to the end, like C2 or X2.
1761 * @return the actual type of the data or false if no such type available
1763 function ActualType($meta)
1765 switch($meta) {
1766 case 'C':
1767 case 'X':
1768 return 'VARCHAR';
1769 case 'B':
1771 case 'D':
1772 case 'T':
1773 case 'L':
1775 case 'R':
1777 case 'I':
1778 case 'N':
1779 return false;
1785 * Close Connection
1787 function Close()
1789 return $this->_close();
1791 // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need
1792 // to be closed too!
1793 //if ($this->_isPersistentConnection != true) return $this->_close();
1794 //else return true;
1798 * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
1800 * @return true if succeeded or false if database does not support transactions
1802 function BeginTrans() {return false;}
1806 * If database does not support transactions, always return true as data always commited
1808 * @param $ok set to false to rollback transaction, true to commit
1810 * @return true/false.
1812 function CommitTrans($ok=true)
1813 { return true;}
1817 * If database does not support transactions, rollbacks always fail, so return false
1819 * @return true/false.
1821 function RollbackTrans()
1822 { return false;}
1826 * return the databases that the driver can connect to.
1827 * Some databases will return an empty array.
1829 * @return an array of database names.
1831 function MetaDatabases()
1833 global $ADODB_FETCH_MODE;
1835 if ($this->metaDatabasesSQL) {
1836 $save = $ADODB_FETCH_MODE;
1837 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
1839 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
1841 $arr = $this->GetCol($this->metaDatabasesSQL);
1842 if (isset($savem)) $this->SetFetchMode($savem);
1843 $ADODB_FETCH_MODE = $save;
1845 return $arr;
1848 return false;
1852 * @param ttype can either be 'VIEW' or 'TABLE' or false.
1853 * If false, both views and tables are returned.
1854 * "VIEW" returns only views
1855 * "TABLE" returns only tables
1856 * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
1857 * @param mask is the input mask - only supported by oci8 and postgresql
1859 * @return array of tables for current database.
1861 function &MetaTables($ttype=false,$showSchema=false,$mask=false)
1863 global $ADODB_FETCH_MODE;
1865 if ($mask) return false;
1867 if ($this->metaTablesSQL) {
1868 // complicated state saving by the need for backward compat
1869 $save = $ADODB_FETCH_MODE;
1870 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
1872 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
1874 $rs = $this->Execute($this->metaTablesSQL);
1875 if (isset($savem)) $this->SetFetchMode($savem);
1876 $ADODB_FETCH_MODE = $save;
1878 if ($rs === false) return false;
1879 $arr =& $rs->GetArray();
1880 $arr2 = array();
1882 if ($hast = ($ttype && isset($arr[0][1]))) {
1883 $showt = strncmp($ttype,'T',1);
1886 for ($i=0; $i < sizeof($arr); $i++) {
1887 if ($hast) {
1888 if ($showt == 0) {
1889 if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
1890 } else {
1891 if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
1893 } else
1894 $arr2[] = trim($arr[$i][0]);
1896 $rs->Close();
1897 return $arr2;
1899 return false;
1903 function _findschema(&$table,&$schema)
1905 if (!$schema && ($at = strpos($table,'.')) !== false) {
1906 $schema = substr($table,0,$at);
1907 $table = substr($table,$at+1);
1912 * List columns in a database as an array of ADOFieldObjects.
1913 * See top of file for definition of object.
1915 * @param table table name to query
1916 * @param upper uppercase table name (required by some databases)
1917 * @schema is optional database schema to use - not supported by all databases.
1919 * @return array of ADOFieldObjects for current table.
1921 function &MetaColumns($table,$upper=true)
1923 global $ADODB_FETCH_MODE;
1925 if (!empty($this->metaColumnsSQL)) {
1927 $schema = false;
1928 $this->_findschema($table,$schema);
1930 $save = $ADODB_FETCH_MODE;
1931 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
1932 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
1933 $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table));
1934 if (isset($savem)) $this->SetFetchMode($savem);
1935 $ADODB_FETCH_MODE = $save;
1936 if ($rs === false) return false;
1938 $retarr = array();
1939 while (!$rs->EOF) { //print_r($rs->fields);
1940 $fld =& new ADOFieldObject();
1941 $fld->name = $rs->fields[0];
1942 $fld->type = $rs->fields[1];
1943 if (isset($rs->fields[3]) && $rs->fields[3]) {
1944 if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
1945 $fld->scale = $rs->fields[4];
1946 if ($fld->scale>0) $fld->max_length += 1;
1947 } else
1948 $fld->max_length = $rs->fields[2];
1950 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
1951 else $retarr[strtoupper($fld->name)] = $fld;
1952 $rs->MoveNext();
1954 $rs->Close();
1955 return $retarr;
1957 return false;
1961 * List indexes on a table as an array.
1962 * @param table table name to query
1963 * @param primary include primary keys.
1965 * @return array of indexes on current table.
1967 function &MetaIndexes($table, $primary = false, $owner = false)
1969 return FALSE;
1973 * List columns names in a table as an array.
1974 * @param table table name to query
1976 * @return array of column names for current table.
1978 function &MetaColumnNames($table)
1980 $objarr =& $this->MetaColumns($table);
1981 if (!is_array($objarr)) return false;
1983 $arr = array();
1984 foreach($objarr as $v) {
1985 $arr[] = $v->name;
1987 return $arr;
1991 * Different SQL databases used different methods to combine strings together.
1992 * This function provides a wrapper.
1994 * param s variable number of string parameters
1996 * Usage: $db->Concat($str1,$str2);
1998 * @return concatenated string
2000 function Concat()
2002 $arr = func_get_args();
2003 return implode($this->concat_operator, $arr);
2008 * Converts a date "d" to a string that the database can understand.
2010 * @param d a date in Unix date time format.
2012 * @return date string in database date format
2014 function DBDate($d)
2016 if (empty($d) && $d !== 0) return 'null';
2018 if (is_string($d) && !is_numeric($d)) {
2019 if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
2020 if ($this->isoDates) return "'$d'";
2021 $d = ADOConnection::UnixDate($d);
2024 return adodb_date($this->fmtDate,$d);
2029 * Converts a timestamp "ts" to a string that the database can understand.
2031 * @param ts a timestamp in Unix date time format.
2033 * @return timestamp string in database timestamp format
2035 function DBTimeStamp($ts)
2037 if (empty($ts) && $ts !== 0) return 'null';
2039 # strlen(14) allows YYYYMMDDHHMMSS format
2040 if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
2041 return adodb_date($this->fmtTimeStamp,$ts);
2043 if ($ts === 'null') return $ts;
2044 if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
2046 $ts = ADOConnection::UnixTimeStamp($ts);
2047 return adodb_date($this->fmtTimeStamp,$ts);
2051 * Also in ADORecordSet.
2052 * @param $v is a date string in YYYY-MM-DD format
2054 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2056 function UnixDate($v)
2058 if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
2059 ($v), $rr)) return false;
2061 if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
2062 // h-m-s-MM-DD-YY
2063 return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2068 * Also in ADORecordSet.
2069 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
2071 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2073 function UnixTimeStamp($v)
2075 if (!preg_match(
2076 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
2077 ($v), $rr)) return false;
2079 if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
2081 // h-m-s-MM-DD-YY
2082 if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2083 return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
2087 * Also in ADORecordSet.
2089 * Format database date based on user defined format.
2091 * @param v is the character date in YYYY-MM-DD format, returned by database
2092 * @param fmt is the format to apply to it, using date()
2094 * @return a date formated as user desires
2097 function UserDate($v,$fmt='Y-m-d')
2099 $tt = $this->UnixDate($v);
2100 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2101 if (($tt === false || $tt == -1) && $v != false) return $v;
2102 else if ($tt == 0) return $this->emptyDate;
2103 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
2106 return adodb_date($fmt,$tt);
2112 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
2113 * @param fmt is the format to apply to it, using date()
2115 * @return a timestamp formated as user desires
2117 function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
2119 # strlen(14) allows YYYYMMDDHHMMSS format
2120 if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
2121 $tt = $this->UnixTimeStamp($v);
2122 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2123 if (($tt === false || $tt == -1) && $v != false) return $v;
2124 if ($tt == 0) return $this->emptyTimeStamp;
2125 return adodb_date($fmt,$tt);
2129 * Quotes a string, without prefixing nor appending quotes.
2131 function addq($s,$magicq=false)
2133 if (!$magic_quotes) {
2135 if ($this->replaceQuote[0] == '\\'){
2136 // only since php 4.0.5
2137 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
2138 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
2140 return str_replace("'",$this->replaceQuote,$s);
2143 // undo magic quotes for "
2144 $s = str_replace('\\"','"',$s);
2146 if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
2147 return $s;
2148 else {// change \' to '' for sybase/mssql
2149 $s = str_replace('\\\\','\\',$s);
2150 return str_replace("\\'",$this->replaceQuote,$s);
2155 * Correctly quotes a string so that all strings are escaped. We prefix and append
2156 * to the string single-quotes.
2157 * An example is $db->qstr("Don't bother",magic_quotes_runtime());
2159 * @param s the string to quote
2160 * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
2161 * This undoes the stupidity of magic quotes for GPC.
2163 * @return quoted string to be sent back to database
2165 function qstr($s,$magic_quotes=false)
2167 if (!$magic_quotes) {
2169 if ($this->replaceQuote[0] == '\\'){
2170 // only since php 4.0.5
2171 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
2172 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
2174 return "'".str_replace("'",$this->replaceQuote,$s)."'";
2177 // undo magic quotes for "
2178 $s = str_replace('\\"','"',$s);
2180 if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
2181 return "'$s'";
2182 else {// change \' to '' for sybase/mssql
2183 $s = str_replace('\\\\','\\',$s);
2184 return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
2190 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
2191 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
2192 * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
2194 * See readme.htm#ex8 for an example of usage.
2196 * @param sql
2197 * @param nrows is the number of rows per page to get
2198 * @param page is the page number to get (1-based)
2199 * @param [inputarr] array of bind variables
2200 * @param [secs2cache] is a private parameter only used by jlim
2201 * @return the recordset ($rs->databaseType == 'array')
2203 * NOTE: phpLens uses a different algorithm and does not use PageExecute().
2206 function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0)
2208 global $ADODB_INCLUDED_LIB;
2209 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
2210 if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
2211 return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
2217 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
2218 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
2219 * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
2221 * @param secs2cache seconds to cache data, set to 0 to force query
2222 * @param sql
2223 * @param nrows is the number of rows per page to get
2224 * @param page is the page number to get (1-based)
2225 * @param [inputarr] array of bind variables
2226 * @return the recordset ($rs->databaseType == 'array')
2228 function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false)
2230 /*switch($this->dataProvider) {
2231 case 'postgres':
2232 case 'mysql':
2233 break;
2234 default: $secs2cache = 0; break;
2236 $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
2237 return $rs;
2240 } // end class ADOConnection
2244 //==============================================================================================
2245 // CLASS ADOFetchObj
2246 //==============================================================================================
2249 * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
2251 class ADOFetchObj {
2254 //==============================================================================================
2255 // CLASS ADORecordSet_empty
2256 //==============================================================================================
2259 * Lightweight recordset when there are no records to be returned
2261 class ADORecordSet_empty
2263 var $dataProvider = 'empty';
2264 var $databaseType = false;
2265 var $EOF = true;
2266 var $_numOfRows = 0;
2267 var $fields = false;
2268 var $connection = false;
2269 function RowCount() {return 0;}
2270 function RecordCount() {return 0;}
2271 function PO_RecordCount(){return 0;}
2272 function Close(){return true;}
2273 function FetchRow() {return false;}
2274 function FieldCount(){ return 0;}
2277 //==============================================================================================
2278 // DATE AND TIME FUNCTIONS
2279 //==============================================================================================
2280 include_once(ADODB_DIR.'/adodb-time.inc.php');
2282 //==============================================================================================
2283 // CLASS ADORecordSet
2284 //==============================================================================================
2286 if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
2287 else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
2289 * RecordSet class that represents the dataset returned by the database.
2290 * To keep memory overhead low, this class holds only the current row in memory.
2291 * No prefetching of data is done, so the RecordCount() can return -1 ( which
2292 * means recordcount not known).
2294 class ADORecordSet extends ADODB_BASE_RS {
2296 * public variables
2298 var $dataProvider = "native";
2299 var $fields = false; /// holds the current row data
2300 var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
2301 /// in other words, we use a text area for editing.
2302 var $canSeek = false; /// indicates that seek is supported
2303 var $sql; /// sql text
2304 var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
2306 var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
2307 var $emptyDate = '&nbsp;'; /// what to display when $time==0
2308 var $debug = false;
2309 var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
2311 var $bind = false; /// used by Fields() to hold array - should be private?
2312 var $fetchMode; /// default fetch mode
2313 var $connection = false; /// the parent connection
2315 * private variables
2317 var $_numOfRows = -1; /** number of rows, or -1 */
2318 var $_numOfFields = -1; /** number of fields in recordset */
2319 var $_queryID = -1; /** This variable keeps the result link identifier. */
2320 var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
2321 var $_closed = false; /** has recordset been closed */
2322 var $_inited = false; /** Init() should only be called once */
2323 var $_obj; /** Used by FetchObj */
2324 var $_names; /** Used by FetchObj */
2326 var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */
2327 var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */
2328 var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */
2329 var $_lastPageNo = -1;
2330 var $_maxRecordCount = 0;
2331 var $datetime = false;
2334 * Constructor
2336 * @param queryID this is the queryID returned by ADOConnection->_query()
2339 function ADORecordSet($queryID)
2341 $this->_queryID = $queryID;
2346 function Init()
2348 if ($this->_inited) return;
2349 $this->_inited = true;
2350 if ($this->_queryID) @$this->_initrs();
2351 else {
2352 $this->_numOfRows = 0;
2353 $this->_numOfFields = 0;
2355 if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
2357 $this->_currentRow = 0;
2358 if ($this->EOF = ($this->_fetch() === false)) {
2359 $this->_numOfRows = 0; // _numOfRows could be -1
2361 } else {
2362 $this->EOF = true;
2368 * Generate a SELECT tag string from a recordset, and return the string.
2369 * If the recordset has 2 cols, we treat the 1st col as the containing
2370 * the text to display to the user, and 2nd col as the return value. Default
2371 * strings are compared with the FIRST column.
2373 * @param name name of SELECT tag
2374 * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
2375 * @param [blank1stItem] true to leave the 1st item in list empty
2376 * @param [multiple] true for listbox, false for popup
2377 * @param [size] #rows to show for listbox. not used by popup
2378 * @param [selectAttr] additional attributes to defined for SELECT tag.
2379 * useful for holding javascript onChange='...' handlers.
2380 & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
2381 * column 0 (1st col) if this is true. This is not documented.
2383 * @return HTML
2385 * changes by glen.davies@cce.ac.nz to support multiple hilited items
2387 function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
2388 $size=0, $selectAttr='',$compareFields0=true)
2390 global $ADODB_INCLUDED_LIB;
2391 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
2392 return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
2393 $size, $selectAttr,$compareFields0);
2397 * Generate a SELECT tag string from a recordset, and return the string.
2398 * If the recordset has 2 cols, we treat the 1st col as the containing
2399 * the text to display to the user, and 2nd col as the return value. Default
2400 * strings are compared with the SECOND column.
2403 function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
2405 global $ADODB_INCLUDED_LIB;
2406 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
2407 return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple,
2408 $size, $selectAttr,false);
2413 * return recordset as a 2-dimensional array.
2415 * @param [nRows] is the number of rows to return. -1 means every row.
2417 * @return an array indexed by the rows (0-based) from the recordset
2419 function &GetArray($nRows = -1)
2421 global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows);
2423 $results = array();
2424 $cnt = 0;
2425 while (!$this->EOF && $nRows != $cnt) {
2426 $results[] = $this->fields;
2427 $this->MoveNext();
2428 $cnt++;
2430 return $results;
2433 function &GetAll($nRows = -1)
2435 $arr =& $this->GetArray($nRows);
2436 return $arr;
2440 * Some databases allow multiple recordsets to be returned. This function
2441 * will return true if there is a next recordset, or false if no more.
2443 function NextRecordSet()
2445 return false;
2449 * return recordset as a 2-dimensional array.
2450 * Helper function for ADOConnection->SelectLimit()
2452 * @param offset is the row to start calculations from (1-based)
2453 * @param [nrows] is the number of rows to return
2455 * @return an array indexed by the rows (0-based) from the recordset
2457 function &GetArrayLimit($nrows,$offset=-1)
2459 if ($offset <= 0) {
2460 $arr =& $this->GetArray($nrows);
2461 return $arr;
2464 $this->Move($offset);
2466 $results = array();
2467 $cnt = 0;
2468 while (!$this->EOF && $nrows != $cnt) {
2469 $results[$cnt++] = $this->fields;
2470 $this->MoveNext();
2473 return $results;
2478 * Synonym for GetArray() for compatibility with ADO.
2480 * @param [nRows] is the number of rows to return. -1 means every row.
2482 * @return an array indexed by the rows (0-based) from the recordset
2484 function &GetRows($nRows = -1)
2486 $arr =& $this->GetArray($nRows);
2487 return $arr;
2491 * return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
2492 * The first column is treated as the key and is not included in the array.
2493 * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
2494 * $force_array == true.
2496 * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
2497 * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
2498 * read the source.
2500 * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
2501 * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
2503 * @return an associative array indexed by the first column of the array,
2504 * or false if the data has less than 2 cols.
2506 function &GetAssoc($force_array = false, $first2cols = false) {
2507 $cols = $this->_numOfFields;
2508 if ($cols < 2) {
2509 return false;
2511 $numIndex = isset($this->fields[0]);
2512 $results = array();
2514 if (!$first2cols && ($cols > 2 || $force_array)) {
2515 if ($numIndex) {
2516 while (!$this->EOF) {
2517 $results[trim($this->fields[0])] = array_slice($this->fields, 1);
2518 $this->MoveNext();
2520 } else {
2521 while (!$this->EOF) {
2522 $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
2523 $this->MoveNext();
2526 } else {
2527 // return scalar values
2528 if ($numIndex) {
2529 while (!$this->EOF) {
2530 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
2531 $results[trim(($this->fields[0]))] = $this->fields[1];
2532 $this->MoveNext();
2534 } else {
2535 while (!$this->EOF) {
2536 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
2537 $v1 = trim(reset($this->fields));
2538 $v2 = ''.next($this->fields);
2539 $results[$v1] = $v2;
2540 $this->MoveNext();
2544 return $results;
2550 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
2551 * @param fmt is the format to apply to it, using date()
2553 * @return a timestamp formated as user desires
2555 function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
2557 if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
2558 $tt = $this->UnixTimeStamp($v);
2559 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2560 if (($tt === false || $tt == -1) && $v != false) return $v;
2561 if ($tt === 0) return $this->emptyTimeStamp;
2562 return adodb_date($fmt,$tt);
2567 * @param v is the character date in YYYY-MM-DD format, returned by database
2568 * @param fmt is the format to apply to it, using date()
2570 * @return a date formated as user desires
2572 function UserDate($v,$fmt='Y-m-d')
2574 $tt = $this->UnixDate($v);
2575 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2576 if (($tt === false || $tt == -1) && $v != false) return $v;
2577 else if ($tt == 0) return $this->emptyDate;
2578 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
2580 return adodb_date($fmt,$tt);
2586 * @param $v is a date string in YYYY-MM-DD format
2588 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2590 function UnixDate($v)
2593 if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
2594 ($v), $rr)) return false;
2596 if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
2597 // h-m-s-MM-DD-YY
2598 return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2603 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
2605 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2607 function UnixTimeStamp($v)
2610 if (!preg_match(
2611 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
2612 ($v), $rr)) return false;
2613 if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
2615 // h-m-s-MM-DD-YY
2616 if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2617 return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
2622 * PEAR DB Compat - do not use internally
2624 function Free()
2626 return $this->Close();
2631 * PEAR DB compat, number of rows
2633 function NumRows()
2635 return $this->_numOfRows;
2640 * PEAR DB compat, number of cols
2642 function NumCols()
2644 return $this->_numOfFields;
2648 * Fetch a row, returning false if no more rows.
2649 * This is PEAR DB compat mode.
2651 * @return false or array containing the current record
2653 function FetchRow()
2655 if ($this->EOF) return false;
2656 $arr = $this->fields;
2657 $this->_currentRow++;
2658 if (!$this->_fetch()) $this->EOF = true;
2659 return $arr;
2664 * Fetch a row, returning PEAR_Error if no more rows.
2665 * This is PEAR DB compat mode.
2667 * @return DB_OK or error object
2669 function FetchInto(&$arr)
2671 if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
2672 $arr = $this->fields;
2673 $this->MoveNext();
2674 return 1; // DB_OK
2679 * Move to the first row in the recordset. Many databases do NOT support this.
2681 * @return true or false
2683 function MoveFirst()
2685 if ($this->_currentRow == 0) return true;
2686 return $this->Move(0);
2691 * Move to the last row in the recordset.
2693 * @return true or false
2695 function MoveLast()
2697 if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
2698 if ($this->EOF) return false;
2699 while (!$this->EOF) {
2700 $f = $this->fields;
2701 $this->MoveNext();
2703 $this->fields = $f;
2704 $this->EOF = false;
2705 return true;
2710 * Move to next record in the recordset.
2712 * @return true if there still rows available, or false if there are no more rows (EOF).
2714 function MoveNext()
2716 if (!$this->EOF) {
2717 $this->_currentRow++;
2718 if ($this->_fetch()) return true;
2720 $this->EOF = true;
2721 /* -- tested error handling when scrolling cursor -- seems useless.
2722 $conn = $this->connection;
2723 if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
2724 $fn = $conn->raiseErrorFn;
2725 $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
2728 return false;
2732 * Random access to a specific row in the recordset. Some databases do not support
2733 * access to previous rows in the databases (no scrolling backwards).
2735 * @param rowNumber is the row to move to (0-based)
2737 * @return true if there still rows available, or false if there are no more rows (EOF).
2739 function Move($rowNumber = 0)
2741 $this->EOF = false;
2742 if ($rowNumber == $this->_currentRow) return true;
2743 if ($rowNumber >= $this->_numOfRows)
2744 if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
2746 if ($this->canSeek) {
2748 if ($this->_seek($rowNumber)) {
2749 $this->_currentRow = $rowNumber;
2750 if ($this->_fetch()) {
2751 return true;
2753 } else {
2754 $this->EOF = true;
2755 return false;
2757 } else {
2758 if ($rowNumber < $this->_currentRow) return false;
2759 global $ADODB_EXTENSION;
2760 if ($ADODB_EXTENSION) {
2761 while (!$this->EOF && $this->_currentRow < $rowNumber) {
2762 adodb_movenext($this);
2764 } else {
2766 while (! $this->EOF && $this->_currentRow < $rowNumber) {
2767 $this->_currentRow++;
2769 if (!$this->_fetch()) $this->EOF = true;
2772 return !($this->EOF);
2775 $this->fields = false;
2776 $this->EOF = true;
2777 return false;
2782 * Get the value of a field in the current row by column name.
2783 * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
2785 * @param colname is the field to access
2787 * @return the value of $colname column
2789 function Fields($colname)
2791 return $this->fields[$colname];
2794 function GetAssocKeys($upper=true)
2796 $this->bind = array();
2797 for ($i=0; $i < $this->_numOfFields; $i++) {
2798 $o =& $this->FetchField($i);
2799 if ($upper === 2) $this->bind[$o->name] = $i;
2800 else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
2805 * Use associative array to get fields array for databases that do not support
2806 * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it
2808 * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
2809 * before you execute your SQL statement, and access $rs->fields['col'] directly.
2811 * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
2813 function &GetRowAssoc($upper=1)
2815 $record = array();
2816 // if (!$this->fields) return $record;
2818 if (!$this->bind) {
2819 $this->GetAssocKeys($upper);
2822 foreach($this->bind as $k => $v) {
2823 $record[$k] = $this->fields[$v];
2826 return $record;
2831 * Clean up recordset
2833 * @return true or false
2835 function Close()
2837 // free connection object - this seems to globally free the object
2838 // and not merely the reference, so don't do this...
2839 // $this->connection = false;
2840 if (!$this->_closed) {
2841 $this->_closed = true;
2842 return $this->_close();
2843 } else
2844 return true;
2848 * synonyms RecordCount and RowCount
2850 * @return the number of rows or -1 if this is not supported
2852 function RecordCount() {return $this->_numOfRows;}
2856 * If we are using PageExecute(), this will return the maximum possible rows
2857 * that can be returned when paging a recordset.
2859 function MaxRecordCount()
2861 return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
2865 * synonyms RecordCount and RowCount
2867 * @return the number of rows or -1 if this is not supported
2869 function RowCount() {return $this->_numOfRows;}
2873 * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
2875 * @return the number of records from a previous SELECT. All databases support this.
2877 * But aware possible problems in multiuser environments. For better speed the table
2878 * must be indexed by the condition. Heavy test this before deploying.
2880 function PO_RecordCount($table="", $condition="") {
2882 $lnumrows = $this->_numOfRows;
2883 // the database doesn't support native recordcount, so we do a workaround
2884 if ($lnumrows == -1 && $this->connection) {
2885 IF ($table) {
2886 if ($condition) $condition = " WHERE " . $condition;
2887 $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
2888 if ($resultrows) $lnumrows = reset($resultrows->fields);
2891 return $lnumrows;
2895 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
2897 function CurrentRow() {return $this->_currentRow;}
2900 * synonym for CurrentRow -- for ADO compat
2902 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
2904 function AbsolutePosition() {return $this->_currentRow;}
2907 * @return the number of columns in the recordset. Some databases will set this to 0
2908 * if no records are returned, others will return the number of columns in the query.
2910 function FieldCount() {return $this->_numOfFields;}
2914 * Get the ADOFieldObject of a specific column.
2916 * @param fieldoffset is the column position to access(0-based).
2918 * @return the ADOFieldObject for that column, or false.
2920 function &FetchField($fieldoffset)
2922 // must be defined by child class
2926 * Get the ADOFieldObjects of all columns in an array.
2929 function FieldTypesArray()
2931 $arr = array();
2932 for ($i=0, $max=$this->_numOfFields; $i < $max; $i++)
2933 $arr[] = $this->FetchField($i);
2934 return $arr;
2938 * Return the fields array of the current row as an object for convenience.
2939 * The default case is lowercase field names.
2941 * @return the object with the properties set to the fields of the current row
2943 function &FetchObj()
2945 $o =& $this->FetchObject(false);
2946 return $o;
2950 * Return the fields array of the current row as an object for convenience.
2951 * The default case is uppercase.
2953 * @param $isupper to set the object property names to uppercase
2955 * @return the object with the properties set to the fields of the current row
2957 function &FetchObject($isupper=true)
2959 if (empty($this->_obj)) {
2960 $this->_obj =& new ADOFetchObj();
2961 $this->_names = array();
2962 for ($i=0; $i <$this->_numOfFields; $i++) {
2963 $f = $this->FetchField($i);
2964 $this->_names[] = $f->name;
2967 $i = 0;
2968 $o = &$this->_obj;
2969 for ($i=0; $i <$this->_numOfFields; $i++) {
2970 $name = $this->_names[$i];
2971 if ($isupper) $n = strtoupper($name);
2972 else $n = $name;
2974 $o->$n = $this->Fields($name);
2976 return $o;
2980 * Return the fields array of the current row as an object for convenience.
2981 * The default is lower-case field names.
2983 * @return the object with the properties set to the fields of the current row,
2984 * or false if EOF
2986 * Fixed bug reported by tim@orotech.net
2988 function &FetchNextObj()
2990 return $this->FetchNextObject(false);
2995 * Return the fields array of the current row as an object for convenience.
2996 * The default is upper case field names.
2998 * @param $isupper to set the object property names to uppercase
3000 * @return the object with the properties set to the fields of the current row,
3001 * or false if EOF
3003 * Fixed bug reported by tim@orotech.net
3005 function &FetchNextObject($isupper=true)
3007 $o = false;
3008 if ($this->_numOfRows != 0 && !$this->EOF) {
3009 $o = $this->FetchObject($isupper);
3010 $this->_currentRow++;
3011 if ($this->_fetch()) return $o;
3013 $this->EOF = true;
3014 return $o;
3018 * Get the metatype of the column. This is used for formatting. This is because
3019 * many databases use different names for the same type, so we transform the original
3020 * type to our standardised version which uses 1 character codes:
3022 * @param t is the type passed in. Normally is ADOFieldObject->type.
3023 * @param len is the maximum length of that field. This is because we treat character
3024 * fields bigger than a certain size as a 'B' (blob).
3025 * @param fieldobj is the field object returned by the database driver. Can hold
3026 * additional info (eg. primary_key for mysql).
3028 * @return the general type of the data:
3029 * C for character < 200 chars
3030 * X for teXt (>= 200 chars)
3031 * B for Binary
3032 * N for numeric floating point
3033 * D for date
3034 * T for timestamp
3035 * L for logical/Boolean
3036 * I for integer
3037 * R for autoincrement counter/integer
3041 function MetaType($t,$len=-1,$fieldobj=false)
3043 if (is_object($t)) {
3044 $fieldobj = $t;
3045 $t = $fieldobj->type;
3046 $len = $fieldobj->max_length;
3048 // changed in 2.32 to hashing instead of switch stmt for speed...
3049 static $typeMap = array(
3050 'VARCHAR' => 'C',
3051 'VARCHAR2' => 'C',
3052 'CHAR' => 'C',
3053 'C' => 'C',
3054 'STRING' => 'C',
3055 'NCHAR' => 'C',
3056 'NVARCHAR' => 'C',
3057 'VARYING' => 'C',
3058 'BPCHAR' => 'C',
3059 'CHARACTER' => 'C',
3060 'INTERVAL' => 'C', # Postgres
3062 'LONGCHAR' => 'X',
3063 'TEXT' => 'X',
3064 'NTEXT' => 'X',
3065 'M' => 'X',
3066 'X' => 'X',
3067 'CLOB' => 'X',
3068 'NCLOB' => 'X',
3069 'LVARCHAR' => 'X',
3071 'BLOB' => 'B',
3072 'IMAGE' => 'B',
3073 'BINARY' => 'B',
3074 'VARBINARY' => 'B',
3075 'LONGBINARY' => 'B',
3076 'B' => 'B',
3078 'YEAR' => 'D', // mysql
3079 'DATE' => 'D',
3080 'D' => 'D',
3082 'TIME' => 'T',
3083 'TIMESTAMP' => 'T',
3084 'DATETIME' => 'T',
3085 'TIMESTAMPTZ' => 'T',
3086 'T' => 'T',
3088 'BOOL' => 'L',
3089 'BOOLEAN' => 'L',
3090 'BIT' => 'L',
3091 'L' => 'L',
3093 'COUNTER' => 'R',
3094 'R' => 'R',
3095 'SERIAL' => 'R', // ifx
3096 'INT IDENTITY' => 'R',
3098 'INT' => 'I',
3099 'INTEGER' => 'I',
3100 'INTEGER UNSIGNED' => 'I',
3101 'SHORT' => 'I',
3102 'TINYINT' => 'I',
3103 'SMALLINT' => 'I',
3104 'I' => 'I',
3106 'LONG' => 'N', // interbase is numeric, oci8 is blob
3107 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
3108 'DECIMAL' => 'N',
3109 'DEC' => 'N',
3110 'REAL' => 'N',
3111 'DOUBLE' => 'N',
3112 'DOUBLE PRECISION' => 'N',
3113 'SMALLFLOAT' => 'N',
3114 'FLOAT' => 'N',
3115 'NUMBER' => 'N',
3116 'NUM' => 'N',
3117 'NUMERIC' => 'N',
3118 'MONEY' => 'N',
3120 ## informix 9.2
3121 'SQLINT' => 'I',
3122 'SQLSERIAL' => 'I',
3123 'SQLSMINT' => 'I',
3124 'SQLSMFLOAT' => 'N',
3125 'SQLFLOAT' => 'N',
3126 'SQLMONEY' => 'N',
3127 'SQLDECIMAL' => 'N',
3128 'SQLDATE' => 'D',
3129 'SQLVCHAR' => 'C',
3130 'SQLCHAR' => 'C',
3131 'SQLDTIME' => 'T',
3132 'SQLINTERVAL' => 'N',
3133 'SQLBYTES' => 'B',
3134 'SQLTEXT' => 'X'
3137 $tmap = false;
3138 $t = strtoupper($t);
3139 $tmap = @$typeMap[$t];
3140 switch ($tmap) {
3141 case 'C':
3143 // is the char field is too long, return as text field...
3144 if ($this->blobSize >= 0) {
3145 if ($len > $this->blobSize) return 'X';
3146 } else if ($len > 250) {
3147 return 'X';
3149 return 'C';
3151 case 'I':
3152 if (!empty($fieldobj->primary_key)) return 'R';
3153 return 'I';
3155 case false:
3156 return 'N';
3158 case 'B':
3159 if (isset($fieldobj->binary))
3160 return ($fieldobj->binary) ? 'B' : 'X';
3161 return 'B';
3163 case 'D':
3164 if (!empty($this->datetime)) return 'T';
3165 return 'D';
3167 default:
3168 if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
3169 return $tmap;
3173 function _close() {}
3176 * set/returns the current recordset page when paginating
3178 function AbsolutePage($page=-1)
3180 if ($page != -1) $this->_currentPage = $page;
3181 return $this->_currentPage;
3185 * set/returns the status of the atFirstPage flag when paginating
3187 function AtFirstPage($status=false)
3189 if ($status != false) $this->_atFirstPage = $status;
3190 return $this->_atFirstPage;
3193 function LastPageNo($page = false)
3195 if ($page != false) $this->_lastPageNo = $page;
3196 return $this->_lastPageNo;
3200 * set/returns the status of the atLastPage flag when paginating
3202 function AtLastPage($status=false)
3204 if ($status != false) $this->_atLastPage = $status;
3205 return $this->_atLastPage;
3208 } // end class ADORecordSet
3210 //==============================================================================================
3211 // CLASS ADORecordSet_array
3212 //==============================================================================================
3215 * This class encapsulates the concept of a recordset created in memory
3216 * as an array. This is useful for the creation of cached recordsets.
3218 * Note that the constructor is different from the standard ADORecordSet
3221 class ADORecordSet_array extends ADORecordSet
3223 var $databaseType = 'array';
3225 var $_array; // holds the 2-dimensional data array
3226 var $_types; // the array of types of each column (C B I L M)
3227 var $_colnames; // names of each column in array
3228 var $_skiprow1; // skip 1st row because it holds column names
3229 var $_fieldarr; // holds array of field objects
3230 var $canSeek = true;
3231 var $affectedrows = false;
3232 var $insertid = false;
3233 var $sql = '';
3234 var $compat = false;
3236 * Constructor
3239 function ADORecordSet_array($fakeid=1)
3241 global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
3243 // fetch() on EOF does not delete $this->fields
3244 $this->compat = !empty($ADODB_COMPAT_FETCH);
3245 $this->ADORecordSet($fakeid); // fake queryID
3246 $this->fetchMode = $ADODB_FETCH_MODE;
3251 * Setup the array.
3253 * @param array is a 2-dimensional array holding the data.
3254 * The first row should hold the column names
3255 * unless paramter $colnames is used.
3256 * @param typearr holds an array of types. These are the same types
3257 * used in MetaTypes (C,B,L,I,N).
3258 * @param [colnames] array of column names. If set, then the first row of
3259 * $array should not hold the column names.
3261 function InitArray($array,$typearr,$colnames=false)
3263 $this->_array = $array;
3264 $this->_types = $typearr;
3265 if ($colnames) {
3266 $this->_skiprow1 = false;
3267 $this->_colnames = $colnames;
3268 } else {
3269 $this->_skiprow1 = true;
3270 $this->_colnames = $array[0];
3272 $this->Init();
3275 * Setup the Array and datatype file objects
3277 * @param array is a 2-dimensional array holding the data.
3278 * The first row should hold the column names
3279 * unless paramter $colnames is used.
3280 * @param fieldarr holds an array of ADOFieldObject's.
3282 function InitArrayFields($array,$fieldarr)
3284 $this->_array = $array;
3285 $this->_skiprow1= false;
3286 if ($fieldarr) {
3287 $this->_fieldobjects = $fieldarr;
3289 $this->Init();
3292 function &GetArray($nRows=-1)
3294 if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
3295 return $this->_array;
3296 } else {
3297 $arr =& ADORecordSet::GetArray($nRows);
3298 return $arr;
3302 function _initrs()
3304 $this->_numOfRows = sizeof($this->_array);
3305 if ($this->_skiprow1) $this->_numOfRows -= 1;
3307 $this->_numOfFields =(isset($this->_fieldobjects)) ?
3308 sizeof($this->_fieldobjects):sizeof($this->_types);
3311 /* Use associative array to get fields array */
3312 function Fields($colname)
3314 if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
3316 if (!$this->bind) {
3317 $this->bind = array();
3318 for ($i=0; $i < $this->_numOfFields; $i++) {
3319 $o = $this->FetchField($i);
3320 $this->bind[strtoupper($o->name)] = $i;
3323 return $this->fields[$this->bind[strtoupper($colname)]];
3326 function &FetchField($fieldOffset = -1)
3328 if (isset($this->_fieldobjects)) {
3329 return $this->_fieldobjects[$fieldOffset];
3331 $o = new ADOFieldObject();
3332 $o->name = $this->_colnames[$fieldOffset];
3333 $o->type = $this->_types[$fieldOffset];
3334 $o->max_length = -1; // length not known
3336 return $o;
3339 function _seek($row)
3341 if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
3342 $this->_currentRow = $row;
3343 if ($this->_skiprow1) $row += 1;
3344 $this->fields = $this->_array[$row];
3345 return true;
3347 return false;
3350 function MoveNext()
3352 if (!$this->EOF) {
3353 $this->_currentRow++;
3355 $pos = $this->_currentRow;
3357 if ($this->_numOfRows <= $pos) {
3358 if (!$this->compat) $this->fields = false;
3359 } else {
3360 if ($this->_skiprow1) $pos += 1;
3361 $this->fields = $this->_array[$pos];
3362 return true;
3364 $this->EOF = true;
3367 return false;
3370 function _fetch()
3372 $pos = $this->_currentRow;
3374 if ($this->_numOfRows <= $pos) {
3375 if (!$this->compat) $this->fields = false;
3376 return false;
3378 if ($this->_skiprow1) $pos += 1;
3379 $this->fields = $this->_array[$pos];
3380 return true;
3383 function _close()
3385 return true;
3388 } // ADORecordSet_array
3390 //==============================================================================================
3391 // HELPER FUNCTIONS
3392 //==============================================================================================
3395 * Synonym for ADOLoadCode. Private function. Do not use.
3397 * @deprecated
3399 function ADOLoadDB($dbType)
3401 return ADOLoadCode($dbType);
3405 * Load the code for a specific database driver. Private function. Do not use.
3407 function ADOLoadCode($dbType)
3409 global $ADODB_LASTDB;
3411 if (!$dbType) return false;
3412 $db = strtolower($dbType);
3413 switch ($db) {
3414 case 'maxsql': $db = 'mysqlt'; break;
3415 case 'postgres':
3416 case 'pgsql': $db = 'postgres7'; break;
3418 @include_once(ADODB_DIR."/drivers/adodb-".$db.".inc.php");
3419 $ADODB_LASTDB = $db;
3421 $ok = class_exists("ADODB_" . $db);
3422 if ($ok) return $db;
3424 $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
3425 if (file_exists($file)) ADOConnection::outp("Missing file: $file");
3426 else ADOConnection::outp("Syntax error in file: $file");
3427 return false;
3431 * synonym for ADONewConnection for people like me who cannot remember the correct name
3433 function &NewADOConnection($db='')
3435 $tmp =& ADONewConnection($db);
3436 return $tmp;
3440 * Instantiate a new Connection class for a specific database driver.
3442 * @param [db] is the database Connection object to create. If undefined,
3443 * use the last database driver that was loaded by ADOLoadCode().
3445 * @return the freshly created instance of the Connection class.
3447 function &ADONewConnection($db='')
3449 GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
3451 if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
3452 $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
3454 if (!empty($ADODB_NEWCONNECTION)) {
3455 $obj = $ADODB_NEWCONNECTION($db);
3456 if ($obj) {
3457 if ($errorfn) $obj->raiseErrorFn = $errorfn;
3458 return $obj;
3462 if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
3463 if (empty($db)) $db = $ADODB_LASTDB;
3465 if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
3467 if (!$db) {
3468 if ($errorfn) {
3469 // raise an error
3470 $ignore = false;
3471 $errorfn('ADONewConnection', 'ADONewConnection', -998,
3472 "could not load the database driver for '$db",
3473 $db,false,$ignore);
3474 } else
3475 ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
3477 return false;
3480 $cls = 'ADODB_'.$db;
3481 if (!class_exists($cls)) {
3482 adodb_backtrace();
3483 return false;
3486 $obj =& new $cls();
3487 if ($errorfn) $obj->raiseErrorFn = $errorfn;
3489 return $obj;
3492 // $perf == true means called by NewPerfMonitor()
3493 function _adodb_getdriver($provider,$drivername,$perf=false)
3495 if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado')
3496 $drivername = $provider;
3497 else {
3498 if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5);
3499 else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4);
3500 else
3501 switch($drivername) {
3502 case 'oracle': $drivername = 'oci8';break;
3503 //case 'sybase': $drivername = 'mssql';break;
3504 case 'access':
3505 if ($perf) $drivername = '';
3506 break;
3507 case 'db2':
3508 break;
3509 default:
3510 $drivername = 'generic';
3511 break;
3515 return $drivername;
3518 function &NewPerfMonitor(&$conn)
3520 $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
3521 if (!$drivername || $drivername == 'generic') return false;
3522 include_once(ADODB_DIR.'/adodb-perf.inc.php');
3523 @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
3524 $class = "Perf_$drivername";
3525 if (!class_exists($class)) return false;
3526 $perf =& new $class($conn);
3528 return $perf;
3531 function &NewDataDictionary(&$conn)
3533 $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
3535 include_once(ADODB_DIR.'/adodb-lib.inc.php');
3536 include_once(ADODB_DIR.'/adodb-datadict.inc.php');
3537 $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
3539 if (!file_exists($path)) {
3540 ADOConnection::outp("Database driver '$path' not available");
3541 return false;
3543 include_once($path);
3544 $class = "ADODB2_$drivername";
3545 $dict =& new $class();
3546 $dict->dataProvider = $conn->dataProvider;
3547 $dict->connection = &$conn;
3548 $dict->upperName = strtoupper($drivername);
3549 $dict->quote = $conn->nameQuote;
3550 if (is_resource($conn->_connectionID))
3551 $dict->serverInfo = $conn->ServerInfo();
3553 return $dict;
3558 * Save a file $filename and its $contents (normally for caching) with file locking
3560 function adodb_write_file($filename, $contents,$debug=false)
3562 # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows
3563 # So to simulate locking, we assume that rename is an atomic operation.
3564 # First we delete $filename, then we create a $tempfile write to it and
3565 # rename to the desired $filename. If the rename works, then we successfully
3566 # modified the file exclusively.
3567 # What a stupid need - having to simulate locking.
3568 # Risks:
3569 # 1. $tempfile name is not unique -- very very low
3570 # 2. unlink($filename) fails -- ok, rename will fail
3571 # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs
3572 # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated
3573 if (strncmp(PHP_OS,'WIN',3) === 0) {
3574 // skip the decimal place
3575 $mtime = substr(str_replace(' ','_',microtime()),2);
3576 // getmypid() actually returns 0 on Win98 - never mind!
3577 $tmpname = $filename.uniqid($mtime).getmypid();
3578 if (!($fd = fopen($tmpname,'a'))) return false;
3579 $ok = ftruncate($fd,0);
3580 if (!fwrite($fd,$contents)) $ok = false;
3581 fclose($fd);
3582 chmod($tmpname,0644);
3583 // the tricky moment
3584 @unlink($filename);
3585 if (!@rename($tmpname,$filename)) {
3586 unlink($tmpname);
3587 $ok = false;
3589 if (!$ok) {
3590 if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));
3592 return $ok;
3594 if (!($fd = fopen($filename, 'a'))) return false;
3595 if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {
3596 $ok = fwrite( $fd, $contents );
3597 fclose($fd);
3598 chmod($filename,0644);
3599 }else {
3600 fclose($fd);
3601 if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");
3602 $ok = false;
3605 return $ok;
3609 Perform a print_r, with pre tags for better formatting.
3611 function adodb_pr($var)
3613 if (isset($_SERVER['HTTP_USER_AGENT'])) {
3614 echo " <pre>\n";print_r($var);echo "</pre>\n";
3615 } else
3616 print_r($var);
3620 Perform a stack-crawl and pretty print it.
3622 @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
3623 @param levels Number of levels to display
3625 function adodb_backtrace($printOrArr=true,$levels=9999)
3627 $s = '';
3628 if (PHPVERSION() < 4.3) return;
3630 $html = (isset($_SERVER['HTTP_USER_AGENT']));
3631 $fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
3633 $MAXSTRLEN = 64;
3635 $s = ($html) ? '<pre align=left>' : '';
3637 if (is_array($printOrArr)) $traceArr = $printOrArr;
3638 else $traceArr = debug_backtrace();
3639 array_shift($traceArr);
3640 $tabs = sizeof($traceArr)-1;
3642 foreach ($traceArr as $arr) {
3643 $levels -= 1;
3644 if ($levels < 0) break;
3646 $args = array();
3647 for ($i=0; $i < $tabs; $i++) $s .= ($html) ? ' &nbsp; ' : "\t";
3648 $tabs -= 1;
3649 if ($html) $s .= '<font face="Courier New,Courier">';
3650 if (isset($arr['class'])) $s .= $arr['class'].'.';
3651 if (isset($arr['args']))
3652 foreach($arr['args'] as $v) {
3653 if (is_null($v)) $args[] = 'null';
3654 else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
3655 else if (is_object($v)) $args[] = 'Object:'.get_class($v);
3656 else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
3657 else {
3658 $v = (string) @$v;
3659 $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
3660 if (strlen($v) > $MAXSTRLEN) $str .= '...';
3661 $args[] = $str;
3664 $s .= $arr['function'].'('.implode(', ',$args).')';
3667 $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
3669 $s .= "\n";
3671 if ($html) $s .= '</pre>';
3672 if ($printOrArr) print $s;
3674 return $s;
3677 } // defined