minor bug fix
[openemr.git] / library / adodb / adodb.inc.php
blobe3c48768a08b46156d6e528023ab921f540a79c7
1 <?php
2 /*
3 * Set tabs to 4 for best viewing.
4 *
5 * Latest version is available at http://adodb.sourceforge.net
6 *
7 * This is the main include file for ADOdb.
8 * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
10 * The ADOdb files are formatted so that doxygen can be used to generate documentation.
11 * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
14 /**
15 \mainpage
17 @version V5.14 8 Sept 2011 (c) 2000-2011 John Lim (jlim#natsoft.com). All rights reserved.
19 Released under both BSD license and Lesser GPL library license. You can choose which license
20 you prefer.
22 PHP's database access functions are not standardised. This creates a need for a database
23 class library to hide the differences between the different database API's (encapsulate
24 the differences) so we can easily switch databases.
26 We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
27 Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
28 ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
29 other databases via ODBC.
31 Latest Download at http://adodb.sourceforge.net/
35 if (!defined('_ADODB_LAYER')) {
36 define('_ADODB_LAYER',1);
38 //==============================================================================================
39 // CONSTANT DEFINITIONS
40 //==============================================================================================
43 /**
44 * Set ADODB_DIR to the directory where this file resides...
45 * This constant was formerly called $ADODB_RootPath
47 if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
49 //==============================================================================================
50 // GLOBAL VARIABLES
51 //==============================================================================================
53 GLOBAL
54 $ADODB_vers, // database version
55 $ADODB_COUNTRECS, // count number of records returned - slows down query
56 $ADODB_CACHE_DIR, // directory to cache recordsets
57 $ADODB_CACHE,
58 $ADODB_CACHE_CLASS,
59 $ADODB_EXTENSION, // ADODB extension installed
60 $ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
61 $ADODB_FETCH_MODE, // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
62 $ADODB_GETONE_EOF,
63 $ADODB_QUOTE_FIELDNAMES; // Allows you to force quotes (backticks) around field names in queries generated by getinsertsql and getupdatesql.
65 //==============================================================================================
66 // GLOBAL SETUP
67 //==============================================================================================
69 $ADODB_EXTENSION = defined('ADODB_EXTENSION');
71 //********************************************************//
73 Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3).
74 Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi
76 0 = ignore empty fields. All empty fields in array are ignored.
77 1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
78 2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
79 3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and empty fields '' are set to empty '' sql values.
81 define('ADODB_FORCE_IGNORE',0);
82 define('ADODB_FORCE_NULL',1);
83 define('ADODB_FORCE_EMPTY',2);
84 define('ADODB_FORCE_VALUE',3);
85 //********************************************************//
88 if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
90 define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
92 // allow [ ] @ ` " and . in table names
93 define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
95 // prefetching used by oracle
96 if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
100 Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
101 This currently works only with mssql, odbc, oci8po and ibase derived drivers.
103 0 = assoc lowercase field names. $rs->fields['orderid']
104 1 = assoc uppercase field names. $rs->fields['ORDERID']
105 2 = use native-case field names. $rs->fields['OrderID']
108 define('ADODB_FETCH_DEFAULT',0);
109 define('ADODB_FETCH_NUM',1);
110 define('ADODB_FETCH_ASSOC',2);
111 define('ADODB_FETCH_BOTH',3);
113 if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
115 // PHP's version scheme makes converting to numbers difficult - workaround
116 $_adodb_ver = (float) PHP_VERSION;
117 if ($_adodb_ver >= 5.2) {
118 define('ADODB_PHPVER',0x5200);
119 } else if ($_adodb_ver >= 5.0) {
120 define('ADODB_PHPVER',0x5000);
121 } else
122 die("PHP5 or later required. You are running ".PHP_VERSION);
126 //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
130 Accepts $src and $dest arrays, replacing string $data
132 function ADODB_str_replace($src, $dest, $data)
134 if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
136 $s = reset($src);
137 $d = reset($dest);
138 while ($s !== false) {
139 $data = str_replace($s,$d,$data);
140 $s = next($src);
141 $d = next($dest);
143 return $data;
146 function ADODB_Setup()
148 GLOBAL
149 $ADODB_vers, // database version
150 $ADODB_COUNTRECS, // count number of records returned - slows down query
151 $ADODB_CACHE_DIR, // directory to cache recordsets
152 $ADODB_FETCH_MODE,
153 $ADODB_CACHE,
154 $ADODB_CACHE_CLASS,
155 $ADODB_FORCE_TYPE,
156 $ADODB_GETONE_EOF,
157 $ADODB_QUOTE_FIELDNAMES;
159 if (empty($ADODB_CACHE_CLASS)) $ADODB_CACHE_CLASS = 'ADODB_Cache_File' ;
160 $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
161 $ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
162 $ADODB_GETONE_EOF = null;
164 if (!isset($ADODB_CACHE_DIR)) {
165 $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
166 } else {
167 // do not accept url based paths, eg. http:/ or ftp:/
168 if (strpos($ADODB_CACHE_DIR,'://') !== false)
169 die("Illegal path http:// or ftp://");
173 // Initialize random number generator for randomizing cache flushes
174 // -- note Since PHP 4.2.0, the seed becomes optional and defaults to a random value if omitted.
175 srand(((double)microtime())*1000000);
178 * ADODB version as a string.
180 $ADODB_vers = 'V5.14 8 Sept 2011 (c) 2000-2011 John Lim (jlim#natsoft.com). All rights reserved. Released BSD & LGPL.';
183 * Determines whether recordset->RecordCount() is used.
184 * Set to false for highest performance -- RecordCount() will always return -1 then
185 * for databases that provide "virtual" recordcounts...
187 if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
191 //==============================================================================================
192 // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
193 //==============================================================================================
195 ADODB_Setup();
197 //==============================================================================================
198 // CLASS ADOFieldObject
199 //==============================================================================================
201 * Helper class for FetchFields -- holds info on a column
203 class ADOFieldObject {
204 var $name = '';
205 var $max_length=0;
206 var $type="";
208 // additional fields by dannym... (danny_milo@yahoo.com)
209 var $not_null = false;
210 // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
211 // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
213 var $has_default = false; // this one I have done only in mysql and postgres for now ...
214 // others to come (dannym)
215 var $default_value; // default, if any, and supported. Check has_default first.
219 // for transaction handling
221 function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
223 //print "Errorno ($fn errno=$errno m=$errmsg) ";
224 $thisConnection->_transOK = false;
225 if ($thisConnection->_oldRaiseFn) {
226 $fn = $thisConnection->_oldRaiseFn;
227 $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
231 //------------------
232 // class for caching
233 class ADODB_Cache_File {
235 var $createdir = true; // requires creation of temp dirs
237 function ADODB_Cache_File()
239 global $ADODB_INCLUDED_CSV;
240 if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
243 // write serialised recordset to cache item/file
244 function writecache($filename, $contents, $debug, $secs2cache)
246 return adodb_write_file($filename, $contents,$debug);
249 // load serialised recordset and unserialise it
250 function &readcache($filename, &$err, $secs2cache, $rsClass)
252 $rs = csv2rs($filename,$err,$secs2cache,$rsClass);
253 return $rs;
256 // flush all items in cache
257 function flushall($debug=false)
259 global $ADODB_CACHE_DIR;
261 $rez = false;
263 if (strlen($ADODB_CACHE_DIR) > 1) {
264 $rez = $this->_dirFlush($ADODB_CACHE_DIR);
265 if ($debug) ADOConnection::outp( "flushall: $dir<br><pre>\n". $rez."</pre>");
267 return $rez;
270 // flush one file in cache
271 function flushcache($f, $debug=false)
273 if (!@unlink($f)) {
274 if ($debug) ADOConnection::outp( "flushcache: failed for $f");
278 function getdirname($hash)
280 global $ADODB_CACHE_DIR;
281 if (!isset($this->notSafeMode)) $this->notSafeMode = !ini_get('safe_mode');
282 return ($this->notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($hash,0,2) : $ADODB_CACHE_DIR;
285 // create temp directories
286 function createdir($hash, $debug)
288 $dir = $this->getdirname($hash);
289 if ($this->notSafeMode && !file_exists($dir)) {
290 $oldu = umask(0);
291 if (!@mkdir($dir,0771)) if(!is_dir($dir) && $debug) ADOConnection::outp("Cannot create $dir");
292 umask($oldu);
295 return $dir;
299 * Private function to erase all of the files and subdirectories in a directory.
301 * Just specify the directory, and tell it if you want to delete the directory or just clear it out.
302 * Note: $kill_top_level is used internally in the function to flush subdirectories.
304 function _dirFlush($dir, $kill_top_level = false)
306 if(!$dh = @opendir($dir)) return;
308 while (($obj = readdir($dh))) {
309 if($obj=='.' || $obj=='..') continue;
310 $f = $dir.'/'.$obj;
312 if (strpos($obj,'.cache')) @unlink($f);
313 if (is_dir($f)) $this->_dirFlush($f, true);
315 if ($kill_top_level === true) @rmdir($dir);
316 return true;
320 //==============================================================================================
321 // CLASS ADOConnection
322 //==============================================================================================
325 * Connection object. For connecting to databases, and executing queries.
327 class ADOConnection {
329 // PUBLIC VARS
331 var $dataProvider = 'native';
332 var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
333 var $database = ''; /// Name of database to be used.
334 var $host = ''; /// The hostname of the database server
335 var $user = ''; /// The username which is used to connect to the database server.
336 var $password = ''; /// Password for the username. For security, we no longer store it.
337 var $debug = false; /// if set to true will output sql statements
338 var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
339 var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
340 var $substr = 'substr'; /// substring operator
341 var $length = 'length'; /// string length ofperator
342 var $random = 'rand()'; /// random function
343 var $upperCase = 'upper'; /// uppercase function
344 var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
345 var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
346 var $true = '1'; /// string that represents TRUE for a database
347 var $false = '0'; /// string that represents FALSE for a database
348 var $replaceQuote = "\\'"; /// string to use to replace quotes
349 var $nameQuote = '"'; /// string to use to quote identifiers and names
350 var $charSet=false; /// character set to use - only for interbase, postgres and oci8
351 var $metaDatabasesSQL = '';
352 var $metaTablesSQL = '';
353 var $uniqueOrderBy = false; /// All order by columns have to be unique
354 var $emptyDate = '&nbsp;';
355 var $emptyTimeStamp = '&nbsp;';
356 var $lastInsID = false;
357 //--
358 var $hasInsertID = false; /// supports autoincrement ID?
359 var $hasAffectedRows = false; /// supports affected rows for update/delete?
360 var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
361 var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
362 var $readOnly = false; /// this is a readonly database - used by phpLens
363 var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
364 var $hasGenID = false; /// can generate sequences using GenID();
365 var $hasTransactions = true; /// has transactions
366 //--
367 var $genID = 0; /// sequence id used by GenID();
368 var $raiseErrorFn = false; /// error function to call
369 var $isoDates = false; /// accepts dates in ISO format
370 var $cacheSecs = 3600; /// cache for 1 hour
372 // memcache
373 var $memCache = false; /// should we use memCache instead of caching in files
374 var $memCacheHost; /// memCache host
375 var $memCachePort = 11211; /// memCache port
376 var $memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
378 var $sysDate = false; /// name of function that returns the current date
379 var $sysTimeStamp = false; /// name of function that returns the current timestamp
380 var $sysUTimeStamp = false; // name of function that returns the current timestamp accurate to the microsecond or nearest fraction
381 var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
383 var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
384 var $numCacheHits = 0;
385 var $numCacheMisses = 0;
386 var $pageExecuteCountRows = true;
387 var $uniqueSort = false; /// indicates that all fields in order by must be unique
388 var $leftOuter = false; /// operator to use for left outer join in WHERE clause
389 var $rightOuter = false; /// operator to use for right outer join in WHERE clause
390 var $ansiOuter = false; /// whether ansi outer join syntax supported
391 var $autoRollback = false; // autoRollback on PConnect().
392 var $poorAffectedRows = false; // affectedRows not working or unreliable
394 var $fnExecute = false;
395 var $fnCacheExecute = false;
396 var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
397 var $rsPrefix = "ADORecordSet_";
399 var $autoCommit = true; /// do not modify this yourself - actually private
400 var $transOff = 0; /// temporarily disable transactions
401 var $transCnt = 0; /// count of nested transactions
403 var $fetchMode=false;
405 var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null
406 var $bulkBind = false; // enable 2D Execute array
408 // PRIVATE VARS
410 var $_oldRaiseFn = false;
411 var $_transOK = null;
412 var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
413 var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
414 /// then returned by the errorMsg() function
415 var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
416 var $_queryID = false; /// This variable keeps the last created result link identifier
418 var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
419 var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
420 var $_evalAll = false;
421 var $_affected = false;
422 var $_logsql = false;
423 var $_transmode = ''; // transaction mode
428 * Constructor
430 function ADOConnection()
432 die('Virtual Class -- cannot instantiate');
435 static function Version()
437 global $ADODB_vers;
439 $ok = preg_match( '/^[Vv]([0-9\.]+)/', $ADODB_vers, $matches );
440 if (!$ok) return (float) substr($ADODB_vers,1);
441 else return $matches[1];
445 Get server version info...
447 @returns An array with 2 elements: $arr['string'] is the description string,
448 and $arr[version] is the version (also a string).
450 function ServerInfo()
452 return array('description' => '', 'version' => '');
455 function IsConnected()
457 return !empty($this->_connectionID);
460 function _findvers($str)
462 if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
463 else return '';
467 * All error messages go through this bottleneck function.
468 * You can define your own handler by defining the function name in ADODB_OUTP.
470 static function outp($msg,$newline=true)
472 global $ADODB_FLUSH,$ADODB_OUTP;
474 if (defined('ADODB_OUTP')) {
475 $fn = ADODB_OUTP;
476 $fn($msg,$newline);
477 return;
478 } else if (isset($ADODB_OUTP)) {
479 $fn = $ADODB_OUTP;
480 $fn($msg,$newline);
481 return;
484 if ($newline) $msg .= "<br>\n";
486 if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
487 else echo strip_tags($msg);
490 if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
494 function Time()
496 $rs = $this->_Execute("select $this->sysTimeStamp");
497 if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
499 return false;
503 * Connect to database
505 * @param [argHostname] Host to connect to
506 * @param [argUsername] Userid to login
507 * @param [argPassword] Associated password
508 * @param [argDatabaseName] database
509 * @param [forceNew] force new connection
511 * @return true or false
513 function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
515 if ($argHostname != "") $this->host = $argHostname;
516 if ($argUsername != "") $this->user = $argUsername;
517 if ($argPassword != "") $this->password = 'not stored'; // not stored for security reasons
518 if ($argDatabaseName != "") $this->database = $argDatabaseName;
520 $this->_isPersistentConnection = false;
522 if ($forceNew) {
523 if ($rez=$this->_nconnect($this->host, $this->user, $argPassword, $this->database)) return true;
524 } else {
525 if ($rez=$this->_connect($this->host, $this->user, $argPassword, $this->database)) return true;
527 if (isset($rez)) {
528 $err = $this->ErrorMsg();
529 if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
530 $ret = false;
531 } else {
532 $err = "Missing extension for ".$this->dataProvider;
533 $ret = 0;
535 if ($fn = $this->raiseErrorFn)
536 $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
539 $this->_connectionID = false;
540 if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
541 return $ret;
544 function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
546 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
551 * Always force a new connection to database - currently only works with oracle
553 * @param [argHostname] Host to connect to
554 * @param [argUsername] Userid to login
555 * @param [argPassword] Associated password
556 * @param [argDatabaseName] database
558 * @return true or false
560 function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
562 return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
566 * Establish persistent connect to database
568 * @param [argHostname] Host to connect to
569 * @param [argUsername] Userid to login
570 * @param [argPassword] Associated password
571 * @param [argDatabaseName] database
573 * @return return true or false
575 function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
578 if (defined('ADODB_NEVER_PERSIST'))
579 return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
581 if ($argHostname != "") $this->host = $argHostname;
582 if ($argUsername != "") $this->user = $argUsername;
583 if ($argPassword != "") $this->password = 'not stored';
584 if ($argDatabaseName != "") $this->database = $argDatabaseName;
586 $this->_isPersistentConnection = true;
588 if ($rez = $this->_pconnect($this->host, $this->user, $argPassword, $this->database)) return true;
589 if (isset($rez)) {
590 $err = $this->ErrorMsg();
591 if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
592 $ret = false;
593 } else {
594 $err = "Missing extension for ".$this->dataProvider;
595 $ret = 0;
597 if ($fn = $this->raiseErrorFn) {
598 $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
601 $this->_connectionID = false;
602 if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
603 return $ret;
606 function outp_throw($msg,$src='WARN',$sql='')
608 if (defined('ADODB_ERROR_HANDLER') && ADODB_ERROR_HANDLER == 'adodb_throw') {
609 adodb_throw($this->databaseType,$src,-9999,$msg,$sql,false,$this);
610 return;
612 ADOConnection::outp($msg);
615 // create cache class. Code is backward compat with old memcache implementation
616 function _CreateCache()
618 global $ADODB_CACHE, $ADODB_CACHE_CLASS;
620 if ($this->memCache) {
621 global $ADODB_INCLUDED_MEMCACHE;
623 if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
624 $ADODB_CACHE = new ADODB_Cache_MemCache($this);
625 } else
626 $ADODB_CACHE = new $ADODB_CACHE_CLASS($this);
630 // Format date column in sql string given an input format that understands Y M D
631 function SQLDate($fmt, $col=false)
633 if (!$col) $col = $this->sysDate;
634 return $col; // child class implement
638 * Should prepare the sql statement and return the stmt resource.
639 * For databases that do not support this, we return the $sql. To ensure
640 * compatibility with databases that do not support prepare:
642 * $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
643 * $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
644 * $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
646 * @param sql SQL to send to database
648 * @return return FALSE, or the prepared statement, or the original sql if
649 * if the database does not support prepare.
652 function Prepare($sql)
654 return $sql;
658 * Some databases, eg. mssql require a different function for preparing
659 * stored procedures. So we cannot use Prepare().
661 * Should prepare the stored procedure and return the stmt resource.
662 * For databases that do not support this, we return the $sql. To ensure
663 * compatibility with databases that do not support prepare:
665 * @param sql SQL to send to database
667 * @return return FALSE, or the prepared statement, or the original sql if
668 * if the database does not support prepare.
671 function PrepareSP($sql,$param=true)
673 return $this->Prepare($sql,$param);
677 * PEAR DB Compat
679 function Quote($s)
681 return $this->qstr($s,false);
685 Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
687 function QMagic($s)
689 return $this->qstr($s,get_magic_quotes_gpc());
692 function q(&$s)
694 #if (!empty($this->qNull)) if ($s == 'null') return $s;
695 $s = $this->qstr($s,false);
699 * PEAR DB Compat - do not use internally.
701 function ErrorNative()
703 return $this->ErrorNo();
708 * PEAR DB Compat - do not use internally.
710 function nextId($seq_name)
712 return $this->GenID($seq_name);
716 * Lock a row, will escalate and lock the table if row locking not supported
717 * will normally free the lock at the end of the transaction
719 * @param $table name of table to lock
720 * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
722 function RowLock($table,$where,$col='1 as adodbignore')
724 return false;
727 function CommitLock($table)
729 return $this->CommitTrans();
732 function RollbackLock($table)
734 return $this->RollbackTrans();
738 * PEAR DB Compat - do not use internally.
740 * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
741 * for easy porting :-)
743 * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
744 * @returns The previous fetch mode
746 function SetFetchMode($mode)
748 $old = $this->fetchMode;
749 $this->fetchMode = $mode;
751 if ($old === false) {
752 global $ADODB_FETCH_MODE;
753 return $ADODB_FETCH_MODE;
755 return $old;
760 * PEAR DB Compat - do not use internally.
762 function Query($sql, $inputarr=false)
764 $rs = $this->Execute($sql, $inputarr);
765 if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
766 return $rs;
771 * PEAR DB Compat - do not use internally
773 function LimitQuery($sql, $offset, $count, $params=false)
775 $rs = $this->SelectLimit($sql, $count, $offset, $params);
776 if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
777 return $rs;
782 * PEAR DB Compat - do not use internally
784 function Disconnect()
786 return $this->Close();
790 Returns placeholder for parameter, eg.
791 $DB->Param('a')
793 will return ':a' for Oracle, and '?' for most other databases...
795 For databases that require positioned params, eg $1, $2, $3 for postgresql,
796 pass in Param(false) before setting the first parameter.
798 function Param($name,$type='C')
800 return '?';
804 InParameter and OutParameter are self-documenting versions of Parameter().
806 function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
808 return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
813 function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
815 return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
821 Usage in oracle
822 $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
823 $db->Parameter($stmt,$id,'myid');
824 $db->Parameter($stmt,$group,'group',64);
825 $db->Execute();
827 @param $stmt Statement returned by Prepare() or PrepareSP().
828 @param $var PHP variable to bind to
829 @param $name Name of stored procedure variable name to bind to.
830 @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
831 @param [$maxLen] Holds an maximum length of the variable.
832 @param [$type] The data type of $var. Legal values depend on driver.
835 function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
837 return false;
841 function IgnoreErrors($saveErrs=false)
843 if (!$saveErrs) {
844 $saveErrs = array($this->raiseErrorFn,$this->_transOK);
845 $this->raiseErrorFn = false;
846 return $saveErrs;
847 } else {
848 $this->raiseErrorFn = $saveErrs[0];
849 $this->_transOK = $saveErrs[1];
854 Improved method of initiating a transaction. Used together with CompleteTrans().
855 Advantages include:
857 a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
858 Only the outermost block is treated as a transaction.<br>
859 b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
860 c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
861 are disabled, making it backward compatible.
863 function StartTrans($errfn = 'ADODB_TransMonitor')
865 if ($this->transOff > 0) {
866 $this->transOff += 1;
867 return true;
870 $this->_oldRaiseFn = $this->raiseErrorFn;
871 $this->raiseErrorFn = $errfn;
872 $this->_transOK = true;
874 if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
875 $ok = $this->BeginTrans();
876 $this->transOff = 1;
877 return $ok;
882 Used together with StartTrans() to end a transaction. Monitors connection
883 for sql errors, and will commit or rollback as appropriate.
885 @autoComplete if true, monitor sql errors and commit and rollback as appropriate,
886 and if set to false force rollback even if no SQL error detected.
887 @returns true on commit, false on rollback.
889 function CompleteTrans($autoComplete = true)
891 if ($this->transOff > 1) {
892 $this->transOff -= 1;
893 return true;
895 $this->raiseErrorFn = $this->_oldRaiseFn;
897 $this->transOff = 0;
898 if ($this->_transOK && $autoComplete) {
899 if (!$this->CommitTrans()) {
900 $this->_transOK = false;
901 if ($this->debug) ADOConnection::outp("Smart Commit failed");
902 } else
903 if ($this->debug) ADOConnection::outp("Smart Commit occurred");
904 } else {
905 $this->_transOK = false;
906 $this->RollbackTrans();
907 if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
910 return $this->_transOK;
914 At the end of a StartTrans/CompleteTrans block, perform a rollback.
916 function FailTrans()
918 if ($this->debug)
919 if ($this->transOff == 0) {
920 ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
921 } else {
922 ADOConnection::outp("FailTrans was called");
923 adodb_backtrace();
925 $this->_transOK = false;
929 Check if transaction has failed, only for Smart Transactions.
931 function HasFailedTrans()
933 if ($this->transOff > 0) return $this->_transOK == false;
934 return false;
938 * Execute SQL
940 * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
941 * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
942 * @return RecordSet or false
944 function Execute($sql,$inputarr=false)
946 if ($this->fnExecute) {
947 $fn = $this->fnExecute;
948 $ret = $fn($this,$sql,$inputarr);
949 if (isset($ret)) return $ret;
951 if ($inputarr) {
952 if (!is_array($inputarr)) $inputarr = array($inputarr);
954 $element0 = reset($inputarr);
955 # is_object check because oci8 descriptors can be passed in
956 $array_2d = $this->bulkBind && is_array($element0) && !is_object(reset($element0));
958 //remove extra memory copy of input -mikefedyk
959 unset($element0);
961 if (!is_array($sql) && !$this->_bindInputArray) {
962 $sqlarr = explode('?',$sql);
963 $nparams = sizeof($sqlarr)-1;
964 if (!$array_2d) $inputarr = array($inputarr);
966 foreach($inputarr as $arr) {
967 $sql = ''; $i = 0;
968 //Use each() instead of foreach to reduce memory usage -mikefedyk
969 while(list(, $v) = each($arr)) {
970 $sql .= $sqlarr[$i];
971 // from Ron Baldwin <ron.baldwin#sourceprose.com>
972 // Only quote string types
973 $typ = gettype($v);
974 if ($typ == 'string')
975 //New memory copy of input created here -mikefedyk
976 $sql .= $this->qstr($v);
977 else if ($typ == 'double')
978 $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
979 else if ($typ == 'boolean')
980 $sql .= $v ? $this->true : $this->false;
981 else if ($typ == 'object') {
982 if (method_exists($v, '__toString')) $sql .= $this->qstr($v->__toString());
983 else $sql .= $this->qstr((string) $v);
984 } else if ($v === null)
985 $sql .= 'NULL';
986 else
987 $sql .= $v;
988 $i += 1;
990 if ($i == $nparams) break;
991 } // while
992 if (isset($sqlarr[$i])) {
993 $sql .= $sqlarr[$i];
994 if ($i+1 != sizeof($sqlarr)) $this->outp_throw( "Input Array does not match ?: ".htmlspecialchars($sql),'Execute');
995 } else if ($i != sizeof($sqlarr))
996 $this->outp_throw( "Input array does not match ?: ".htmlspecialchars($sql),'Execute');
998 $ret = $this->_Execute($sql);
999 if (!$ret) return $ret;
1001 } else {
1002 if ($array_2d) {
1003 if (is_string($sql))
1004 $stmt = $this->Prepare($sql);
1005 else
1006 $stmt = $sql;
1008 foreach($inputarr as $arr) {
1009 $ret = $this->_Execute($stmt,$arr);
1010 if (!$ret) return $ret;
1012 } else {
1013 $ret = $this->_Execute($sql,$inputarr);
1016 } else {
1017 $ret = $this->_Execute($sql,false);
1020 return $ret;
1024 function _Execute($sql,$inputarr=false)
1026 if ($this->debug) {
1027 global $ADODB_INCLUDED_LIB;
1028 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
1029 $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
1030 } else {
1031 $this->_queryID = @$this->_query($sql,$inputarr);
1034 /************************
1035 // OK, query executed
1036 *************************/
1038 if ($this->_queryID === false) { // error handling if query fails
1039 if ($this->debug == 99) adodb_backtrace(true,5);
1040 $fn = $this->raiseErrorFn;
1041 if ($fn) {
1042 $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
1044 $false = false;
1045 return $false;
1048 if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
1049 $rsclass = $this->rsPrefix.'empty';
1050 $rs = (class_exists($rsclass)) ? new $rsclass(): new ADORecordSet_empty();
1052 return $rs;
1055 // return real recordset from select statement
1056 $rsclass = $this->rsPrefix.$this->databaseType;
1057 $rs = new $rsclass($this->_queryID,$this->fetchMode);
1058 $rs->connection = $this; // Pablo suggestion
1059 $rs->Init();
1060 if (is_array($sql)) $rs->sql = $sql[0];
1061 else $rs->sql = $sql;
1062 if ($rs->_numOfRows <= 0) {
1063 global $ADODB_COUNTRECS;
1064 if ($ADODB_COUNTRECS) {
1065 if (!$rs->EOF) {
1066 $rs = $this->_rs2rs($rs,-1,-1,!is_array($sql));
1067 $rs->_queryID = $this->_queryID;
1068 } else
1069 $rs->_numOfRows = 0;
1072 return $rs;
1075 function CreateSequence($seqname='adodbseq',$startID=1)
1077 if (empty($this->_genSeqSQL)) return false;
1078 return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
1081 function DropSequence($seqname='adodbseq')
1083 if (empty($this->_dropSeqSQL)) return false;
1084 return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
1088 * Generates a sequence id and stores it in $this->genID;
1089 * GenID is only available if $this->hasGenID = true;
1091 * @param seqname name of sequence to use
1092 * @param startID if sequence does not exist, start at this ID
1093 * @return 0 if not supported, otherwise a sequence id
1095 function GenID($seqname='adodbseq',$startID=1)
1097 if (!$this->hasGenID) {
1098 return 0; // formerly returns false pre 1.60
1101 $getnext = sprintf($this->_genIDSQL,$seqname);
1103 $holdtransOK = $this->_transOK;
1105 $save_handler = $this->raiseErrorFn;
1106 $this->raiseErrorFn = '';
1107 @($rs = $this->Execute($getnext));
1108 $this->raiseErrorFn = $save_handler;
1110 if (!$rs) {
1111 $this->_transOK = $holdtransOK; //if the status was ok before reset
1112 $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
1113 $rs = $this->Execute($getnext);
1115 if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
1116 else $this->genID = 0; // false
1118 if ($rs) $rs->Close();
1120 return $this->genID;
1124 * @param $table string name of the table, not needed by all databases (eg. mysql), default ''
1125 * @param $column string name of the column, not needed by all databases (eg. mysql), default ''
1126 * @return the last inserted ID. Not all databases support this.
1128 function Insert_ID($table='',$column='')
1130 if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
1131 if ($this->hasInsertID) return $this->_insertid($table,$column);
1132 if ($this->debug) {
1133 ADOConnection::outp( '<p>Insert_ID error</p>');
1134 adodb_backtrace();
1136 return false;
1141 * Portable Insert ID. Pablo Roca <pabloroca#mvps.org>
1143 * @return the last inserted ID. All databases support this. But aware possible
1144 * problems in multiuser environments. Heavy test this before deploying.
1146 function PO_Insert_ID($table="", $id="")
1148 if ($this->hasInsertID){
1149 return $this->Insert_ID($table,$id);
1150 } else {
1151 return $this->GetOne("SELECT MAX($id) FROM $table");
1156 * @return # rows affected by UPDATE/DELETE
1158 function Affected_Rows()
1160 if ($this->hasAffectedRows) {
1161 if ($this->fnExecute === 'adodb_log_sql') {
1162 if ($this->_logsql && $this->_affected !== false) return $this->_affected;
1164 $val = $this->_affectedrows();
1165 return ($val < 0) ? false : $val;
1168 if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
1169 return false;
1174 * @return the last error message
1176 function ErrorMsg()
1178 if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
1179 else return '';
1184 * @return the last error number. Normally 0 means no error.
1186 function ErrorNo()
1188 return ($this->_errorMsg) ? -1 : 0;
1191 function MetaError($err=false)
1193 include_once(ADODB_DIR."/adodb-error.inc.php");
1194 if ($err === false) $err = $this->ErrorNo();
1195 return adodb_error($this->dataProvider,$this->databaseType,$err);
1198 function MetaErrorMsg($errno)
1200 include_once(ADODB_DIR."/adodb-error.inc.php");
1201 return adodb_errormsg($errno);
1205 * @returns an array with the primary key columns in it.
1207 function MetaPrimaryKeys($table, $owner=false)
1209 // owner not used in base class - see oci8
1210 $p = array();
1211 $objs = $this->MetaColumns($table);
1212 if ($objs) {
1213 foreach($objs as $v) {
1214 if (!empty($v->primary_key))
1215 $p[] = $v->name;
1218 if (sizeof($p)) return $p;
1219 if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
1220 return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
1221 return false;
1225 * @returns assoc array where keys are tables, and values are foreign keys
1227 function MetaForeignKeys($table, $owner=false, $upper=false)
1229 return false;
1232 * Choose a database to connect to. Many databases do not support this.
1234 * @param dbName is the name of the database to select
1235 * @return true or false
1237 function SelectDB($dbName)
1238 {return false;}
1242 * Will select, getting rows from $offset (1-based), for $nrows.
1243 * This simulates the MySQL "select * from table limit $offset,$nrows" , and
1244 * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
1245 * MySQL and PostgreSQL parameter ordering is the opposite of the other.
1246 * eg.
1247 * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
1248 * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
1250 * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
1251 * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
1253 * @param sql
1254 * @param [offset] is the row to start calculations from (1-based)
1255 * @param [nrows] is the number of rows to get
1256 * @param [inputarr] array of bind variables
1257 * @param [secs2cache] is a private parameter only used by jlim
1258 * @return the recordset ($rs->databaseType == 'array')
1260 function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
1262 if ($this->hasTop && $nrows > 0) {
1263 // suggested by Reinhard Balling. Access requires top after distinct
1264 // Informix requires first before distinct - F Riosa
1265 $ismssql = (strpos($this->databaseType,'mssql') !== false);
1266 if ($ismssql) $isaccess = false;
1267 else $isaccess = (strpos($this->databaseType,'access') !== false);
1269 if ($offset <= 0) {
1271 // access includes ties in result
1272 if ($isaccess) {
1273 $sql = preg_replace(
1274 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
1276 if ($secs2cache != 0) {
1277 $ret = $this->CacheExecute($secs2cache, $sql,$inputarr);
1278 } else {
1279 $ret = $this->Execute($sql,$inputarr);
1281 return $ret; // PHP5 fix
1282 } else if ($ismssql){
1283 $sql = preg_replace(
1284 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
1285 } else {
1286 $sql = preg_replace(
1287 '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
1289 } else {
1290 $nn = $nrows + $offset;
1291 if ($isaccess || $ismssql) {
1292 $sql = preg_replace(
1293 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
1294 } else {
1295 $sql = preg_replace(
1296 '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
1301 // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
1302 // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
1303 global $ADODB_COUNTRECS;
1305 $savec = $ADODB_COUNTRECS;
1306 $ADODB_COUNTRECS = false;
1309 if ($secs2cache != 0) $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
1310 else $rs = $this->Execute($sql,$inputarr);
1312 $ADODB_COUNTRECS = $savec;
1313 if ($rs && !$rs->EOF) {
1314 $rs = $this->_rs2rs($rs,$nrows,$offset);
1316 //print_r($rs);
1317 return $rs;
1321 * Create serializable recordset. Breaks rs link to connection.
1323 * @param rs the recordset to serialize
1325 function SerializableRS(&$rs)
1327 $rs2 = $this->_rs2rs($rs);
1328 $ignore = false;
1329 $rs2->connection = $ignore;
1331 return $rs2;
1335 * Convert database recordset to an array recordset
1336 * input recordset's cursor should be at beginning, and
1337 * old $rs will be closed.
1339 * @param rs the recordset to copy
1340 * @param [nrows] number of rows to retrieve (optional)
1341 * @param [offset] offset by number of rows (optional)
1342 * @return the new recordset
1344 function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
1346 if (! $rs) {
1347 $false = false;
1348 return $false;
1350 $dbtype = $rs->databaseType;
1351 if (!$dbtype) {
1352 $rs = $rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
1353 return $rs;
1355 if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
1356 $rs->MoveFirst();
1357 $rs = $rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
1358 return $rs;
1360 $flds = array();
1361 for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
1362 $flds[] = $rs->FetchField($i);
1365 $arr = $rs->GetArrayLimit($nrows,$offset);
1366 //print_r($arr);
1367 if ($close) $rs->Close();
1369 $arrayClass = $this->arrayClass;
1371 $rs2 = new $arrayClass();
1372 $rs2->connection = $this;
1373 $rs2->sql = $rs->sql;
1374 $rs2->dataProvider = $this->dataProvider;
1375 $rs2->InitArrayFields($arr,$flds);
1376 $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
1377 return $rs2;
1381 * Return all rows. Compat with PEAR DB
1383 function GetAll($sql, $inputarr=false)
1385 $arr = $this->GetArray($sql,$inputarr);
1386 return $arr;
1389 function GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
1391 $rs = $this->Execute($sql, $inputarr);
1392 if (!$rs) {
1393 $false = false;
1394 return $false;
1396 $arr = $rs->GetAssoc($force_array,$first2cols);
1397 return $arr;
1400 function CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
1402 if (!is_numeric($secs2cache)) {
1403 $first2cols = $force_array;
1404 $force_array = $inputarr;
1406 $rs = $this->CacheExecute($secs2cache, $sql, $inputarr);
1407 if (!$rs) {
1408 $false = false;
1409 return $false;
1411 $arr = $rs->GetAssoc($force_array,$first2cols);
1412 return $arr;
1416 * Return first element of first row of sql statement. Recordset is disposed
1417 * for you.
1419 * @param sql SQL statement
1420 * @param [inputarr] input bind array
1422 function GetOne($sql,$inputarr=false)
1424 global $ADODB_COUNTRECS,$ADODB_GETONE_EOF;
1425 $crecs = $ADODB_COUNTRECS;
1426 $ADODB_COUNTRECS = false;
1428 $ret = false;
1429 $rs = $this->Execute($sql,$inputarr);
1430 if ($rs) {
1431 if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
1432 else $ret = reset($rs->fields);
1434 $rs->Close();
1436 $ADODB_COUNTRECS = $crecs;
1437 return $ret;
1440 // $where should include 'WHERE fld=value'
1441 function GetMedian($table, $field,$where = '')
1443 $total = $this->GetOne("select count(*) from $table $where");
1444 if (!$total) return false;
1446 $midrow = (integer) ($total/2);
1447 $rs = $this->SelectLimit("select $field from $table $where order by 1",1,$midrow);
1448 if ($rs && !$rs->EOF) return reset($rs->fields);
1449 return false;
1453 function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
1455 global $ADODB_GETONE_EOF;
1456 $ret = false;
1457 $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
1458 if ($rs) {
1459 if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
1460 else $ret = reset($rs->fields);
1461 $rs->Close();
1464 return $ret;
1467 function GetCol($sql, $inputarr = false, $trim = false)
1470 $rs = $this->Execute($sql, $inputarr);
1471 if ($rs) {
1472 $rv = array();
1473 if ($trim) {
1474 while (!$rs->EOF) {
1475 $rv[] = trim(reset($rs->fields));
1476 $rs->MoveNext();
1478 } else {
1479 while (!$rs->EOF) {
1480 $rv[] = reset($rs->fields);
1481 $rs->MoveNext();
1484 $rs->Close();
1485 } else
1486 $rv = false;
1487 return $rv;
1490 function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
1492 $rs = $this->CacheExecute($secs, $sql, $inputarr);
1493 if ($rs) {
1494 $rv = array();
1495 if ($trim) {
1496 while (!$rs->EOF) {
1497 $rv[] = trim(reset($rs->fields));
1498 $rs->MoveNext();
1500 } else {
1501 while (!$rs->EOF) {
1502 $rv[] = reset($rs->fields);
1503 $rs->MoveNext();
1506 $rs->Close();
1507 } else
1508 $rv = false;
1510 return $rv;
1513 function Transpose(&$rs,$addfieldnames=true)
1515 $rs2 = $this->_rs2rs($rs);
1516 $false = false;
1517 if (!$rs2) return $false;
1519 $rs2->_transpose($addfieldnames);
1520 return $rs2;
1524 Calculate the offset of a date for a particular database and generate
1525 appropriate SQL. Useful for calculating future/past dates and storing
1526 in a database.
1528 If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
1530 function OffsetDate($dayFraction,$date=false)
1532 if (!$date) $date = $this->sysDate;
1533 return '('.$date.'+'.$dayFraction.')';
1539 * @param sql SQL statement
1540 * @param [inputarr] input bind array
1542 function GetArray($sql,$inputarr=false)
1544 global $ADODB_COUNTRECS;
1546 $savec = $ADODB_COUNTRECS;
1547 $ADODB_COUNTRECS = false;
1548 $rs = $this->Execute($sql,$inputarr);
1549 $ADODB_COUNTRECS = $savec;
1550 if (!$rs)
1551 if (defined('ADODB_PEAR')) {
1552 $cls = ADODB_PEAR_Error();
1553 return $cls;
1554 } else {
1555 $false = false;
1556 return $false;
1558 $arr = $rs->GetArray();
1559 $rs->Close();
1560 return $arr;
1563 function CacheGetAll($secs2cache,$sql=false,$inputarr=false)
1565 $arr = $this->CacheGetArray($secs2cache,$sql,$inputarr);
1566 return $arr;
1569 function CacheGetArray($secs2cache,$sql=false,$inputarr=false)
1571 global $ADODB_COUNTRECS;
1573 $savec = $ADODB_COUNTRECS;
1574 $ADODB_COUNTRECS = false;
1575 $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
1576 $ADODB_COUNTRECS = $savec;
1578 if (!$rs)
1579 if (defined('ADODB_PEAR')) {
1580 $cls = ADODB_PEAR_Error();
1581 return $cls;
1582 } else {
1583 $false = false;
1584 return $false;
1586 $arr = $rs->GetArray();
1587 $rs->Close();
1588 return $arr;
1591 function GetRandRow($sql, $arr= false)
1593 $rezarr = $this->GetAll($sql, $arr);
1594 $sz = sizeof($rezarr);
1595 return $rezarr[abs(rand()) % $sz];
1599 * Return one row of sql statement. Recordset is disposed for you.
1601 * @param sql SQL statement
1602 * @param [inputarr] input bind array
1604 function GetRow($sql,$inputarr=false)
1606 global $ADODB_COUNTRECS;
1607 $crecs = $ADODB_COUNTRECS;
1608 $ADODB_COUNTRECS = false;
1610 $rs = $this->Execute($sql,$inputarr);
1612 $ADODB_COUNTRECS = $crecs;
1613 if ($rs) {
1614 if (!$rs->EOF) $arr = $rs->fields;
1615 else $arr = array();
1616 $rs->Close();
1617 return $arr;
1620 $false = false;
1621 return $false;
1624 function CacheGetRow($secs2cache,$sql=false,$inputarr=false)
1626 $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
1627 if ($rs) {
1628 if (!$rs->EOF) $arr = $rs->fields;
1629 else $arr = array();
1631 $rs->Close();
1632 return $arr;
1634 $false = false;
1635 return $false;
1639 * Insert or replace a single record. Note: this is not the same as MySQL's replace.
1640 * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
1641 * Also note that no table locking is done currently, so it is possible that the
1642 * record be inserted twice by two programs...
1644 * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
1646 * $table table name
1647 * $fieldArray associative array of data (you must quote strings yourself).
1648 * $keyCol the primary key field name or if compound key, array of field names
1649 * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
1650 * but does not work with dates nor SQL functions.
1651 * has_autoinc the primary key is an auto-inc field, so skip in insert.
1653 * Currently blob replace not supported
1655 * returns 0 = fail, 1 = update, 2 = insert
1658 function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
1660 global $ADODB_INCLUDED_LIB;
1661 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
1663 return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
1668 * Will select, getting rows from $offset (1-based), for $nrows.
1669 * This simulates the MySQL "select * from table limit $offset,$nrows" , and
1670 * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
1671 * MySQL and PostgreSQL parameter ordering is the opposite of the other.
1672 * eg.
1673 * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
1674 * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
1676 * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
1678 * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
1679 * @param sql
1680 * @param [offset] is the row to start calculations from (1-based)
1681 * @param [nrows] is the number of rows to get
1682 * @param [inputarr] array of bind variables
1683 * @return the recordset ($rs->databaseType == 'array')
1685 function CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
1687 if (!is_numeric($secs2cache)) {
1688 if ($sql === false) $sql = -1;
1689 if ($offset == -1) $offset = false;
1690 // sql, nrows, offset,inputarr
1691 $rs = $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
1692 } else {
1693 if ($sql === false) $this->outp_throw("Warning: \$sql missing from CacheSelectLimit()",'CacheSelectLimit');
1694 $rs = $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
1696 return $rs;
1701 * Flush cached recordsets that match a particular $sql statement.
1702 * If $sql == false, then we purge all files in the cache.
1706 * Flush cached recordsets that match a particular $sql statement.
1707 * If $sql == false, then we purge all files in the cache.
1709 function CacheFlush($sql=false,$inputarr=false)
1711 global $ADODB_CACHE_DIR, $ADODB_CACHE;
1713 if (empty($ADODB_CACHE)) return false;
1715 if (!$sql) {
1716 $ADODB_CACHE->flushall($this->debug);
1717 return;
1720 $f = $this->_gencachename($sql.serialize($inputarr),false);
1721 return $ADODB_CACHE->flushcache($f, $this->debug);
1726 * Private function to generate filename for caching.
1727 * Filename is generated based on:
1729 * - sql statement
1730 * - database type (oci8, ibase, ifx, etc)
1731 * - database name
1732 * - userid
1733 * - setFetchMode (adodb 4.23)
1735 * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
1736 * Assuming that we can have 50,000 files per directory with good performance,
1737 * then we can scale to 12.8 million unique cached recordsets. Wow!
1739 function _gencachename($sql,$createdir)
1741 global $ADODB_CACHE, $ADODB_CACHE_DIR;
1743 if ($this->fetchMode === false) {
1744 global $ADODB_FETCH_MODE;
1745 $mode = $ADODB_FETCH_MODE;
1746 } else {
1747 $mode = $this->fetchMode;
1749 $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
1750 if (!$ADODB_CACHE->createdir) return $m;
1751 if (!$createdir) $dir = $ADODB_CACHE->getdirname($m);
1752 else $dir = $ADODB_CACHE->createdir($m, $this->debug);
1754 return $dir.'/adodb_'.$m.'.cache';
1759 * Execute SQL, caching recordsets.
1761 * @param [secs2cache] seconds to cache data, set to 0 to force query.
1762 * This is an optional parameter.
1763 * @param sql SQL statement to execute
1764 * @param [inputarr] holds the input data to bind to
1765 * @return RecordSet or false
1767 function CacheExecute($secs2cache,$sql=false,$inputarr=false)
1769 global $ADODB_CACHE;
1771 if (empty($ADODB_CACHE)) $this->_CreateCache();
1773 if (!is_numeric($secs2cache)) {
1774 $inputarr = $sql;
1775 $sql = $secs2cache;
1776 $secs2cache = $this->cacheSecs;
1779 if (is_array($sql)) {
1780 $sqlparam = $sql;
1781 $sql = $sql[0];
1782 } else
1783 $sqlparam = $sql;
1786 $md5file = $this->_gencachename($sql.serialize($inputarr),true);
1787 $err = '';
1789 if ($secs2cache > 0){
1790 $rs = $ADODB_CACHE->readcache($md5file,$err,$secs2cache,$this->arrayClass);
1791 $this->numCacheHits += 1;
1792 } else {
1793 $err='Timeout 1';
1794 $rs = false;
1795 $this->numCacheMisses += 1;
1798 if (!$rs) {
1799 // no cached rs found
1800 if ($this->debug) {
1801 if (get_magic_quotes_runtime() && !$this->memCache) {
1802 ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
1804 if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (this is a notice and not an error)");
1807 $rs = $this->Execute($sqlparam,$inputarr);
1809 if ($rs) {
1811 $eof = $rs->EOF;
1812 $rs = $this->_rs2rs($rs); // read entire recordset into memory immediately
1813 $rs->timeCreated = time(); // used by caching
1814 $txt = _rs2serialize($rs,false,$sql); // serialize
1816 $ok = $ADODB_CACHE->writecache($md5file,$txt,$this->debug, $secs2cache);
1817 if (!$ok) {
1818 if ($ok === false) {
1819 $em = 'Cache write error';
1820 $en = -32000;
1822 if ($fn = $this->raiseErrorFn) {
1823 $fn($this->databaseType,'CacheExecute', $en, $em, $md5file,$sql,$this);
1825 } else {
1826 $em = 'Cache file locked warning';
1827 $en = -32001;
1828 // do not call error handling for just a warning
1831 if ($this->debug) ADOConnection::outp( " ".$em);
1833 if ($rs->EOF && !$eof) {
1834 $rs->MoveFirst();
1835 //$rs = csv2rs($md5file,$err);
1836 $rs->connection = $this; // Pablo suggestion
1839 } else if (!$this->memCache)
1840 $ADODB_CACHE->flushcache($md5file);
1841 } else {
1842 $this->_errorMsg = '';
1843 $this->_errorCode = 0;
1845 if ($this->fnCacheExecute) {
1846 $fn = $this->fnCacheExecute;
1847 $fn($this, $secs2cache, $sql, $inputarr);
1849 // ok, set cached object found
1850 $rs->connection = $this; // Pablo suggestion
1851 if ($this->debug){
1852 if ($this->debug == 99) adodb_backtrace();
1853 $inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
1854 $ttl = $rs->timeCreated + $secs2cache - time();
1855 $s = is_array($sql) ? $sql[0] : $sql;
1856 if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
1858 ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
1861 return $rs;
1866 Similar to PEAR DB's autoExecute(), except that
1867 $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
1868 If $mode == 'UPDATE', then $where is compulsory as a safety measure.
1870 $forceUpdate means that even if the data has not changed, perform update.
1872 function AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false)
1874 $false = false;
1875 $sql = 'SELECT * FROM '.$table;
1876 if ($where!==FALSE) $sql .= ' WHERE '.$where;
1877 else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
1878 $this->outp_throw('AutoExecute: Illegal mode=UPDATE with empty WHERE clause','AutoExecute');
1879 return $false;
1882 $rs = $this->SelectLimit($sql,1);
1883 if (!$rs) return $false; // table does not exist
1884 $rs->tableName = $table;
1885 $rs->sql = $sql;
1887 switch((string) $mode) {
1888 case 'UPDATE':
1889 case '2':
1890 $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
1891 break;
1892 case 'INSERT':
1893 case '1':
1894 $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
1895 break;
1896 default:
1897 $this->outp_throw("AutoExecute: Unknown mode=$mode",'AutoExecute');
1898 return $false;
1900 $ret = false;
1901 if ($sql) $ret = $this->Execute($sql);
1902 if ($ret) $ret = true;
1903 return $ret;
1908 * Generates an Update Query based on an existing recordset.
1909 * $arrFields is an associative array of fields with the value
1910 * that should be assigned.
1912 * Note: This function should only be used on a recordset
1913 * that is run against a single table and sql should only
1914 * be a simple select stmt with no groupby/orderby/limit
1916 * "Jonathan Younger" <jyounger@unilab.com>
1918 function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
1920 global $ADODB_INCLUDED_LIB;
1922 //********************************************************//
1923 //This is here to maintain compatibility
1924 //with older adodb versions. Sets force type to force nulls if $forcenulls is set.
1925 if (!isset($force)) {
1926 global $ADODB_FORCE_TYPE;
1927 $force = $ADODB_FORCE_TYPE;
1929 //********************************************************//
1931 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
1932 return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
1936 * Generates an Insert Query based on an existing recordset.
1937 * $arrFields is an associative array of fields with the value
1938 * that should be assigned.
1940 * Note: This function should only be used on a recordset
1941 * that is run against a single table.
1943 function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
1945 global $ADODB_INCLUDED_LIB;
1946 if (!isset($force)) {
1947 global $ADODB_FORCE_TYPE;
1948 $force = $ADODB_FORCE_TYPE;
1951 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
1952 return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
1957 * Update a blob column, given a where clause. There are more sophisticated
1958 * blob handling functions that we could have implemented, but all require
1959 * a very complex API. Instead we have chosen something that is extremely
1960 * simple to understand and use.
1962 * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
1964 * Usage to update a $blobvalue which has a primary key blob_id=1 into a
1965 * field blobtable.blobcolumn:
1967 * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
1969 * Insert example:
1971 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
1972 * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
1975 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
1977 return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
1981 * Usage:
1982 * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
1984 * $blobtype supports 'BLOB' and 'CLOB'
1986 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
1987 * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
1989 function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
1991 $fd = fopen($path,'rb');
1992 if ($fd === false) return false;
1993 $val = fread($fd,filesize($path));
1994 fclose($fd);
1995 return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
1998 function BlobDecode($blob)
2000 return $blob;
2003 function BlobEncode($blob)
2005 return $blob;
2008 function SetCharSet($charset)
2010 return false;
2013 function IfNull( $field, $ifNull )
2015 return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
2018 function LogSQL($enable=true)
2020 include_once(ADODB_DIR.'/adodb-perf.inc.php');
2022 if ($enable) $this->fnExecute = 'adodb_log_sql';
2023 else $this->fnExecute = false;
2025 $old = $this->_logsql;
2026 $this->_logsql = $enable;
2027 if ($enable && !$old) $this->_affected = false;
2028 return $old;
2031 function GetCharSet()
2033 return false;
2037 * Usage:
2038 * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
2040 * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
2041 * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
2043 function UpdateClob($table,$column,$val,$where)
2045 return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
2048 // not the fastest implementation - quick and dirty - jlim
2049 // for best performance, use the actual $rs->MetaType().
2050 function MetaType($t,$len=-1,$fieldobj=false)
2053 if (empty($this->_metars)) {
2054 $rsclass = $this->rsPrefix.$this->databaseType;
2055 $this->_metars = new $rsclass(false,$this->fetchMode);
2056 $this->_metars->connection = $this;
2058 return $this->_metars->MetaType($t,$len,$fieldobj);
2063 * Change the SQL connection locale to a specified locale.
2064 * This is used to get the date formats written depending on the client locale.
2066 function SetDateLocale($locale = 'En')
2068 $this->locale = $locale;
2069 switch (strtoupper($locale))
2071 case 'EN':
2072 $this->fmtDate="'Y-m-d'";
2073 $this->fmtTimeStamp = "'Y-m-d H:i:s'";
2074 break;
2076 case 'US':
2077 $this->fmtDate = "'m-d-Y'";
2078 $this->fmtTimeStamp = "'m-d-Y H:i:s'";
2079 break;
2081 case 'PT_BR':
2082 case 'NL':
2083 case 'FR':
2084 case 'RO':
2085 case 'IT':
2086 $this->fmtDate="'d-m-Y'";
2087 $this->fmtTimeStamp = "'d-m-Y H:i:s'";
2088 break;
2090 case 'GE':
2091 $this->fmtDate="'d.m.Y'";
2092 $this->fmtTimeStamp = "'d.m.Y H:i:s'";
2093 break;
2095 default:
2096 $this->fmtDate="'Y-m-d'";
2097 $this->fmtTimeStamp = "'Y-m-d H:i:s'";
2098 break;
2103 * GetActiveRecordsClass Performs an 'ALL' query
2105 * @param mixed $class This string represents the class of the current active record
2106 * @param mixed $table Table used by the active record object
2107 * @param mixed $whereOrderBy Where, order, by clauses
2108 * @param mixed $bindarr
2109 * @param mixed $primkeyArr
2110 * @param array $extra Query extras: limit, offset...
2111 * @param mixed $relations Associative array: table's foreign name, "hasMany", "belongsTo"
2112 * @access public
2113 * @return void
2115 function GetActiveRecordsClass(
2116 $class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false,
2117 $extra=array(),
2118 $relations=array())
2120 global $_ADODB_ACTIVE_DBS;
2121 ## reduce overhead of adodb.inc.php -- moved to adodb-active-record.inc.php
2122 ## if adodb-active-recordx is loaded -- should be no issue as they will probably use Find()
2123 if (!isset($_ADODB_ACTIVE_DBS))include_once(ADODB_DIR.'/adodb-active-record.inc.php');
2124 return adodb_GetActiveRecordsClass($this, $class, $table, $whereOrderBy, $bindarr, $primkeyArr, $extra, $relations);
2127 function GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
2129 $arr = $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
2130 return $arr;
2134 * Close Connection
2136 function Close()
2138 $rez = $this->_close();
2139 $this->_connectionID = false;
2140 return $rez;
2144 * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
2146 * @return true if succeeded or false if database does not support transactions
2148 function BeginTrans()
2150 if ($this->debug) ADOConnection::outp("BeginTrans: Transactions not supported for this driver");
2151 return false;
2154 /* set transaction mode */
2155 function SetTransactionMode( $transaction_mode )
2157 $transaction_mode = $this->MetaTransaction($transaction_mode, $this->dataProvider);
2158 $this->_transmode = $transaction_mode;
2161 http://msdn2.microsoft.com/en-US/ms173763.aspx
2162 http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-isolation.html
2163 http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html
2164 http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm
2166 function MetaTransaction($mode,$db)
2168 $mode = strtoupper($mode);
2169 $mode = str_replace('ISOLATION LEVEL ','',$mode);
2171 switch($mode) {
2173 case 'READ UNCOMMITTED':
2174 switch($db) {
2175 case 'oci8':
2176 case 'oracle':
2177 return 'ISOLATION LEVEL READ COMMITTED';
2178 default:
2179 return 'ISOLATION LEVEL READ UNCOMMITTED';
2181 break;
2183 case 'READ COMMITTED':
2184 return 'ISOLATION LEVEL READ COMMITTED';
2185 break;
2187 case 'REPEATABLE READ':
2188 switch($db) {
2189 case 'oci8':
2190 case 'oracle':
2191 return 'ISOLATION LEVEL SERIALIZABLE';
2192 default:
2193 return 'ISOLATION LEVEL REPEATABLE READ';
2195 break;
2197 case 'SERIALIZABLE':
2198 return 'ISOLATION LEVEL SERIALIZABLE';
2199 break;
2201 default:
2202 return $mode;
2207 * If database does not support transactions, always return true as data always commited
2209 * @param $ok set to false to rollback transaction, true to commit
2211 * @return true/false.
2213 function CommitTrans($ok=true)
2214 { return true;}
2218 * If database does not support transactions, rollbacks always fail, so return false
2220 * @return true/false.
2222 function RollbackTrans()
2223 { return false;}
2227 * return the databases that the driver can connect to.
2228 * Some databases will return an empty array.
2230 * @return an array of database names.
2232 function MetaDatabases()
2234 global $ADODB_FETCH_MODE;
2236 if ($this->metaDatabasesSQL) {
2237 $save = $ADODB_FETCH_MODE;
2238 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
2240 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
2242 $arr = $this->GetCol($this->metaDatabasesSQL);
2243 if (isset($savem)) $this->SetFetchMode($savem);
2244 $ADODB_FETCH_MODE = $save;
2246 return $arr;
2249 return false;
2254 * @param ttype can either be 'VIEW' or 'TABLE' or false.
2255 * If false, both views and tables are returned.
2256 * "VIEW" returns only views
2257 * "TABLE" returns only tables
2258 * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
2259 * @param mask is the input mask - only supported by oci8 and postgresql
2261 * @return array of tables for current database.
2263 function MetaTables($ttype=false,$showSchema=false,$mask=false)
2265 global $ADODB_FETCH_MODE;
2268 $false = false;
2269 if ($mask) {
2270 return $false;
2272 if ($this->metaTablesSQL) {
2273 $save = $ADODB_FETCH_MODE;
2274 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
2276 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
2278 $rs = $this->Execute($this->metaTablesSQL);
2279 if (isset($savem)) $this->SetFetchMode($savem);
2280 $ADODB_FETCH_MODE = $save;
2282 if ($rs === false) return $false;
2283 $arr = $rs->GetArray();
2284 $arr2 = array();
2286 if ($hast = ($ttype && isset($arr[0][1]))) {
2287 $showt = strncmp($ttype,'T',1);
2290 for ($i=0; $i < sizeof($arr); $i++) {
2291 if ($hast) {
2292 if ($showt == 0) {
2293 if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
2294 } else {
2295 if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
2297 } else
2298 $arr2[] = trim($arr[$i][0]);
2300 $rs->Close();
2301 return $arr2;
2303 return $false;
2307 function _findschema(&$table,&$schema)
2309 if (!$schema && ($at = strpos($table,'.')) !== false) {
2310 $schema = substr($table,0,$at);
2311 $table = substr($table,$at+1);
2316 * List columns in a database as an array of ADOFieldObjects.
2317 * See top of file for definition of object.
2319 * @param $table table name to query
2320 * @param $normalize makes table name case-insensitive (required by some databases)
2321 * @schema is optional database schema to use - not supported by all databases.
2323 * @return array of ADOFieldObjects for current table.
2325 function MetaColumns($table,$normalize=true)
2327 global $ADODB_FETCH_MODE;
2329 $false = false;
2331 if (!empty($this->metaColumnsSQL)) {
2333 $schema = false;
2334 $this->_findschema($table,$schema);
2336 $save = $ADODB_FETCH_MODE;
2337 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
2338 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
2339 $rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table));
2340 if (isset($savem)) $this->SetFetchMode($savem);
2341 $ADODB_FETCH_MODE = $save;
2342 if ($rs === false || $rs->EOF) return $false;
2344 $retarr = array();
2345 while (!$rs->EOF) { //print_r($rs->fields);
2346 $fld = new ADOFieldObject();
2347 $fld->name = $rs->fields[0];
2348 $fld->type = $rs->fields[1];
2349 if (isset($rs->fields[3]) && $rs->fields[3]) {
2350 if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
2351 $fld->scale = $rs->fields[4];
2352 if ($fld->scale>0) $fld->max_length += 1;
2353 } else
2354 $fld->max_length = $rs->fields[2];
2356 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
2357 else $retarr[strtoupper($fld->name)] = $fld;
2358 $rs->MoveNext();
2360 $rs->Close();
2361 return $retarr;
2363 return $false;
2367 * List indexes on a table as an array.
2368 * @param table table name to query
2369 * @param primary true to only show primary keys. Not actually used for most databases
2371 * @return array of indexes on current table. Each element represents an index, and is itself an associative array.
2373 Array (
2374 [name_of_index] => Array
2376 [unique] => true or false
2377 [columns] => Array
2379 [0] => firstname
2380 [1] => lastname
2384 function MetaIndexes($table, $primary = false, $owner = false)
2386 $false = false;
2387 return $false;
2391 * List columns names in a table as an array.
2392 * @param table table name to query
2394 * @return array of column names for current table.
2396 function MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */)
2398 $objarr = $this->MetaColumns($table);
2399 if (!is_array($objarr)) {
2400 $false = false;
2401 return $false;
2403 $arr = array();
2404 if ($numIndexes) {
2405 $i = 0;
2406 if ($useattnum) {
2407 foreach($objarr as $v)
2408 $arr[$v->attnum] = $v->name;
2410 } else
2411 foreach($objarr as $v) $arr[$i++] = $v->name;
2412 } else
2413 foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
2415 return $arr;
2419 * Different SQL databases used different methods to combine strings together.
2420 * This function provides a wrapper.
2422 * param s variable number of string parameters
2424 * Usage: $db->Concat($str1,$str2);
2426 * @return concatenated string
2428 function Concat()
2430 $arr = func_get_args();
2431 return implode($this->concat_operator, $arr);
2436 * Converts a date "d" to a string that the database can understand.
2438 * @param d a date in Unix date time format.
2440 * @return date string in database date format
2442 function DBDate($d, $isfld=false)
2444 if (empty($d) && $d !== 0) return 'null';
2445 if ($isfld) return $d;
2447 if (is_object($d)) return $d->format($this->fmtDate);
2450 if (is_string($d) && !is_numeric($d)) {
2451 if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
2452 if ($this->isoDates) return "'$d'";
2453 $d = ADOConnection::UnixDate($d);
2456 return adodb_date($this->fmtDate,$d);
2459 function BindDate($d)
2461 $d = $this->DBDate($d);
2462 if (strncmp($d,"'",1)) return $d;
2464 return substr($d,1,strlen($d)-2);
2467 function BindTimeStamp($d)
2469 $d = $this->DBTimeStamp($d);
2470 if (strncmp($d,"'",1)) return $d;
2472 return substr($d,1,strlen($d)-2);
2477 * Converts a timestamp "ts" to a string that the database can understand.
2479 * @param ts a timestamp in Unix date time format.
2481 * @return timestamp string in database timestamp format
2483 function DBTimeStamp($ts,$isfld=false)
2485 if (empty($ts) && $ts !== 0) return 'null';
2486 if ($isfld) return $ts;
2487 if (is_object($ts)) return $ts->format($this->fmtTimeStamp);
2489 # strlen(14) allows YYYYMMDDHHMMSS format
2490 if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
2491 return adodb_date($this->fmtTimeStamp,$ts);
2493 if ($ts === 'null') return $ts;
2494 if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
2496 $ts = ADOConnection::UnixTimeStamp($ts);
2497 return adodb_date($this->fmtTimeStamp,$ts);
2501 * Also in ADORecordSet.
2502 * @param $v is a date string in YYYY-MM-DD format
2504 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2506 static function UnixDate($v)
2508 if (is_object($v)) {
2509 // odbtp support
2510 //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
2511 return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
2514 if (is_numeric($v) && strlen($v) !== 8) return $v;
2515 if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
2516 ($v), $rr)) return false;
2518 if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
2519 // h-m-s-MM-DD-YY
2520 return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2525 * Also in ADORecordSet.
2526 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
2528 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2530 static function UnixTimeStamp($v)
2532 if (is_object($v)) {
2533 // odbtp support
2534 //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
2535 return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
2538 if (!preg_match(
2539 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
2540 ($v), $rr)) return false;
2542 if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
2544 // h-m-s-MM-DD-YY
2545 if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2546 return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
2550 * Also in ADORecordSet.
2552 * Format database date based on user defined format.
2554 * @param v is the character date in YYYY-MM-DD format, returned by database
2555 * @param fmt is the format to apply to it, using date()
2557 * @return a date formated as user desires
2560 function UserDate($v,$fmt='Y-m-d',$gmt=false)
2562 $tt = $this->UnixDate($v);
2564 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2565 if (($tt === false || $tt == -1) && $v != false) return $v;
2566 else if ($tt == 0) return $this->emptyDate;
2567 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
2570 return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
2576 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
2577 * @param fmt is the format to apply to it, using date()
2579 * @return a timestamp formated as user desires
2581 function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false)
2583 if (!isset($v)) return $this->emptyTimeStamp;
2584 # strlen(14) allows YYYYMMDDHHMMSS format
2585 if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
2586 $tt = $this->UnixTimeStamp($v);
2587 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2588 if (($tt === false || $tt == -1) && $v != false) return $v;
2589 if ($tt == 0) return $this->emptyTimeStamp;
2590 return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
2593 function escape($s,$magic_quotes=false)
2595 return $this->addq($s,$magic_quotes);
2599 * Quotes a string, without prefixing nor appending quotes.
2601 function addq($s,$magic_quotes=false)
2603 if (!$magic_quotes) {
2605 if ($this->replaceQuote[0] == '\\'){
2606 // only since php 4.0.5
2607 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
2608 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
2610 return str_replace("'",$this->replaceQuote,$s);
2613 // undo magic quotes for "
2614 $s = str_replace('\\"','"',$s);
2616 if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything
2617 return $s;
2618 else {// change \' to '' for sybase/mssql
2619 $s = str_replace('\\\\','\\',$s);
2620 return str_replace("\\'",$this->replaceQuote,$s);
2625 * Correctly quotes a string so that all strings are escaped. We prefix and append
2626 * to the string single-quotes.
2627 * An example is $db->qstr("Don't bother",magic_quotes_runtime());
2629 * @param s the string to quote
2630 * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
2631 * This undoes the stupidity of magic quotes for GPC.
2633 * @return quoted string to be sent back to database
2635 function qstr($s,$magic_quotes=false)
2637 if (!$magic_quotes) {
2639 if ($this->replaceQuote[0] == '\\'){
2640 // only since php 4.0.5
2641 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
2642 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
2644 return "'".str_replace("'",$this->replaceQuote,$s)."'";
2647 // undo magic quotes for "
2648 $s = str_replace('\\"','"',$s);
2650 if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything
2651 return "'$s'";
2652 else {// change \' to '' for sybase/mssql
2653 $s = str_replace('\\\\','\\',$s);
2654 return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
2660 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
2661 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
2662 * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
2664 * See readme.htm#ex8 for an example of usage.
2666 * @param sql
2667 * @param nrows is the number of rows per page to get
2668 * @param page is the page number to get (1-based)
2669 * @param [inputarr] array of bind variables
2670 * @param [secs2cache] is a private parameter only used by jlim
2671 * @return the recordset ($rs->databaseType == 'array')
2673 * NOTE: phpLens uses a different algorithm and does not use PageExecute().
2676 function PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0)
2678 global $ADODB_INCLUDED_LIB;
2679 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
2680 if ($this->pageExecuteCountRows) $rs = _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
2681 else $rs = _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
2682 return $rs;
2687 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
2688 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
2689 * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
2691 * @param secs2cache seconds to cache data, set to 0 to force query
2692 * @param sql
2693 * @param nrows is the number of rows per page to get
2694 * @param page is the page number to get (1-based)
2695 * @param [inputarr] array of bind variables
2696 * @return the recordset ($rs->databaseType == 'array')
2698 function CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false)
2700 /*switch($this->dataProvider) {
2701 case 'postgres':
2702 case 'mysql':
2703 break;
2704 default: $secs2cache = 0; break;
2706 $rs = $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
2707 return $rs;
2710 } // end class ADOConnection
2714 //==============================================================================================
2715 // CLASS ADOFetchObj
2716 //==============================================================================================
2719 * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
2721 class ADOFetchObj {
2724 //==============================================================================================
2725 // CLASS ADORecordSet_empty
2726 //==============================================================================================
2728 class ADODB_Iterator_empty implements Iterator {
2730 private $rs;
2732 function __construct($rs)
2734 $this->rs = $rs;
2736 function rewind()
2740 function valid()
2742 return !$this->rs->EOF;
2745 function key()
2747 return false;
2750 function current()
2752 return false;
2755 function next()
2759 function __call($func, $params)
2761 return call_user_func_array(array($this->rs, $func), $params);
2764 function hasMore()
2766 return false;
2773 * Lightweight recordset when there are no records to be returned
2775 class ADORecordSet_empty implements IteratorAggregate
2777 var $dataProvider = 'empty';
2778 var $databaseType = false;
2779 var $EOF = true;
2780 var $_numOfRows = 0;
2781 var $fields = false;
2782 var $connection = false;
2783 function RowCount() {return 0;}
2784 function RecordCount() {return 0;}
2785 function PO_RecordCount(){return 0;}
2786 function Close(){return true;}
2787 function FetchRow() {return false;}
2788 function FieldCount(){ return 0;}
2789 function Init() {}
2790 function getIterator() {return new ADODB_Iterator_empty($this);}
2793 //==============================================================================================
2794 // DATE AND TIME FUNCTIONS
2795 //==============================================================================================
2796 if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR.'/adodb-time.inc.php');
2798 //==============================================================================================
2799 // CLASS ADORecordSet
2800 //==============================================================================================
2802 class ADODB_Iterator implements Iterator {
2804 private $rs;
2806 function __construct($rs)
2808 $this->rs = $rs;
2810 function rewind()
2812 $this->rs->MoveFirst();
2815 function valid()
2817 return !$this->rs->EOF;
2820 function key()
2822 return $this->rs->_currentRow;
2825 function current()
2827 return $this->rs->fields;
2830 function next()
2832 $this->rs->MoveNext();
2835 function __call($func, $params)
2837 return call_user_func_array(array($this->rs, $func), $params);
2841 function hasMore()
2843 return !$this->rs->EOF;
2851 * RecordSet class that represents the dataset returned by the database.
2852 * To keep memory overhead low, this class holds only the current row in memory.
2853 * No prefetching of data is done, so the RecordCount() can return -1 ( which
2854 * means recordcount not known).
2856 class ADORecordSet implements IteratorAggregate {
2858 * public variables
2860 var $dataProvider = "native";
2861 var $fields = false; /// holds the current row data
2862 var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
2863 /// in other words, we use a text area for editing.
2864 var $canSeek = false; /// indicates that seek is supported
2865 var $sql; /// sql text
2866 var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
2868 var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
2869 var $emptyDate = '&nbsp;'; /// what to display when $time==0
2870 var $debug = false;
2871 var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
2873 var $bind = false; /// used by Fields() to hold array - should be private?
2874 var $fetchMode; /// default fetch mode
2875 var $connection = false; /// the parent connection
2877 * private variables
2879 var $_numOfRows = -1; /** number of rows, or -1 */
2880 var $_numOfFields = -1; /** number of fields in recordset */
2881 var $_queryID = -1; /** This variable keeps the result link identifier. */
2882 var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
2883 var $_closed = false; /** has recordset been closed */
2884 var $_inited = false; /** Init() should only be called once */
2885 var $_obj; /** Used by FetchObj */
2886 var $_names; /** Used by FetchObj */
2888 var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */
2889 var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */
2890 var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */
2891 var $_lastPageNo = -1;
2892 var $_maxRecordCount = 0;
2893 var $datetime = false;
2896 * Constructor
2898 * @param queryID this is the queryID returned by ADOConnection->_query()
2901 function ADORecordSet($queryID)
2903 $this->_queryID = $queryID;
2906 function getIterator()
2908 return new ADODB_Iterator($this);
2911 /* this is experimental - i don't really know what to return... */
2912 function __toString()
2914 include_once(ADODB_DIR.'/toexport.inc.php');
2915 return _adodb_export($this,',',',',false,true);
2919 function Init()
2921 if ($this->_inited) return;
2922 $this->_inited = true;
2923 if ($this->_queryID) @$this->_initrs();
2924 else {
2925 $this->_numOfRows = 0;
2926 $this->_numOfFields = 0;
2928 if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
2930 $this->_currentRow = 0;
2931 if ($this->EOF = ($this->_fetch() === false)) {
2932 $this->_numOfRows = 0; // _numOfRows could be -1
2934 } else {
2935 $this->EOF = true;
2941 * Generate a SELECT tag string from a recordset, and return the string.
2942 * If the recordset has 2 cols, we treat the 1st col as the containing
2943 * the text to display to the user, and 2nd col as the return value. Default
2944 * strings are compared with the FIRST column.
2946 * @param name name of SELECT tag
2947 * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
2948 * @param [blank1stItem] true to leave the 1st item in list empty
2949 * @param [multiple] true for listbox, false for popup
2950 * @param [size] #rows to show for listbox. not used by popup
2951 * @param [selectAttr] additional attributes to defined for SELECT tag.
2952 * useful for holding javascript onChange='...' handlers.
2953 & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
2954 * column 0 (1st col) if this is true. This is not documented.
2956 * @return HTML
2958 * changes by glen.davies@cce.ac.nz to support multiple hilited items
2960 function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
2961 $size=0, $selectAttr='',$compareFields0=true)
2963 global $ADODB_INCLUDED_LIB;
2964 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
2965 return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
2966 $size, $selectAttr,$compareFields0);
2972 * Generate a SELECT tag string from a recordset, and return the string.
2973 * If the recordset has 2 cols, we treat the 1st col as the containing
2974 * the text to display to the user, and 2nd col as the return value. Default
2975 * strings are compared with the SECOND column.
2978 function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
2980 return $this->GetMenu($name,$defstr,$blank1stItem,$multiple,
2981 $size, $selectAttr,false);
2985 Grouped Menu
2987 function GetMenu3($name,$defstr='',$blank1stItem=true,$multiple=false,
2988 $size=0, $selectAttr='')
2990 global $ADODB_INCLUDED_LIB;
2991 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
2992 return _adodb_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple,
2993 $size, $selectAttr,false);
2997 * return recordset as a 2-dimensional array.
2999 * @param [nRows] is the number of rows to return. -1 means every row.
3001 * @return an array indexed by the rows (0-based) from the recordset
3003 function GetArray($nRows = -1)
3005 global $ADODB_EXTENSION; if ($ADODB_EXTENSION) {
3006 $results = adodb_getall($this,$nRows);
3007 return $results;
3009 $results = array();
3010 $cnt = 0;
3011 while (!$this->EOF && $nRows != $cnt) {
3012 $results[] = $this->fields;
3013 $this->MoveNext();
3014 $cnt++;
3016 return $results;
3019 function GetAll($nRows = -1)
3021 $arr = $this->GetArray($nRows);
3022 return $arr;
3026 * Some databases allow multiple recordsets to be returned. This function
3027 * will return true if there is a next recordset, or false if no more.
3029 function NextRecordSet()
3031 return false;
3035 * return recordset as a 2-dimensional array.
3036 * Helper function for ADOConnection->SelectLimit()
3038 * @param offset is the row to start calculations from (1-based)
3039 * @param [nrows] is the number of rows to return
3041 * @return an array indexed by the rows (0-based) from the recordset
3043 function GetArrayLimit($nrows,$offset=-1)
3045 if ($offset <= 0) {
3046 $arr = $this->GetArray($nrows);
3047 return $arr;
3050 $this->Move($offset);
3052 $results = array();
3053 $cnt = 0;
3054 while (!$this->EOF && $nrows != $cnt) {
3055 $results[$cnt++] = $this->fields;
3056 $this->MoveNext();
3059 return $results;
3064 * Synonym for GetArray() for compatibility with ADO.
3066 * @param [nRows] is the number of rows to return. -1 means every row.
3068 * @return an array indexed by the rows (0-based) from the recordset
3070 function GetRows($nRows = -1)
3072 $arr = $this->GetArray($nRows);
3073 return $arr;
3077 * return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
3078 * The first column is treated as the key and is not included in the array.
3079 * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
3080 * $force_array == true.
3082 * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
3083 * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
3084 * read the source.
3086 * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
3087 * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
3089 * @return an associative array indexed by the first column of the array,
3090 * or false if the data has less than 2 cols.
3092 function GetAssoc($force_array = false, $first2cols = false)
3094 global $ADODB_EXTENSION;
3096 $cols = $this->_numOfFields;
3097 if ($cols < 2) {
3098 $false = false;
3099 return $false;
3101 $numIndex = isset($this->fields[0]);
3102 $results = array();
3104 if (!$first2cols && ($cols > 2 || $force_array)) {
3105 if ($ADODB_EXTENSION) {
3106 if ($numIndex) {
3107 while (!$this->EOF) {
3108 $results[trim($this->fields[0])] = array_slice($this->fields, 1);
3109 adodb_movenext($this);
3111 } else {
3112 while (!$this->EOF) {
3113 // Fix for array_slice re-numbering numeric associative keys
3114 $keys = array_slice(array_keys($this->fields), 1);
3115 $sliced_array = array();
3117 foreach($keys as $key) {
3118 $sliced_array[$key] = $this->fields[$key];
3121 $results[trim(reset($this->fields))] = $sliced_array;
3122 adodb_movenext($this);
3125 } else {
3126 if ($numIndex) {
3127 while (!$this->EOF) {
3128 $results[trim($this->fields[0])] = array_slice($this->fields, 1);
3129 $this->MoveNext();
3131 } else {
3132 while (!$this->EOF) {
3133 // Fix for array_slice re-numbering numeric associative keys
3134 $keys = array_slice(array_keys($this->fields), 1);
3135 $sliced_array = array();
3137 foreach($keys as $key) {
3138 $sliced_array[$key] = $this->fields[$key];
3141 $results[trim(reset($this->fields))] = $sliced_array;
3142 $this->MoveNext();
3146 } else {
3147 if ($ADODB_EXTENSION) {
3148 // return scalar values
3149 if ($numIndex) {
3150 while (!$this->EOF) {
3151 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3152 $results[trim(($this->fields[0]))] = $this->fields[1];
3153 adodb_movenext($this);
3155 } else {
3156 while (!$this->EOF) {
3157 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3158 $v1 = trim(reset($this->fields));
3159 $v2 = ''.next($this->fields);
3160 $results[$v1] = $v2;
3161 adodb_movenext($this);
3164 } else {
3165 if ($numIndex) {
3166 while (!$this->EOF) {
3167 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3168 $results[trim(($this->fields[0]))] = $this->fields[1];
3169 $this->MoveNext();
3171 } else {
3172 while (!$this->EOF) {
3173 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3174 $v1 = trim(reset($this->fields));
3175 $v2 = ''.next($this->fields);
3176 $results[$v1] = $v2;
3177 $this->MoveNext();
3183 $ref = $results; # workaround accelerator incompat with PHP 4.4 :(
3184 return $ref;
3190 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
3191 * @param fmt is the format to apply to it, using date()
3193 * @return a timestamp formated as user desires
3195 function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
3197 if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
3198 $tt = $this->UnixTimeStamp($v);
3199 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
3200 if (($tt === false || $tt == -1) && $v != false) return $v;
3201 if ($tt === 0) return $this->emptyTimeStamp;
3202 return adodb_date($fmt,$tt);
3207 * @param v is the character date in YYYY-MM-DD format, returned by database
3208 * @param fmt is the format to apply to it, using date()
3210 * @return a date formated as user desires
3212 function UserDate($v,$fmt='Y-m-d')
3214 $tt = $this->UnixDate($v);
3215 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
3216 if (($tt === false || $tt == -1) && $v != false) return $v;
3217 else if ($tt == 0) return $this->emptyDate;
3218 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
3220 return adodb_date($fmt,$tt);
3225 * @param $v is a date string in YYYY-MM-DD format
3227 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
3229 static function UnixDate($v)
3231 return ADOConnection::UnixDate($v);
3236 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
3238 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
3240 static function UnixTimeStamp($v)
3242 return ADOConnection::UnixTimeStamp($v);
3247 * PEAR DB Compat - do not use internally
3249 function Free()
3251 return $this->Close();
3256 * PEAR DB compat, number of rows
3258 function NumRows()
3260 return $this->_numOfRows;
3265 * PEAR DB compat, number of cols
3267 function NumCols()
3269 return $this->_numOfFields;
3273 * Fetch a row, returning false if no more rows.
3274 * This is PEAR DB compat mode.
3276 * @return false or array containing the current record
3278 function FetchRow()
3280 if ($this->EOF) {
3281 $false = false;
3282 return $false;
3284 $arr = $this->fields;
3285 $this->_currentRow++;
3286 if (!$this->_fetch()) $this->EOF = true;
3287 return $arr;
3292 * Fetch a row, returning PEAR_Error if no more rows.
3293 * This is PEAR DB compat mode.
3295 * @return DB_OK or error object
3297 function FetchInto(&$arr)
3299 if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
3300 $arr = $this->fields;
3301 $this->MoveNext();
3302 return 1; // DB_OK
3307 * Move to the first row in the recordset. Many databases do NOT support this.
3309 * @return true or false
3311 function MoveFirst()
3313 if ($this->_currentRow == 0) return true;
3314 return $this->Move(0);
3319 * Move to the last row in the recordset.
3321 * @return true or false
3323 function MoveLast()
3325 if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
3326 if ($this->EOF) return false;
3327 while (!$this->EOF) {
3328 $f = $this->fields;
3329 $this->MoveNext();
3331 $this->fields = $f;
3332 $this->EOF = false;
3333 return true;
3338 * Move to next record in the recordset.
3340 * @return true if there still rows available, or false if there are no more rows (EOF).
3342 function MoveNext()
3344 if (!$this->EOF) {
3345 $this->_currentRow++;
3346 if ($this->_fetch()) return true;
3348 $this->EOF = true;
3349 /* -- tested error handling when scrolling cursor -- seems useless.
3350 $conn = $this->connection;
3351 if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
3352 $fn = $conn->raiseErrorFn;
3353 $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
3356 return false;
3361 * Random access to a specific row in the recordset. Some databases do not support
3362 * access to previous rows in the databases (no scrolling backwards).
3364 * @param rowNumber is the row to move to (0-based)
3366 * @return true if there still rows available, or false if there are no more rows (EOF).
3368 function Move($rowNumber = 0)
3370 $this->EOF = false;
3371 if ($rowNumber == $this->_currentRow) return true;
3372 if ($rowNumber >= $this->_numOfRows)
3373 if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
3375 if ($this->canSeek) {
3377 if ($this->_seek($rowNumber)) {
3378 $this->_currentRow = $rowNumber;
3379 if ($this->_fetch()) {
3380 return true;
3382 } else {
3383 $this->EOF = true;
3384 return false;
3386 } else {
3387 if ($rowNumber < $this->_currentRow) return false;
3388 global $ADODB_EXTENSION;
3389 if ($ADODB_EXTENSION) {
3390 while (!$this->EOF && $this->_currentRow < $rowNumber) {
3391 adodb_movenext($this);
3393 } else {
3395 while (! $this->EOF && $this->_currentRow < $rowNumber) {
3396 $this->_currentRow++;
3398 if (!$this->_fetch()) $this->EOF = true;
3401 return !($this->EOF);
3404 $this->fields = false;
3405 $this->EOF = true;
3406 return false;
3411 * Get the value of a field in the current row by column name.
3412 * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
3414 * @param colname is the field to access
3416 * @return the value of $colname column
3418 function Fields($colname)
3420 return $this->fields[$colname];
3423 function GetAssocKeys($upper=true)
3425 $this->bind = array();
3426 for ($i=0; $i < $this->_numOfFields; $i++) {
3427 $o = $this->FetchField($i);
3428 if ($upper === 2) $this->bind[$o->name] = $i;
3429 else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
3434 * Use associative array to get fields array for databases that do not support
3435 * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it
3437 * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
3438 * before you execute your SQL statement, and access $rs->fields['col'] directly.
3440 * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
3442 function GetRowAssoc($upper=1)
3444 $record = array();
3445 // if (!$this->fields) return $record;
3447 if (!$this->bind) {
3448 $this->GetAssocKeys($upper);
3451 foreach($this->bind as $k => $v) {
3452 $record[$k] = $this->fields[$v];
3455 return $record;
3460 * Clean up recordset
3462 * @return true or false
3464 function Close()
3466 // free connection object - this seems to globally free the object
3467 // and not merely the reference, so don't do this...
3468 // $this->connection = false;
3469 if (!$this->_closed) {
3470 $this->_closed = true;
3471 return $this->_close();
3472 } else
3473 return true;
3477 * synonyms RecordCount and RowCount
3479 * @return the number of rows or -1 if this is not supported
3481 function RecordCount() {return $this->_numOfRows;}
3485 * If we are using PageExecute(), this will return the maximum possible rows
3486 * that can be returned when paging a recordset.
3488 function MaxRecordCount()
3490 return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
3494 * synonyms RecordCount and RowCount
3496 * @return the number of rows or -1 if this is not supported
3498 function RowCount() {return $this->_numOfRows;}
3502 * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
3504 * @return the number of records from a previous SELECT. All databases support this.
3506 * But aware possible problems in multiuser environments. For better speed the table
3507 * must be indexed by the condition. Heavy test this before deploying.
3509 function PO_RecordCount($table="", $condition="") {
3511 $lnumrows = $this->_numOfRows;
3512 // the database doesn't support native recordcount, so we do a workaround
3513 if ($lnumrows == -1 && $this->connection) {
3514 IF ($table) {
3515 if ($condition) $condition = " WHERE " . $condition;
3516 $resultrows = $this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
3517 if ($resultrows) $lnumrows = reset($resultrows->fields);
3520 return $lnumrows;
3525 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
3527 function CurrentRow() {return $this->_currentRow;}
3530 * synonym for CurrentRow -- for ADO compat
3532 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
3534 function AbsolutePosition() {return $this->_currentRow;}
3537 * @return the number of columns in the recordset. Some databases will set this to 0
3538 * if no records are returned, others will return the number of columns in the query.
3540 function FieldCount() {return $this->_numOfFields;}
3544 * Get the ADOFieldObject of a specific column.
3546 * @param fieldoffset is the column position to access(0-based).
3548 * @return the ADOFieldObject for that column, or false.
3550 function FetchField($fieldoffset = -1)
3552 // must be defined by child class
3554 $false = false;
3555 return $false;
3559 * Get the ADOFieldObjects of all columns in an array.
3562 function FieldTypesArray()
3564 $arr = array();
3565 for ($i=0, $max=$this->_numOfFields; $i < $max; $i++)
3566 $arr[] = $this->FetchField($i);
3567 return $arr;
3571 * Return the fields array of the current row as an object for convenience.
3572 * The default case is lowercase field names.
3574 * @return the object with the properties set to the fields of the current row
3576 function FetchObj()
3578 $o = $this->FetchObject(false);
3579 return $o;
3583 * Return the fields array of the current row as an object for convenience.
3584 * The default case is uppercase.
3586 * @param $isupper to set the object property names to uppercase
3588 * @return the object with the properties set to the fields of the current row
3590 function FetchObject($isupper=true)
3592 if (empty($this->_obj)) {
3593 $this->_obj = new ADOFetchObj();
3594 $this->_names = array();
3595 for ($i=0; $i <$this->_numOfFields; $i++) {
3596 $f = $this->FetchField($i);
3597 $this->_names[] = $f->name;
3600 $i = 0;
3601 if (PHP_VERSION >= 5) $o = clone($this->_obj);
3602 else $o = $this->_obj;
3604 for ($i=0; $i <$this->_numOfFields; $i++) {
3605 $name = $this->_names[$i];
3606 if ($isupper) $n = strtoupper($name);
3607 else $n = $name;
3609 $o->$n = $this->Fields($name);
3611 return $o;
3615 * Return the fields array of the current row as an object for convenience.
3616 * The default is lower-case field names.
3618 * @return the object with the properties set to the fields of the current row,
3619 * or false if EOF
3621 * Fixed bug reported by tim@orotech.net
3623 function FetchNextObj()
3625 $o = $this->FetchNextObject(false);
3626 return $o;
3631 * Return the fields array of the current row as an object for convenience.
3632 * The default is upper case field names.
3634 * @param $isupper to set the object property names to uppercase
3636 * @return the object with the properties set to the fields of the current row,
3637 * or false if EOF
3639 * Fixed bug reported by tim@orotech.net
3641 function FetchNextObject($isupper=true)
3643 $o = false;
3644 if ($this->_numOfRows != 0 && !$this->EOF) {
3645 $o = $this->FetchObject($isupper);
3646 $this->_currentRow++;
3647 if ($this->_fetch()) return $o;
3649 $this->EOF = true;
3650 return $o;
3654 * Get the metatype of the column. This is used for formatting. This is because
3655 * many databases use different names for the same type, so we transform the original
3656 * type to our standardised version which uses 1 character codes:
3658 * @param t is the type passed in. Normally is ADOFieldObject->type.
3659 * @param len is the maximum length of that field. This is because we treat character
3660 * fields bigger than a certain size as a 'B' (blob).
3661 * @param fieldobj is the field object returned by the database driver. Can hold
3662 * additional info (eg. primary_key for mysql).
3664 * @return the general type of the data:
3665 * C for character < 250 chars
3666 * X for teXt (>= 250 chars)
3667 * B for Binary
3668 * N for numeric or floating point
3669 * D for date
3670 * T for timestamp
3671 * L for logical/Boolean
3672 * I for integer
3673 * R for autoincrement counter/integer
3677 function MetaType($t,$len=-1,$fieldobj=false)
3679 if (is_object($t)) {
3680 $fieldobj = $t;
3681 $t = $fieldobj->type;
3682 $len = $fieldobj->max_length;
3684 // changed in 2.32 to hashing instead of switch stmt for speed...
3685 static $typeMap = array(
3686 'VARCHAR' => 'C',
3687 'VARCHAR2' => 'C',
3688 'CHAR' => 'C',
3689 'C' => 'C',
3690 'STRING' => 'C',
3691 'NCHAR' => 'C',
3692 'NVARCHAR' => 'C',
3693 'VARYING' => 'C',
3694 'BPCHAR' => 'C',
3695 'CHARACTER' => 'C',
3696 'INTERVAL' => 'C', # Postgres
3697 'MACADDR' => 'C', # postgres
3698 'VAR_STRING' => 'C', # mysql
3700 'LONGCHAR' => 'X',
3701 'TEXT' => 'X',
3702 'NTEXT' => 'X',
3703 'M' => 'X',
3704 'X' => 'X',
3705 'CLOB' => 'X',
3706 'NCLOB' => 'X',
3707 'LVARCHAR' => 'X',
3709 'BLOB' => 'B',
3710 'IMAGE' => 'B',
3711 'BINARY' => 'B',
3712 'VARBINARY' => 'B',
3713 'LONGBINARY' => 'B',
3714 'B' => 'B',
3716 'YEAR' => 'D', // mysql
3717 'DATE' => 'D',
3718 'D' => 'D',
3720 'UNIQUEIDENTIFIER' => 'C', # MS SQL Server
3722 'SMALLDATETIME' => 'T',
3723 'TIME' => 'T',
3724 'TIMESTAMP' => 'T',
3725 'DATETIME' => 'T',
3726 'TIMESTAMPTZ' => 'T',
3727 'T' => 'T',
3728 'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
3730 'BOOL' => 'L',
3731 'BOOLEAN' => 'L',
3732 'BIT' => 'L',
3733 'L' => 'L',
3735 'COUNTER' => 'R',
3736 'R' => 'R',
3737 'SERIAL' => 'R', // ifx
3738 'INT IDENTITY' => 'R',
3740 'INT' => 'I',
3741 'INT2' => 'I',
3742 'INT4' => 'I',
3743 'INT8' => 'I',
3744 'INTEGER' => 'I',
3745 'INTEGER UNSIGNED' => 'I',
3746 'SHORT' => 'I',
3747 'TINYINT' => 'I',
3748 'SMALLINT' => 'I',
3749 'I' => 'I',
3751 'LONG' => 'N', // interbase is numeric, oci8 is blob
3752 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
3753 'DECIMAL' => 'N',
3754 'DEC' => 'N',
3755 'REAL' => 'N',
3756 'DOUBLE' => 'N',
3757 'DOUBLE PRECISION' => 'N',
3758 'SMALLFLOAT' => 'N',
3759 'FLOAT' => 'N',
3760 'NUMBER' => 'N',
3761 'NUM' => 'N',
3762 'NUMERIC' => 'N',
3763 'MONEY' => 'N',
3765 ## informix 9.2
3766 'SQLINT' => 'I',
3767 'SQLSERIAL' => 'I',
3768 'SQLSMINT' => 'I',
3769 'SQLSMFLOAT' => 'N',
3770 'SQLFLOAT' => 'N',
3771 'SQLMONEY' => 'N',
3772 'SQLDECIMAL' => 'N',
3773 'SQLDATE' => 'D',
3774 'SQLVCHAR' => 'C',
3775 'SQLCHAR' => 'C',
3776 'SQLDTIME' => 'T',
3777 'SQLINTERVAL' => 'N',
3778 'SQLBYTES' => 'B',
3779 'SQLTEXT' => 'X',
3780 ## informix 10
3781 "SQLINT8" => 'I8',
3782 "SQLSERIAL8" => 'I8',
3783 "SQLNCHAR" => 'C',
3784 "SQLNVCHAR" => 'C',
3785 "SQLLVARCHAR" => 'X',
3786 "SQLBOOL" => 'L'
3789 $tmap = false;
3790 $t = strtoupper($t);
3791 $tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
3792 switch ($tmap) {
3793 case 'C':
3795 // is the char field is too long, return as text field...
3796 if ($this->blobSize >= 0) {
3797 if ($len > $this->blobSize) return 'X';
3798 } else if ($len > 250) {
3799 return 'X';
3801 return 'C';
3803 case 'I':
3804 if (!empty($fieldobj->primary_key)) return 'R';
3805 return 'I';
3807 case false:
3808 return 'N';
3810 case 'B':
3811 if (isset($fieldobj->binary))
3812 return ($fieldobj->binary) ? 'B' : 'X';
3813 return 'B';
3815 case 'D':
3816 if (!empty($this->connection) && !empty($this->connection->datetime)) return 'T';
3817 return 'D';
3819 default:
3820 if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
3821 return $tmap;
3826 function _close() {}
3829 * set/returns the current recordset page when paginating
3831 function AbsolutePage($page=-1)
3833 if ($page != -1) $this->_currentPage = $page;
3834 return $this->_currentPage;
3838 * set/returns the status of the atFirstPage flag when paginating
3840 function AtFirstPage($status=false)
3842 if ($status != false) $this->_atFirstPage = $status;
3843 return $this->_atFirstPage;
3846 function LastPageNo($page = false)
3848 if ($page != false) $this->_lastPageNo = $page;
3849 return $this->_lastPageNo;
3853 * set/returns the status of the atLastPage flag when paginating
3855 function AtLastPage($status=false)
3857 if ($status != false) $this->_atLastPage = $status;
3858 return $this->_atLastPage;
3861 } // end class ADORecordSet
3863 //==============================================================================================
3864 // CLASS ADORecordSet_array
3865 //==============================================================================================
3868 * This class encapsulates the concept of a recordset created in memory
3869 * as an array. This is useful for the creation of cached recordsets.
3871 * Note that the constructor is different from the standard ADORecordSet
3874 class ADORecordSet_array extends ADORecordSet
3876 var $databaseType = 'array';
3878 var $_array; // holds the 2-dimensional data array
3879 var $_types; // the array of types of each column (C B I L M)
3880 var $_colnames; // names of each column in array
3881 var $_skiprow1; // skip 1st row because it holds column names
3882 var $_fieldobjects; // holds array of field objects
3883 var $canSeek = true;
3884 var $affectedrows = false;
3885 var $insertid = false;
3886 var $sql = '';
3887 var $compat = false;
3889 * Constructor
3892 function ADORecordSet_array($fakeid=1)
3894 global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
3896 // fetch() on EOF does not delete $this->fields
3897 $this->compat = !empty($ADODB_COMPAT_FETCH);
3898 $this->ADORecordSet($fakeid); // fake queryID
3899 $this->fetchMode = $ADODB_FETCH_MODE;
3902 function _transpose($addfieldnames=true)
3904 global $ADODB_INCLUDED_LIB;
3906 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
3907 $hdr = true;
3909 $fobjs = $addfieldnames ? $this->_fieldobjects : false;
3910 adodb_transpose($this->_array, $newarr, $hdr, $fobjs);
3911 //adodb_pr($newarr);
3913 $this->_skiprow1 = false;
3914 $this->_array = $newarr;
3915 $this->_colnames = $hdr;
3917 adodb_probetypes($newarr,$this->_types);
3919 $this->_fieldobjects = array();
3921 foreach($hdr as $k => $name) {
3922 $f = new ADOFieldObject();
3923 $f->name = $name;
3924 $f->type = $this->_types[$k];
3925 $f->max_length = -1;
3926 $this->_fieldobjects[] = $f;
3928 $this->fields = reset($this->_array);
3930 $this->_initrs();
3935 * Setup the array.
3937 * @param array is a 2-dimensional array holding the data.
3938 * The first row should hold the column names
3939 * unless paramter $colnames is used.
3940 * @param typearr holds an array of types. These are the same types
3941 * used in MetaTypes (C,B,L,I,N).
3942 * @param [colnames] array of column names. If set, then the first row of
3943 * $array should not hold the column names.
3945 function InitArray($array,$typearr,$colnames=false)
3947 $this->_array = $array;
3948 $this->_types = $typearr;
3949 if ($colnames) {
3950 $this->_skiprow1 = false;
3951 $this->_colnames = $colnames;
3952 } else {
3953 $this->_skiprow1 = true;
3954 $this->_colnames = $array[0];
3956 $this->Init();
3959 * Setup the Array and datatype file objects
3961 * @param array is a 2-dimensional array holding the data.
3962 * The first row should hold the column names
3963 * unless paramter $colnames is used.
3964 * @param fieldarr holds an array of ADOFieldObject's.
3966 function InitArrayFields(&$array,&$fieldarr)
3968 $this->_array = $array;
3969 $this->_skiprow1= false;
3970 if ($fieldarr) {
3971 $this->_fieldobjects = $fieldarr;
3973 $this->Init();
3976 function GetArray($nRows=-1)
3978 if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
3979 return $this->_array;
3980 } else {
3981 $arr = ADORecordSet::GetArray($nRows);
3982 return $arr;
3986 function _initrs()
3988 $this->_numOfRows = sizeof($this->_array);
3989 if ($this->_skiprow1) $this->_numOfRows -= 1;
3991 $this->_numOfFields =(isset($this->_fieldobjects)) ?
3992 sizeof($this->_fieldobjects):sizeof($this->_types);
3995 /* Use associative array to get fields array */
3996 function Fields($colname)
3998 $mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode;
4000 if ($mode & ADODB_FETCH_ASSOC) {
4001 if (!isset($this->fields[$colname]) && !is_null($this->fields[$colname])) $colname = strtolower($colname);
4002 return $this->fields[$colname];
4004 if (!$this->bind) {
4005 $this->bind = array();
4006 for ($i=0; $i < $this->_numOfFields; $i++) {
4007 $o = $this->FetchField($i);
4008 $this->bind[strtoupper($o->name)] = $i;
4011 return $this->fields[$this->bind[strtoupper($colname)]];
4014 function FetchField($fieldOffset = -1)
4016 if (isset($this->_fieldobjects)) {
4017 return $this->_fieldobjects[$fieldOffset];
4019 $o = new ADOFieldObject();
4020 $o->name = $this->_colnames[$fieldOffset];
4021 $o->type = $this->_types[$fieldOffset];
4022 $o->max_length = -1; // length not known
4024 return $o;
4027 function _seek($row)
4029 if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
4030 $this->_currentRow = $row;
4031 if ($this->_skiprow1) $row += 1;
4032 $this->fields = $this->_array[$row];
4033 return true;
4035 return false;
4038 function MoveNext()
4040 if (!$this->EOF) {
4041 $this->_currentRow++;
4043 $pos = $this->_currentRow;
4045 if ($this->_numOfRows <= $pos) {
4046 if (!$this->compat) $this->fields = false;
4047 } else {
4048 if ($this->_skiprow1) $pos += 1;
4049 $this->fields = $this->_array[$pos];
4050 return true;
4052 $this->EOF = true;
4055 return false;
4058 function _fetch()
4060 $pos = $this->_currentRow;
4062 if ($this->_numOfRows <= $pos) {
4063 if (!$this->compat) $this->fields = false;
4064 return false;
4066 if ($this->_skiprow1) $pos += 1;
4067 $this->fields = $this->_array[$pos];
4068 return true;
4071 function _close()
4073 return true;
4076 } // ADORecordSet_array
4078 //==============================================================================================
4079 // HELPER FUNCTIONS
4080 //==============================================================================================
4083 * Synonym for ADOLoadCode. Private function. Do not use.
4085 * @deprecated
4087 function ADOLoadDB($dbType)
4089 return ADOLoadCode($dbType);
4093 * Load the code for a specific database driver. Private function. Do not use.
4095 function ADOLoadCode($dbType)
4097 global $ADODB_LASTDB;
4099 if (!$dbType) return false;
4100 $db = strtolower($dbType);
4101 switch ($db) {
4102 case 'ado':
4103 if (PHP_VERSION >= 5) $db = 'ado5';
4104 $class = 'ado';
4105 break;
4106 case 'ifx':
4107 case 'maxsql': $class = $db = 'mysqlt'; break;
4108 case 'postgres':
4109 case 'postgres8':
4110 case 'pgsql': $class = $db = 'postgres7'; break;
4111 default:
4112 $class = $db; break;
4115 $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
4116 @include_once($file);
4117 $ADODB_LASTDB = $class;
4118 if (class_exists("ADODB_" . $class)) return $class;
4120 //ADOConnection::outp(adodb_pr(get_declared_classes(),true));
4121 if (!file_exists($file)) ADOConnection::outp("Missing file: $file");
4122 else ADOConnection::outp("Syntax error in file: $file");
4123 return false;
4127 * synonym for ADONewConnection for people like me who cannot remember the correct name
4129 function NewADOConnection($db='')
4131 $tmp = ADONewConnection($db);
4132 return $tmp;
4136 * Instantiate a new Connection class for a specific database driver.
4138 * @param [db] is the database Connection object to create. If undefined,
4139 * use the last database driver that was loaded by ADOLoadCode().
4141 * @return the freshly created instance of the Connection class.
4143 function ADONewConnection($db='')
4145 GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
4147 if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
4148 $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
4149 $false = false;
4150 if (($at = strpos($db,'://')) !== FALSE) {
4151 $origdsn = $db;
4152 $fakedsn = 'fake'.substr($origdsn,$at);
4153 if (($at2 = strpos($origdsn,'@/')) !== FALSE) {
4154 // special handling of oracle, which might not have host
4155 $fakedsn = str_replace('@/','@adodb-fakehost/',$fakedsn);
4158 if ((strpos($origdsn, 'sqlite')) !== FALSE && stripos($origdsn, '%2F') === FALSE) {
4159 // special handling for SQLite, it only might have the path to the database file.
4160 // If you try to connect to a SQLite database using a dsn like 'sqlite:///path/to/database', the 'parse_url' php function
4161 // will throw you an exception with a message such as "unable to parse url"
4162 list($scheme, $path) = explode('://', $origdsn);
4163 $dsna['scheme'] = $scheme;
4164 if ($qmark = strpos($path,'?')) {
4165 $dsn['query'] = substr($path,$qmark+1);
4166 $path = substr($path,0,$qmark);
4168 $dsna['path'] = '/' . urlencode($path);
4169 } else
4170 $dsna = @parse_url($fakedsn);
4172 if (!$dsna) {
4173 return $false;
4175 $dsna['scheme'] = substr($origdsn,0,$at);
4176 if ($at2 !== FALSE) {
4177 $dsna['host'] = '';
4180 if (strncmp($origdsn,'pdo',3) == 0) {
4181 $sch = explode('_',$dsna['scheme']);
4182 if (sizeof($sch)>1) {
4184 $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
4185 if ($sch[1] == 'sqlite')
4186 $dsna['host'] = rawurlencode($sch[1].':'.rawurldecode($dsna['host']));
4187 else
4188 $dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host']));
4189 $dsna['scheme'] = 'pdo';
4193 $db = @$dsna['scheme'];
4194 if (!$db) return $false;
4195 $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
4196 $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : '';
4197 $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : '';
4198 $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial /
4200 if (isset($dsna['query'])) {
4201 $opt1 = explode('&',$dsna['query']);
4202 foreach($opt1 as $k => $v) {
4203 $arr = explode('=',$v);
4204 $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1;
4206 } else $opt = array();
4209 * phptype: Database backend used in PHP (mysql, odbc etc.)
4210 * dbsyntax: Database used with regards to SQL syntax etc.
4211 * protocol: Communication protocol to use (tcp, unix etc.)
4212 * hostspec: Host specification (hostname[:port])
4213 * database: Database to use on the DBMS server
4214 * username: User name for login
4215 * password: Password for login
4217 if (!empty($ADODB_NEWCONNECTION)) {
4218 $obj = $ADODB_NEWCONNECTION($db);
4222 if(empty($obj)) {
4224 if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
4225 if (empty($db)) $db = $ADODB_LASTDB;
4227 if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
4229 if (!$db) {
4230 if (isset($origdsn)) $db = $origdsn;
4231 if ($errorfn) {
4232 // raise an error
4233 $ignore = false;
4234 $errorfn('ADONewConnection', 'ADONewConnection', -998,
4235 "could not load the database driver for '$db'",
4236 $db,false,$ignore);
4237 } else
4238 ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
4240 return $false;
4243 $cls = 'ADODB_'.$db;
4244 if (!class_exists($cls)) {
4245 adodb_backtrace();
4246 return $false;
4249 $obj = new $cls();
4252 # constructor should not fail
4253 if ($obj) {
4254 if ($errorfn) $obj->raiseErrorFn = $errorfn;
4255 if (isset($dsna)) {
4256 if (isset($dsna['port'])) $obj->port = $dsna['port'];
4257 foreach($opt as $k => $v) {
4258 switch(strtolower($k)) {
4259 case 'new':
4260 $nconnect = true; $persist = true; break;
4261 case 'persist':
4262 case 'persistent': $persist = $v; break;
4263 case 'debug': $obj->debug = (integer) $v; break;
4264 #ibase
4265 case 'role': $obj->role = $v; break;
4266 case 'dialect': $obj->dialect = (integer) $v; break;
4267 case 'charset': $obj->charset = $v; $obj->charSet=$v; break;
4268 case 'buffers': $obj->buffers = $v; break;
4269 case 'fetchmode': $obj->SetFetchMode($v); break;
4270 #ado
4271 case 'charpage': $obj->charPage = $v; break;
4272 #mysql, mysqli
4273 case 'clientflags': $obj->clientFlags = $v; break;
4274 #mysql, mysqli, postgres
4275 case 'port': $obj->port = $v; break;
4276 #mysqli
4277 case 'socket': $obj->socket = $v; break;
4278 #oci8
4279 case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break;
4280 case 'cachesecs': $obj->cacheSecs = $v; break;
4281 case 'memcache':
4282 $varr = explode(':',$v);
4283 $vlen = sizeof($varr);
4284 if ($vlen == 0) break;
4285 $obj->memCache = true;
4286 $obj->memCacheHost = explode(',',$varr[0]);
4287 if ($vlen == 1) break;
4288 $obj->memCachePort = $varr[1];
4289 if ($vlen == 2) break;
4290 $obj->memCacheCompress = $varr[2] ? true : false;
4291 break;
4294 if (empty($persist))
4295 $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
4296 else if (empty($nconnect))
4297 $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
4298 else
4299 $ok = $obj->NConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
4301 if (!$ok) return $false;
4304 return $obj;
4309 // $perf == true means called by NewPerfMonitor(), otherwise for data dictionary
4310 function _adodb_getdriver($provider,$drivername,$perf=false)
4312 switch ($provider) {
4313 case 'odbtp': if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6);
4314 case 'odbc' : if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5);
4315 case 'ado' : if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4);
4316 case 'native': break;
4317 default:
4318 return $provider;
4321 switch($drivername) {
4322 case 'mysqlt':
4323 case 'mysqli':
4324 $drivername='mysql';
4325 break;
4326 case 'postgres7':
4327 case 'postgres8':
4328 $drivername = 'postgres';
4329 break;
4330 case 'firebird15': $drivername = 'firebird'; break;
4331 case 'oracle': $drivername = 'oci8'; break;
4332 case 'access': if ($perf) $drivername = ''; break;
4333 case 'db2' : break;
4334 case 'sapdb' : break;
4335 default:
4336 $drivername = 'generic';
4337 break;
4339 return $drivername;
4342 function NewPerfMonitor(&$conn)
4344 $false = false;
4345 $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
4346 if (!$drivername || $drivername == 'generic') return $false;
4347 include_once(ADODB_DIR.'/adodb-perf.inc.php');
4348 @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
4349 $class = "Perf_$drivername";
4350 if (!class_exists($class)) return $false;
4351 $perf = new $class($conn);
4353 return $perf;
4356 function NewDataDictionary(&$conn,$drivername=false)
4358 $false = false;
4359 if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
4361 include_once(ADODB_DIR.'/adodb-lib.inc.php');
4362 include_once(ADODB_DIR.'/adodb-datadict.inc.php');
4363 $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
4365 if (!file_exists($path)) {
4366 ADOConnection::outp("Dictionary driver '$path' not available");
4367 return $false;
4369 include_once($path);
4370 $class = "ADODB2_$drivername";
4371 $dict = new $class();
4372 $dict->dataProvider = $conn->dataProvider;
4373 $dict->connection = $conn;
4374 $dict->upperName = strtoupper($drivername);
4375 $dict->quote = $conn->nameQuote;
4376 if (!empty($conn->_connectionID))
4377 $dict->serverInfo = $conn->ServerInfo();
4379 return $dict;
4385 Perform a print_r, with pre tags for better formatting.
4387 function adodb_pr($var,$as_string=false)
4389 if ($as_string) ob_start();
4391 if (isset($_SERVER['HTTP_USER_AGENT'])) {
4392 echo " <pre>\n";print_r($var);echo "</pre>\n";
4393 } else
4394 print_r($var);
4396 if ($as_string) {
4397 $s = ob_get_contents();
4398 ob_end_clean();
4399 return $s;
4404 Perform a stack-crawl and pretty print it.
4406 @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
4407 @param levels Number of levels to display
4409 function adodb_backtrace($printOrArr=true,$levels=9999,$ishtml=null)
4411 global $ADODB_INCLUDED_LIB;
4412 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
4413 return _adodb_backtrace($printOrArr,$levels,0,$ishtml);