3 * Set tabs to 4 for best viewing.
\r
5 * Latest version is available at http://php.weblogs.com/adodb
\r
7 * This is the main include file for ADOdb.
\r
8 * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
\r
10 * The ADOdb files are formatted so that doxygen can be used to generate documentation.
\r
11 * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
\r
17 @version V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved.
\r
19 Released under both BSD license and Lesser GPL library license. You can choose which license
\r
22 PHP's database access functions are not standardised. This creates a need for a database
\r
23 class library to hide the differences between the different database API's (encapsulate
\r
24 the differences) so we can easily switch databases.
\r
26 We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
\r
27 Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
\r
28 ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
\r
29 other databases via ODBC.
\r
31 Latest Download at http://php.weblogs.com/adodb<br>
\r
32 Manual is at http://php.weblogs.com/adodb_manual
\r
36 if (!defined('_ADODB_LAYER')) {
\r
37 define('_ADODB_LAYER',1);
\r
39 //==============================================================================================
\r
40 // CONSTANT DEFINITIONS
\r
41 //==============================================================================================
\r
45 * Set ADODB_DIR to the directory where this file resides...
\r
46 * This constant was formerly called $ADODB_RootPath
\r
48 if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
\r
50 //==============================================================================================
\r
52 //==============================================================================================
\r
55 $ADODB_vers, // database version
\r
56 $ADODB_COUNTRECS, // count number of records returned - slows down query
\r
57 $ADODB_CACHE_DIR, // directory to cache recordsets
\r
58 $ADODB_EXTENSION, // ADODB extension installed
\r
59 $ADODB_COMPAT_PATCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
\r
60 $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
\r
62 //==============================================================================================
\r
64 //==============================================================================================
\r
66 $ADODB_EXTENSION = defined('ADODB_EXTENSION');
\r
67 if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
\r
69 define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
\r
71 // allow [ ] @ ` " and . in table names
\r
72 define('ADODB_TABLE_REGEX','([]0-9a-z_\"\`\.\@\[-]*)');
\r
74 // prefetching used by oracle
\r
75 if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
\r
79 Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
\r
80 This currently works only with mssql, odbc, oci8po and ibase derived drivers.
\r
82 0 = assoc lowercase field names. $rs->fields['orderid']
\r
83 1 = assoc uppercase field names. $rs->fields['ORDERID']
\r
84 2 = use native-case field names. $rs->fields['OrderID']
\r
87 define('ADODB_FETCH_DEFAULT',0);
\r
88 define('ADODB_FETCH_NUM',1);
\r
89 define('ADODB_FETCH_ASSOC',2);
\r
90 define('ADODB_FETCH_BOTH',3);
\r
92 if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
\r
94 if (strnatcmp(PHP_VERSION,'4.3.0')>=0) {
\r
95 define('ADODB_PHPVER',0x4300);
\r
96 } else if (strnatcmp(PHP_VERSION,'4.2.0')>=0) {
\r
97 define('ADODB_PHPVER',0x4200);
\r
98 } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
\r
99 define('ADODB_PHPVER',0x4050);
\r
101 define('ADODB_PHPVER',0x4000);
\r
105 //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
\r
109 Accepts $src and $dest arrays, replacing string $data
\r
111 function ADODB_str_replace($src, $dest, $data)
\r
113 if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
\r
117 while ($s !== false) {
\r
118 $data = str_replace($s,$d,$data);
\r
125 function ADODB_Setup()
\r
128 $ADODB_vers, // database version
\r
129 $ADODB_COUNTRECS, // count number of records returned - slows down query
\r
130 $ADODB_CACHE_DIR, // directory to cache recordsets
\r
133 $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
\r
135 if (!isset($ADODB_CACHE_DIR)) {
\r
136 $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
\r
138 // do not accept url based paths, eg. http:/ or ftp:/
\r
139 if (strpos($ADODB_CACHE_DIR,'://') !== false)
\r
140 die("Illegal path http:// or ftp://");
\r
144 // Initialize random number generator for randomizing cache flushes
\r
145 srand(((double)microtime())*1000000);
\r
148 * ADODB version as a string.
\r
150 $ADODB_vers = 'V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
\r
153 * Determines whether recordset->RecordCount() is used.
\r
154 * Set to false for highest performance -- RecordCount() will always return -1 then
\r
155 * for databases that provide "virtual" recordcounts...
\r
157 if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
\r
161 //==============================================================================================
\r
162 // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
\r
163 //==============================================================================================
\r
167 //==============================================================================================
\r
168 // CLASS ADOFieldObject
\r
169 //==============================================================================================
\r
171 * Helper class for FetchFields -- holds info on a column
\r
173 class ADOFieldObject {
\r
178 // additional fields by dannym... (danny_milo@yahoo.com)
\r
179 var $not_null = false;
\r
180 // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
\r
181 // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
\r
183 var $has_default = false; // this one I have done only in mysql and postgres for now ...
\r
184 // others to come (dannym)
\r
185 var $default_value; // default, if any, and supported. Check has_default first.
\r
190 function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
\r
192 //print "Errorno ($fn errno=$errno m=$errmsg) ";
\r
193 $thisConnection->_transOK = false;
\r
194 if ($thisConnection->_oldRaiseFn) {
\r
195 $fn = $thisConnection->_oldRaiseFn;
\r
196 $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
\r
200 //==============================================================================================
\r
201 // CLASS ADOConnection
\r
202 //==============================================================================================
\r
205 * Connection object. For connecting to databases, and executing queries.
\r
207 class ADOConnection {
\r
211 var $dataProvider = 'native';
\r
212 var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
\r
213 var $database = ''; /// Name of database to be used.
\r
214 var $host = ''; /// The hostname of the database server
\r
215 var $user = ''; /// The username which is used to connect to the database server.
\r
216 var $password = ''; /// Password for the username. For security, we no longer store it.
\r
217 var $debug = false; /// if set to true will output sql statements
\r
218 var $maxblobsize = 256000; /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro
\r
219 var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
\r
220 var $substr = 'substr'; /// substring operator
\r
221 var $length = 'length'; /// string length operator
\r
222 var $random = 'rand()'; /// random function
\r
223 var $upperCase = false; /// uppercase function
\r
224 var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
\r
225 var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
\r
226 var $true = '1'; /// string that represents TRUE for a database
\r
227 var $false = '0'; /// string that represents FALSE for a database
\r
228 var $replaceQuote = "\\'"; /// string to use to replace quotes
\r
229 var $nameQuote = '"'; /// string to use to quote identifiers and names
\r
230 var $charSet=false; /// character set to use - only for interbase
\r
231 var $metaDatabasesSQL = '';
\r
232 var $metaTablesSQL = '';
\r
233 var $uniqueOrderBy = false; /// All order by columns have to be unique
\r
234 var $emptyDate = ' ';
\r
235 var $emptyTimeStamp = ' ';
\r
236 var $lastInsID = false;
\r
238 var $hasInsertID = false; /// supports autoincrement ID?
\r
239 var $hasAffectedRows = false; /// supports affected rows for update/delete?
\r
240 var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
\r
241 var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
\r
242 var $readOnly = false; /// this is a readonly database - used by phpLens
\r
243 var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
\r
244 var $hasGenID = false; /// can generate sequences using GenID();
\r
245 var $hasTransactions = true; /// has transactions
\r
247 var $genID = 0; /// sequence id used by GenID();
\r
248 var $raiseErrorFn = false; /// error function to call
\r
249 var $isoDates = false; /// accepts dates in ISO format
\r
250 var $cacheSecs = 3600; /// cache for 1 hour
\r
251 var $sysDate = false; /// name of function that returns the current date
\r
252 var $sysTimeStamp = false; /// name of function that returns the current timestamp
\r
253 var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
\r
255 var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
\r
256 var $numCacheHits = 0;
\r
257 var $numCacheMisses = 0;
\r
258 var $pageExecuteCountRows = true;
\r
259 var $uniqueSort = false; /// indicates that all fields in order by must be unique
\r
260 var $leftOuter = false; /// operator to use for left outer join in WHERE clause
\r
261 var $rightOuter = false; /// operator to use for right outer join in WHERE clause
\r
262 var $ansiOuter = false; /// whether ansi outer join syntax supported
\r
263 var $autoRollback = false; // autoRollback on PConnect().
\r
264 var $poorAffectedRows = false; // affectedRows not working or unreliable
\r
266 var $fnExecute = false;
\r
267 var $fnCacheExecute = false;
\r
268 var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
\r
269 var $rsPrefix = "ADORecordSet_";
\r
271 var $autoCommit = true; /// do not modify this yourself - actually private
\r
272 var $transOff = 0; /// temporarily disable transactions
\r
273 var $transCnt = 0; /// count of nested transactions
\r
275 var $fetchMode=false;
\r
279 var $_oldRaiseFn = false;
\r
280 var $_transOK = null;
\r
281 var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
\r
282 var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
\r
283 /// then returned by the errorMsg() function
\r
284 var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
\r
285 var $_queryID = false; /// This variable keeps the last created result link identifier
\r
287 var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
\r
288 var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
\r
289 var $_evalAll = false;
\r
290 var $_affected = false;
\r
291 var $_logsql = false;
\r
298 function ADOConnection()
\r
300 die('Virtual Class -- cannot instantiate');
\r
304 Get server version info...
\r
306 @returns An array with 2 elements: $arr['string'] is the description string,
\r
307 and $arr[version] is the version (also a string).
\r
309 function ServerInfo()
\r
311 return array('description' => '', 'version' => '');
\r
314 function _findvers($str)
\r
316 if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
\r
321 * All error messages go through this bottleneck function.
\r
322 * You can define your own handler by defining the function name in ADODB_OUTP.
\r
324 function outp($msg,$newline=true)
\r
326 global $HTTP_SERVER_VARS,$ADODB_FLUSH,$ADODB_OUTP;
\r
328 if (defined('ADODB_OUTP')) {
\r
330 $fn($msg,$newline);
\r
332 } else if (isset($ADODB_OUTP)) {
\r
334 $fn($msg,$newline);
\r
338 if ($newline) $msg .= "<br>\n";
\r
340 if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg;
\r
341 else echo strip_tags($msg);
\r
342 if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // dp not flush if output buffering enabled - useless - thx to Jesse Mullan
\r
348 $rs =& $this->Execute("select $this->sysTimeStamp");
\r
349 if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
\r
355 * Connect to database
\r
357 * @param [argHostname] Host to connect to
\r
358 * @param [argUsername] Userid to login
\r
359 * @param [argPassword] Associated password
\r
360 * @param [argDatabaseName] database
\r
361 * @param [forceNew] force new connection
\r
363 * @return true or false
\r
365 function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
\r
367 if ($argHostname != "") $this->host = $argHostname;
\r
368 if ($argUsername != "") $this->user = $argUsername;
\r
369 if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
\r
370 if ($argDatabaseName != "") $this->database = $argDatabaseName;
\r
372 $this->_isPersistentConnection = false;
\r
373 if ($fn = $this->raiseErrorFn) {
\r
375 if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
\r
377 if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
\r
379 $err = $this->ErrorMsg();
\r
380 if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
\r
381 $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
\r
384 if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
\r
386 if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
\r
389 if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());
\r
393 function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
\r
395 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
\r
400 * Always force a new connection to database - currently only works with oracle
\r
402 * @param [argHostname] Host to connect to
\r
403 * @param [argUsername] Userid to login
\r
404 * @param [argPassword] Associated password
\r
405 * @param [argDatabaseName] database
\r
407 * @return true or false
\r
409 function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
\r
411 return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
\r
415 * Establish persistent connect to database
\r
417 * @param [argHostname] Host to connect to
\r
418 * @param [argUsername] Userid to login
\r
419 * @param [argPassword] Associated password
\r
420 * @param [argDatabaseName] database
\r
422 * @return return true or false
\r
424 function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
\r
426 if (defined('ADODB_NEVER_PERSIST'))
\r
427 return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
\r
429 if ($argHostname != "") $this->host = $argHostname;
\r
430 if ($argUsername != "") $this->user = $argUsername;
\r
431 if ($argPassword != "") $this->password = $argPassword;
\r
432 if ($argDatabaseName != "") $this->database = $argDatabaseName;
\r
434 $this->_isPersistentConnection = true;
\r
436 if ($fn = $this->raiseErrorFn) {
\r
437 if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
\r
438 $err = $this->ErrorMsg();
\r
439 if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
\r
440 $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
\r
442 if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
\r
444 if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());
\r
448 // Format date column in sql string given an input format that understands Y M D
\r
449 function SQLDate($fmt, $col=false)
\r
451 if (!$col) $col = $this->sysDate;
\r
452 return $col; // child class implement
\r
456 * Should prepare the sql statement and return the stmt resource.
\r
457 * For databases that do not support this, we return the $sql. To ensure
\r
458 * compatibility with databases that do not support prepare:
\r
460 * $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
\r
461 * $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
\r
462 * $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
\r
464 * @param sql SQL to send to database
\r
466 * @return return FALSE, or the prepared statement, or the original sql if
\r
467 * if the database does not support prepare.
\r
470 function Prepare($sql)
\r
476 * Some databases, eg. mssql require a different function for preparing
\r
477 * stored procedures. So we cannot use Prepare().
\r
479 * Should prepare the stored procedure and return the stmt resource.
\r
480 * For databases that do not support this, we return the $sql. To ensure
\r
481 * compatibility with databases that do not support prepare:
\r
483 * @param sql SQL to send to database
\r
485 * @return return FALSE, or the prepared statement, or the original sql if
\r
486 * if the database does not support prepare.
\r
489 function PrepareSP($sql,$param=true)
\r
491 return $this->Prepare($sql,$param);
\r
499 return $this->qstr($s,false);
\r
503 Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
\r
505 function QMagic($s)
\r
507 return $this->qstr($s,get_magic_quotes_gpc());
\r
512 $s = $this->qstr($s,false);
\r
516 * PEAR DB Compat - do not use internally.
\r
518 function ErrorNative()
\r
520 return $this->ErrorNo();
\r
525 * PEAR DB Compat - do not use internally.
\r
527 function nextId($seq_name)
\r
529 return $this->GenID($seq_name);
\r
533 * Lock a row, will escalate and lock the table if row locking not supported
\r
534 * will normally free the lock at the end of the transaction
\r
536 * @param $table name of table to lock
\r
537 * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
\r
539 function RowLock($table,$where)
\r
544 function CommitLock($table)
\r
546 return $this->CommitTrans();
\r
549 function RollbackLock($table)
\r
551 return $this->RollbackTrans();
\r
555 * PEAR DB Compat - do not use internally.
\r
557 * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
\r
558 * for easy porting :-)
\r
560 * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
\r
561 * @returns The previous fetch mode
\r
563 function SetFetchMode($mode)
\r
565 $old = $this->fetchMode;
\r
566 $this->fetchMode = $mode;
\r
568 if ($old === false) {
\r
569 global $ADODB_FETCH_MODE;
\r
570 return $ADODB_FETCH_MODE;
\r
577 * PEAR DB Compat - do not use internally.
\r
579 function &Query($sql, $inputarr=false)
\r
581 $rs = &$this->Execute($sql, $inputarr);
\r
582 if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
\r
588 * PEAR DB Compat - do not use internally
\r
590 function &LimitQuery($sql, $offset, $count, $params=false)
\r
592 $rs = &$this->SelectLimit($sql, $count, $offset, $params);
\r
593 if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
\r
599 * PEAR DB Compat - do not use internally
\r
601 function Disconnect()
\r
603 return $this->Close();
\r
607 Returns placeholder for parameter, eg.
\r
610 will return ':a' for Oracle, and '?' for most other databases...
\r
612 For databases that require positioned params, eg $1, $2, $3 for postgresql,
\r
613 pass in Param(false) before setting the first parameter.
\r
615 function Param($name)
\r
621 InParameter and OutParameter are self-documenting versions of Parameter().
\r
623 function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
\r
625 return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
\r
630 function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
\r
632 return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
\r
638 $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
\r
639 $db->Parameter($stmt,$id,'myid');
\r
640 $db->Parameter($stmt,$group,'group',64);
\r
643 @param $stmt Statement returned by Prepare() or PrepareSP().
\r
644 @param $var PHP variable to bind to
\r
645 @param $name Name of stored procedure variable name to bind to.
\r
646 @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
\r
647 @param [$maxLen] Holds an maximum length of the variable.
\r
648 @param [$type] The data type of $var. Legal values depend on driver.
\r
651 function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
\r
657 Improved method of initiating a transaction. Used together with CompleteTrans().
\r
658 Advantages include:
\r
660 a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
\r
661 Only the outermost block is treated as a transaction.<br>
\r
662 b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
\r
663 c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
\r
664 are disabled, making it backward compatible.
\r
666 function StartTrans($errfn = 'ADODB_TransMonitor')
\r
668 if ($this->transOff > 0) {
\r
669 $this->transOff += 1;
\r
673 $this->_oldRaiseFn = $this->raiseErrorFn;
\r
674 $this->raiseErrorFn = $errfn;
\r
675 $this->_transOK = true;
\r
677 if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
\r
678 $this->BeginTrans();
\r
679 $this->transOff = 1;
\r
683 Used together with StartTrans() to end a transaction. Monitors connection
\r
684 for sql errors, and will commit or rollback as appropriate.
\r
686 @autoComplete if true, monitor sql errors and commit and rollback as appropriate,
\r
687 and if set to false force rollback even if no SQL error detected.
\r
688 @returns true on commit, false on rollback.
\r
690 function CompleteTrans($autoComplete = true)
\r
692 if ($this->transOff > 1) {
\r
693 $this->transOff -= 1;
\r
696 $this->raiseErrorFn = $this->_oldRaiseFn;
\r
698 $this->transOff = 0;
\r
699 if ($this->_transOK && $autoComplete) {
\r
700 if (!$this->CommitTrans()) {
\r
701 $this->_transOK = false;
\r
702 if ($this->debug) ADOConnection::outp("Smart Commit failed");
\r
704 if ($this->debug) ADOConnection::outp("Smart Commit occurred");
\r
706 $this->RollbackTrans();
\r
707 if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
\r
710 return $this->_transOK;
\r
714 At the end of a StartTrans/CompleteTrans block, perform a rollback.
\r
716 function FailTrans()
\r
719 if ($this->transOff == 0) {
\r
720 ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
\r
722 ADOConnection::outp("FailTrans was called");
\r
725 $this->_transOK = false;
\r
729 Check if transaction has failed, only for Smart Transactions.
\r
731 function HasFailedTrans()
\r
733 if ($this->transOff > 0) return $this->_transOK == false;
\r
740 * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
\r
741 * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
\r
742 * @return RecordSet or false
\r
744 function &Execute($sql,$inputarr=false)
\r
746 if ($this->fnExecute) {
\r
747 $fn = $this->fnExecute;
\r
748 $ret =& $fn($this,$sql,$inputarr);
\r
749 if (isset($ret)) return $ret;
\r
751 if ($inputarr && is_array($inputarr)) {
\r
752 $element0 = reset($inputarr);
\r
753 # is_object check is because oci8 descriptors can be passed in
\r
754 $array_2d = is_array($element0) && !is_object(reset($element0));
\r
756 if (!is_array($sql) && !$this->_bindInputArray) {
\r
757 $sqlarr = explode('?',$sql);
\r
759 if (!$array_2d) $inputarr = array($inputarr);
\r
760 foreach($inputarr as $arr) {
\r
762 foreach($arr as $v) {
\r
763 $sql .= $sqlarr[$i];
\r
764 // from Ron Baldwin <ron.baldwin@sourceprose.com>
\r
765 // Only quote string types
\r
766 if (gettype($v) == 'string')
\r
767 $sql .= $this->qstr($v);
\r
768 else if ($v === null)
\r
774 $sql .= $sqlarr[$i];
\r
776 if ($i+1 != sizeof($sqlarr))
\r
777 ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
\r
779 $ret =& $this->_Execute($sql,false);
\r
780 if (!$ret) return $ret;
\r
784 $stmt = $this->Prepare($sql);
\r
785 foreach($inputarr as $arr) {
\r
786 $ret =& $this->_Execute($stmt,$arr);
\r
787 if (!$ret) return $ret;
\r
790 $ret =& $this->_Execute($sql,$inputarr);
\r
793 $ret =& $this->_Execute($sql,false);
\r
799 function& _Execute($sql,$inputarr=false)
\r
802 if ($this->debug) {
\r
803 global $HTTP_SERVER_VARS;
\r
807 foreach($inputarr as $kk=>$vv) {
\r
808 if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
\r
809 $ss .= "($kk=>'$vv') ";
\r
813 $sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql);
\r
815 // check if running from browser or command-line
\r
816 $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
\r
819 if ($this->debug === -1)
\r
820 ADOConnection::outp( "<br>\n($this->databaseType): ".htmlspecialchars($sqlTxt)." <code>$ss</code>\n<br>\n",false);
\r
822 ADOConnection::outp( "<hr>\n($this->databaseType): ".htmlspecialchars($sqlTxt)." <code>$ss</code>\n<hr>\n",false);
\r
824 ADOConnection::outp("-----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false);
\r
826 $this->_queryID = $this->_query($sql,$inputarr);
\r
828 Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
\r
829 because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion
\r
831 if ($this->databaseType == 'mssql') {
\r
832 // ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6
\r
833 if($emsg = $this->ErrorMsg()) {
\r
834 if ($err = $this->ErrorNo()) ADOConnection::outp($err.': '.$emsg);
\r
836 } else if (!$this->_queryID) {
\r
837 ADOConnection::outp($this->ErrorNo() .': '. $this->ErrorMsg());
\r
840 //****************************
\r
841 // non-debug version of query
\r
842 //****************************
\r
844 $this->_queryID =@$this->_query($sql,$inputarr);
\r
847 /************************
\r
848 // OK, query executed
\r
849 *************************/
\r
851 if ($this->_queryID === false) {
\r
852 // error handling if query fails
\r
853 if ($this->debug == 99) adodb_backtrace(true,5);
\r
854 $fn = $this->raiseErrorFn;
\r
856 $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
\r
863 if ($this->_queryID === true) {
\r
864 // return simplified empty recordset for inserts/updates/deletes with lower overhead
\r
865 $rs =& new ADORecordSet_empty();
\r
869 // return real recordset from select statement
\r
870 $rsclass = $this->rsPrefix.$this->databaseType;
\r
871 $rs =& new $rsclass($this->_queryID,$this->fetchMode);
\r
872 $rs->connection = &$this; // Pablo suggestion
\r
874 if (is_array($sql)) $rs->sql = $sql[0];
\r
875 else $rs->sql = $sql;
\r
876 if ($rs->_numOfRows <= 0) {
\r
877 global $ADODB_COUNTRECS;
\r
879 if ($ADODB_COUNTRECS) {
\r
881 $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
\r
882 $rs->_queryID = $this->_queryID;
\r
884 $rs->_numOfRows = 0;
\r
890 function CreateSequence($seqname='adodbseq',$startID=1)
\r
892 if (empty($this->_genSeqSQL)) return false;
\r
893 return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
\r
896 function DropSequence($seqname)
\r
898 if (empty($this->_dropSeqSQL)) return false;
\r
899 return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
\r
903 * Generates a sequence id and stores it in $this->genID;
\r
904 * GenID is only available if $this->hasGenID = true;
\r
906 * @param seqname name of sequence to use
\r
907 * @param startID if sequence does not exist, start at this ID
\r
908 * @return 0 if not supported, otherwise a sequence id
\r
910 function GenID($seqname='adodbseq',$startID=1)
\r
912 if (!$this->hasGenID) {
\r
913 return 0; // formerly returns false pre 1.60
\r
916 $getnext = sprintf($this->_genIDSQL,$seqname);
\r
918 $holdtransOK = $this->_transOK;
\r
919 $rs = @$this->Execute($getnext);
\r
921 $this->_transOK = $holdtransOK; //if the status was ok before reset
\r
922 $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
\r
923 $rs = $this->Execute($getnext);
\r
925 if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
\r
926 else $this->genID = 0; // false
\r
928 if ($rs) $rs->Close();
\r
930 return $this->genID;
\r
934 * @return the last inserted ID. Not all databases support this.
\r
936 function Insert_ID()
\r
938 if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
\r
939 if ($this->hasInsertID) return $this->_insertid();
\r
940 if ($this->debug) {
\r
941 ADOConnection::outp( '<p>Insert_ID error</p>');
\r
949 * Portable Insert ID. Pablo Roca <pabloroca@mvps.org>
\r
951 * @return the last inserted ID. All databases support this. But aware possible
\r
952 * problems in multiuser environments. Heavy test this before deploying.
\r
954 function PO_Insert_ID($table="", $id="")
\r
956 if ($this->hasInsertID){
\r
957 return $this->Insert_ID();
\r
959 return $this->GetOne("SELECT MAX($id) FROM $table");
\r
964 * @return # rows affected by UPDATE/DELETE
\r
966 function Affected_Rows()
\r
968 if ($this->hasAffectedRows) {
\r
969 if ($this->fnExecute === 'adodb_log_sql') {
\r
970 if ($this->_logsql && $this->_affected !== false) return $this->_affected;
\r
972 $val = $this->_affectedrows();
\r
973 return ($val < 0) ? false : $val;
\r
976 if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
\r
982 * @return the last error message
\r
984 function ErrorMsg()
\r
986 return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
\r
991 * @return the last error number. Normally 0 means no error.
\r
993 function ErrorNo()
\r
995 return ($this->_errorMsg) ? -1 : 0;
\r
998 function MetaError($err=false)
\r
1000 include_once(ADODB_DIR."/adodb-error.inc.php");
\r
1001 if ($err === false) $err = $this->ErrorNo();
\r
1002 return adodb_error($this->dataProvider,$this->databaseType,$err);
\r
1005 function MetaErrorMsg($errno)
\r
1007 include_once(ADODB_DIR."/adodb-error.inc.php");
\r
1008 return adodb_errormsg($errno);
\r
1012 * @returns an array with the primary key columns in it.
\r
1014 function MetaPrimaryKeys($table, $owner=false)
\r
1016 // owner not used in base class - see oci8
\r
1018 $objs =& $this->MetaColumns($table);
\r
1020 foreach($objs as $v) {
\r
1021 if (!empty($v->primary_key))
\r
1025 if (sizeof($p)) return $p;
\r
1026 if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
\r
1027 return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
\r
1032 * @returns assoc array where keys are tables, and values are foreign keys
\r
1034 function MetaForeignKeys($table, $owner=false, $upper=false)
\r
1039 * Choose a database to connect to. Many databases do not support this.
\r
1041 * @param dbName is the name of the database to select
\r
1042 * @return true or false
\r
1044 function SelectDB($dbName)
\r
1049 * Will select, getting rows from $offset (1-based), for $nrows.
\r
1050 * This simulates the MySQL "select * from table limit $offset,$nrows" , and
\r
1051 * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
\r
1052 * MySQL and PostgreSQL parameter ordering is the opposite of the other.
\r
1054 * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
\r
1055 * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
\r
1057 * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
\r
1058 * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
\r
1061 * @param [offset] is the row to start calculations from (1-based)
\r
1062 * @param [nrows] is the number of rows to get
\r
1063 * @param [inputarr] array of bind variables
\r
1064 * @param [secs2cache] is a private parameter only used by jlim
\r
1065 * @return the recordset ($rs->databaseType == 'array')
\r
1067 function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
\r
1069 if ($this->hasTop && $nrows > 0) {
\r
1070 // suggested by Reinhard Balling. Access requires top after distinct
\r
1071 // Informix requires first before distinct - F Riosa
\r
1072 $ismssql = (strpos($this->databaseType,'mssql') !== false);
\r
1073 if ($ismssql) $isaccess = false;
\r
1074 else $isaccess = (strpos($this->databaseType,'access') !== false);
\r
1076 if ($offset <= 0) {
\r
1078 // access includes ties in result
\r
1080 $sql = preg_replace(
\r
1081 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
\r
1083 if ($secs2cache>0) {
\r
1084 $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
\r
1086 $ret =& $this->Execute($sql,$inputarr);
\r
1088 return $ret; // PHP5 fix
\r
1089 } else if ($ismssql){
\r
1090 $sql = preg_replace(
\r
1091 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
\r
1093 $sql = preg_replace(
\r
1094 '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
\r
1097 $nn = $nrows + $offset;
\r
1098 if ($isaccess || $ismssql) {
\r
1099 $sql = preg_replace(
\r
1100 '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
\r
1102 $sql = preg_replace(
\r
1103 '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
\r
1108 // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
\r
1109 // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
\r
1110 global $ADODB_COUNTRECS;
\r
1112 $savec = $ADODB_COUNTRECS;
\r
1113 $ADODB_COUNTRECS = false;
\r
1116 if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
\r
1117 else $rs = &$this->Execute($sql,$inputarr);
\r
1119 if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
\r
1120 else $rs = &$this->Execute($sql,$inputarr);
\r
1122 $ADODB_COUNTRECS = $savec;
\r
1123 if ($rs && !$rs->EOF) {
\r
1124 $rs =& $this->_rs2rs($rs,$nrows,$offset);
\r
1131 * Create serializable recordset. Breaks rs link to connection.
\r
1133 * @param rs the recordset to serialize
\r
1135 function &SerializableRS(&$rs)
\r
1137 $rs2 =& $this->_rs2rs($rs);
\r
1139 $rs2->connection =& $ignore;
\r
1145 * Convert database recordset to an array recordset
\r
1146 * input recordset's cursor should be at beginning, and
\r
1147 * old $rs will be closed.
\r
1149 * @param rs the recordset to copy
\r
1150 * @param [nrows] number of rows to retrieve (optional)
\r
1151 * @param [offset] offset by number of rows (optional)
\r
1152 * @return the new recordset
\r
1154 function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
\r
1156 if (! $rs) return false;
\r
1158 $dbtype = $rs->databaseType;
\r
1160 $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
\r
1163 if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
\r
1165 $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
\r
1169 for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
\r
1170 $flds[] = $rs->FetchField($i);
\r
1172 $arr =& $rs->GetArrayLimit($nrows,$offset);
\r
1174 if ($close) $rs->Close();
\r
1176 $arrayClass = $this->arrayClass;
\r
1178 $rs2 =& new $arrayClass();
\r
1179 $rs2->connection = &$this;
\r
1180 $rs2->sql = $rs->sql;
\r
1181 $rs2->dataProvider = $this->dataProvider;
\r
1182 $rs2->InitArrayFields($arr,$flds);
\r
1187 * Return all rows. Compat with PEAR DB
\r
1189 function &GetAll($sql, $inputarr=false)
\r
1191 $arr =& $this->GetArray($sql,$inputarr);
\r
1195 function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
\r
1197 $rs =& $this->Execute($sql, $inputarr);
\r
1198 if (!$rs) return false;
\r
1200 $arr =& $rs->GetAssoc($force_array,$first2cols);
\r
1204 function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
\r
1206 if (!is_numeric($secs2cache)) {
\r
1207 $first2cols = $force_array;
\r
1208 $force_array = $inputarr;
\r
1210 $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);
\r
1211 if (!$rs) return false;
\r
1213 $arr =& $rs->GetAssoc($force_array,$first2cols);
\r
1218 * Return first element of first row of sql statement. Recordset is disposed
\r
1221 * @param sql SQL statement
\r
1222 * @param [inputarr] input bind array
\r
1224 function GetOne($sql,$inputarr=false)
\r
1226 global $ADODB_COUNTRECS;
\r
1227 $crecs = $ADODB_COUNTRECS;
\r
1228 $ADODB_COUNTRECS = false;
\r
1231 $rs = &$this->Execute($sql,$inputarr);
\r
1233 if (!$rs->EOF) $ret = reset($rs->fields);
\r
1236 $ADODB_COUNTRECS = $crecs;
\r
1240 function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
\r
1243 $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
\r
1245 if (!$rs->EOF) $ret = reset($rs->fields);
\r
1252 function GetCol($sql, $inputarr = false, $trim = false)
\r
1255 $rs = &$this->Execute($sql, $inputarr);
\r
1259 while (!$rs->EOF) {
\r
1260 $rv[] = trim(reset($rs->fields));
\r
1264 while (!$rs->EOF) {
\r
1265 $rv[] = reset($rs->fields);
\r
1274 function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
\r
1277 $rs = &$this->CacheExecute($secs, $sql, $inputarr);
\r
1280 while (!$rs->EOF) {
\r
1281 $rv[] = trim(reset($rs->fields));
\r
1285 while (!$rs->EOF) {
\r
1286 $rv[] = reset($rs->fields);
\r
1296 Calculate the offset of a date for a particular database and generate
\r
1297 appropriate SQL. Useful for calculating future/past dates and storing
\r
1300 If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
\r
1302 function OffsetDate($dayFraction,$date=false)
\r
1304 if (!$date) $date = $this->sysDate;
\r
1305 return '('.$date.'+'.$dayFraction.')';
\r
1311 * @param sql SQL statement
\r
1312 * @param [inputarr] input bind array
\r
1314 function &GetArray($sql,$inputarr=false)
\r
1316 global $ADODB_COUNTRECS;
\r
1318 $savec = $ADODB_COUNTRECS;
\r
1319 $ADODB_COUNTRECS = false;
\r
1320 $rs =& $this->Execute($sql,$inputarr);
\r
1321 $ADODB_COUNTRECS = $savec;
\r
1323 if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
\r
1324 else return false;
\r
1325 $arr =& $rs->GetArray();
\r
1330 function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
\r
1332 global $ADODB_COUNTRECS;
\r
1334 $savec = $ADODB_COUNTRECS;
\r
1335 $ADODB_COUNTRECS = false;
\r
1336 $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
\r
1337 $ADODB_COUNTRECS = $savec;
\r
1340 if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
\r
1341 else return false;
\r
1343 $arr =& $rs->GetArray();
\r
1351 * Return one row of sql statement. Recordset is disposed for you.
\r
1353 * @param sql SQL statement
\r
1354 * @param [inputarr] input bind array
\r
1356 function &GetRow($sql,$inputarr=false)
\r
1358 global $ADODB_COUNTRECS;
\r
1359 $crecs = $ADODB_COUNTRECS;
\r
1360 $ADODB_COUNTRECS = false;
\r
1362 $rs =& $this->Execute($sql,$inputarr);
\r
1364 $ADODB_COUNTRECS = $crecs;
\r
1366 if (!$rs->EOF) $arr = $rs->fields;
\r
1367 else $arr = array();
\r
1375 function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
\r
1377 $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
\r
1380 if (!$rs->EOF) $arr = $rs->fields;
\r
1388 * Insert or replace a single record. Note: this is not the same as MySQL's replace.
\r
1389 * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
\r
1390 * Also note that no table locking is done currently, so it is possible that the
\r
1391 * record be inserted twice by two programs...
\r
1393 * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
\r
1395 * $table table name
\r
1396 * $fieldArray associative array of data (you must quote strings yourself).
\r
1397 * $keyCol the primary key field name or if compound key, array of field names
\r
1398 * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
\r
1399 * but does not work with dates nor SQL functions.
\r
1400 * has_autoinc the primary key is an auto-inc field, so skip in insert.
\r
1402 * Currently blob replace not supported
\r
1404 * returns 0 = fail, 1 = update, 2 = insert
\r
1407 function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
\r
1409 global $ADODB_INCLUDED_LIB;
\r
1410 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
\r
1412 return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
\r
1417 * Will select, getting rows from $offset (1-based), for $nrows.
\r
1418 * This simulates the MySQL "select * from table limit $offset,$nrows" , and
\r
1419 * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
\r
1420 * MySQL and PostgreSQL parameter ordering is the opposite of the other.
\r
1422 * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
\r
1423 * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
\r
1425 * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
\r
1427 * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
\r
1429 * @param [offset] is the row to start calculations from (1-based)
\r
1430 * @param [nrows] is the number of rows to get
\r
1431 * @param [inputarr] array of bind variables
\r
1432 * @return the recordset ($rs->databaseType == 'array')
\r
1434 function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
\r
1436 if (!is_numeric($secs2cache)) {
\r
1437 if ($sql === false) $sql = -1;
\r
1438 if ($offset == -1) $offset = false;
\r
1439 // sql, nrows, offset,inputarr
\r
1440 $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
\r
1442 if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
\r
1443 $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
\r
1449 * Flush cached recordsets that match a particular $sql statement.
\r
1450 * If $sql == false, then we purge all files in the cache.
\r
1452 function CacheFlush($sql=false,$inputarr=false)
\r
1454 global $ADODB_CACHE_DIR;
\r
1456 if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
\r
1457 if (strncmp(PHP_OS,'WIN',3) === 0) {
\r
1458 $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
\r
1460 $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache';
\r
1461 // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
\r
1463 if ($this->debug) {
\r
1464 ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
\r
1470 $f = $this->_gencachename($sql.serialize($inputarr),false);
\r
1471 adodb_write_file($f,''); // is adodb_write_file needed?
\r
1472 if (!@unlink($f)) {
\r
1473 if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
\r
1478 * Private function to generate filename for caching.
\r
1479 * Filename is generated based on:
\r
1482 * - database type (oci8, ibase, ifx, etc)
\r
1486 * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
\r
1487 * Assuming that we can have 50,000 files per directory with good performance,
\r
1488 * then we can scale to 12.8 million unique cached recordsets. Wow!
\r
1490 function _gencachename($sql,$createdir)
\r
1492 global $ADODB_CACHE_DIR;
\r
1494 $m = md5($sql.$this->databaseType.$this->database.$this->user);
\r
1495 $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2);
\r
1496 if ($createdir && !file_exists($dir)) {
\r
1498 if (!mkdir($dir,0771))
\r
1499 if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
\r
1502 return $dir.'/adodb_'.$m.'.cache';
\r
1507 * Execute SQL, caching recordsets.
\r
1509 * @param [secs2cache] seconds to cache data, set to 0 to force query.
\r
1510 * This is an optional parameter.
\r
1511 * @param sql SQL statement to execute
\r
1512 * @param [inputarr] holds the input data to bind to
\r
1513 * @return RecordSet or false
\r
1515 function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
\r
1517 if (!is_numeric($secs2cache)) {
\r
1519 $sql = $secs2cache;
\r
1520 $secs2cache = $this->cacheSecs;
\r
1522 global $ADODB_INCLUDED_CSV;
\r
1523 if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
\r
1525 if (is_array($sql)) $sql = $sql[0];
\r
1527 $md5file = $this->_gencachename($sql.serialize($inputarr),true);
\r
1530 if ($secs2cache > 0){
\r
1531 $rs = &csv2rs($md5file,$err,$secs2cache);
\r
1532 $this->numCacheHits += 1;
\r
1536 $this->numCacheMisses += 1;
\r
1539 // no cached rs found
\r
1540 if ($this->debug) {
\r
1541 if (get_magic_quotes_runtime()) {
\r
1542 ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
\r
1544 if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
\r
1546 $rs = &$this->Execute($sql,$inputarr);
\r
1549 $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
\r
1550 $txt = _rs2serialize($rs,false,$sql); // serialize
\r
1552 if (!adodb_write_file($md5file,$txt,$this->debug)) {
\r
1553 if ($fn = $this->raiseErrorFn) {
\r
1554 $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
\r
1556 if ($this->debug) ADOConnection::outp( " Cache write error");
\r
1558 if ($rs->EOF && !$eof) {
\r
1560 //$rs = &csv2rs($md5file,$err);
\r
1561 $rs->connection = &$this; // Pablo suggestion
\r
1565 @unlink($md5file);
\r
1567 $this->_errorMsg = '';
\r
1568 $this->_errorCode = 0;
\r
1570 if ($this->fnCacheExecute) {
\r
1571 $fn = $this->fnCacheExecute;
\r
1572 $fn($this, $secs2cache, $sql, $inputarr);
\r
1574 // ok, set cached object found
\r
1575 $rs->connection = &$this; // Pablo suggestion
\r
1576 if ($this->debug){
\r
1577 global $HTTP_SERVER_VARS;
\r
1579 $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
\r
1580 $ttl = $rs->timeCreated + $secs2cache - time();
\r
1581 $s = is_array($sql) ? $sql[0] : $sql;
\r
1582 if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
\r
1584 ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
\r
1592 * Generates an Update Query based on an existing recordset.
\r
1593 * $arrFields is an associative array of fields with the value
\r
1594 * that should be assigned.
\r
1596 * Note: This function should only be used on a recordset
\r
1597 * that is run against a single table and sql should only
\r
1598 * be a simple select stmt with no groupby/orderby/limit
\r
1600 * "Jonathan Younger" <jyounger@unilab.com>
\r
1602 function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false)
\r
1604 global $ADODB_INCLUDED_LIB;
\r
1605 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
\r
1606 return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq);
\r
1611 * Generates an Insert Query based on an existing recordset.
\r
1612 * $arrFields is an associative array of fields with the value
\r
1613 * that should be assigned.
\r
1615 * Note: This function should only be used on a recordset
\r
1616 * that is run against a single table.
\r
1618 function GetInsertSQL(&$rs, $arrFields,$magicq=false)
\r
1620 global $ADODB_INCLUDED_LIB;
\r
1621 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
\r
1622 return _adodb_getinsertsql($this,$rs,$arrFields,$magicq);
\r
1627 * Update a blob column, given a where clause. There are more sophisticated
\r
1628 * blob handling functions that we could have implemented, but all require
\r
1629 * a very complex API. Instead we have chosen something that is extremely
\r
1630 * simple to understand and use.
\r
1632 * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
\r
1634 * Usage to update a $blobvalue which has a primary key blob_id=1 into a
\r
1635 * field blobtable.blobcolumn:
\r
1637 * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
\r
1641 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
\r
1642 * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
\r
1645 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
\r
1647 return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
\r
1652 * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
\r
1654 * $blobtype supports 'BLOB' and 'CLOB'
\r
1656 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
\r
1657 * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
\r
1659 function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
\r
1661 $fd = fopen($path,'rb');
\r
1662 if ($fd === false) return false;
\r
1663 $val = fread($fd,filesize($path));
\r
1665 return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
\r
1668 function BlobDecode($blob)
\r
1673 function BlobEncode($blob)
\r
1678 function SetCharSet($charset)
\r
1683 function IfNull( $field, $ifNull )
\r
1685 return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
\r
1688 function LogSQL($enable=true)
\r
1690 include_once(ADODB_DIR.'/adodb-perf.inc.php');
\r
1692 if ($enable) $this->fnExecute = 'adodb_log_sql';
\r
1693 else $this->fnExecute = false;
\r
1695 $old = $this->_logsql;
\r
1696 $this->_logsql = $enable;
\r
1697 if ($enable && !$old) $this->_affected = false;
\r
1701 function GetCharSet()
\r
1708 * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
\r
1710 * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
\r
1711 * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
\r
1713 function UpdateClob($table,$column,$val,$where)
\r
1715 return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
\r
1720 * Change the SQL connection locale to a specified locale.
\r
1721 * This is used to get the date formats written depending on the client locale.
\r
1723 function SetDateLocale($locale = 'En')
\r
1725 $this->locale = $locale;
\r
1730 $this->fmtDate="Y-m-d";
\r
1731 $this->fmtTimeStamp = "Y-m-d H:i:s";
\r
1737 $this->fmtDate="d-m-Y";
\r
1738 $this->fmtTimeStamp = "d-m-Y H:i:s";
\r
1742 $this->fmtDate="d.m.Y";
\r
1743 $this->fmtTimeStamp = "d.m.Y H:i:s";
\r
1750 * $meta contains the desired type, which could be...
\r
1751 * C for character. You will have to define the precision yourself.
\r
1752 * X for teXt. For unlimited character lengths.
\r
1754 * F for floating point, with no need to define scale and precision
\r
1755 * N for decimal numbers, you will have to define the (scale, precision) yourself
\r
1758 * L for logical/Boolean
\r
1760 * R for autoincrement counter/integer
\r
1761 * and if you want to use double-byte, add a 2 to the end, like C2 or X2.
\r
1764 * @return the actual type of the data or false if no such type available
\r
1766 function ActualType($meta)
\r
1788 * Close Connection
\r
1792 return $this->_close();
\r
1794 // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need
\r
1795 // to be closed too!
\r
1796 //if ($this->_isPersistentConnection != true) return $this->_close();
\r
1797 //else return true;
\r
1801 * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
\r
1803 * @return true if succeeded or false if database does not support transactions
\r
1805 function BeginTrans() {return false;}
\r
1809 * If database does not support transactions, always return true as data always commited
\r
1811 * @param $ok set to false to rollback transaction, true to commit
\r
1813 * @return true/false.
\r
1815 function CommitTrans($ok=true)
\r
1820 * If database does not support transactions, rollbacks always fail, so return false
\r
1822 * @return true/false.
\r
1824 function RollbackTrans()
\r
1829 * return the databases that the driver can connect to.
\r
1830 * Some databases will return an empty array.
\r
1832 * @return an array of database names.
\r
1834 function MetaDatabases()
\r
1836 global $ADODB_FETCH_MODE;
\r
1838 if ($this->metaDatabasesSQL) {
\r
1839 $save = $ADODB_FETCH_MODE;
\r
1840 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
\r
1842 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
\r
1844 $arr = $this->GetCol($this->metaDatabasesSQL);
\r
1845 if (isset($savem)) $this->SetFetchMode($savem);
\r
1846 $ADODB_FETCH_MODE = $save;
\r
1855 * @param ttype can either be 'VIEW' or 'TABLE' or false.
\r
1856 * If false, both views and tables are returned.
\r
1857 * "VIEW" returns only views
\r
1858 * "TABLE" returns only tables
\r
1859 * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
\r
1860 * @param mask is the input mask - only supported by oci8 and postgresql
\r
1862 * @return array of tables for current database.
\r
1864 function &MetaTables($ttype=false,$showSchema=false,$mask=false)
\r
1866 global $ADODB_FETCH_MODE;
\r
1868 if ($mask) return false;
\r
1870 if ($this->metaTablesSQL) {
\r
1871 // complicated state saving by the need for backward compat
\r
1872 $save = $ADODB_FETCH_MODE;
\r
1873 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
\r
1875 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
\r
1877 $rs = $this->Execute($this->metaTablesSQL);
\r
1878 if (isset($savem)) $this->SetFetchMode($savem);
\r
1879 $ADODB_FETCH_MODE = $save;
\r
1881 if ($rs === false) return false;
\r
1882 $arr =& $rs->GetArray();
\r
1885 if ($hast = ($ttype && isset($arr[0][1]))) {
\r
1886 $showt = strncmp($ttype,'T',1);
\r
1889 for ($i=0; $i < sizeof($arr); $i++) {
\r
1891 if ($showt == 0) {
\r
1892 if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
\r
1894 if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
\r
1897 $arr2[] = trim($arr[$i][0]);
\r
1906 function _findschema(&$table,&$schema)
\r
1908 if (!$schema && ($at = strpos($table,'.')) !== false) {
\r
1909 $schema = substr($table,0,$at);
\r
1910 $table = substr($table,$at+1);
\r
1915 * List columns in a database as an array of ADOFieldObjects.
\r
1916 * See top of file for definition of object.
\r
1918 * @param table table name to query
\r
1919 * @param upper uppercase table name (required by some databases)
\r
1920 * @schema is optional database schema to use - not supported by all databases.
\r
1922 * @return array of ADOFieldObjects for current table.
\r
1924 function &MetaColumns($table,$upper=true)
\r
1926 global $ADODB_FETCH_MODE;
\r
1928 if (!empty($this->metaColumnsSQL)) {
\r
1931 $this->_findschema($table,$schema);
\r
1933 $save = $ADODB_FETCH_MODE;
\r
1934 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
\r
1935 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
\r
1936 $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table));
\r
1937 if (isset($savem)) $this->SetFetchMode($savem);
\r
1938 $ADODB_FETCH_MODE = $save;
\r
1939 if ($rs === false) return false;
\r
1941 $retarr = array();
\r
1942 while (!$rs->EOF) { //print_r($rs->fields);
\r
1943 $fld =& new ADOFieldObject();
\r
1944 $fld->name = $rs->fields[0];
\r
1945 $fld->type = $rs->fields[1];
\r
1946 if (isset($rs->fields[3]) && $rs->fields[3]) {
\r
1947 if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
\r
1948 $fld->scale = $rs->fields[4];
\r
1949 if ($fld->scale>0) $fld->max_length += 1;
\r
1951 $fld->max_length = $rs->fields[2];
\r
1953 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
\r
1954 else $retarr[strtoupper($fld->name)] = $fld;
\r
1964 * List indexes on a table as an array.
\r
1965 * @param table table name to query
\r
1966 * @param primary include primary keys.
\r
1968 * @return array of indexes on current table.
\r
1970 function &MetaIndexes($table, $primary = false, $owner = false)
\r
1976 * List columns names in a table as an array.
\r
1977 * @param table table name to query
\r
1979 * @return array of column names for current table.
\r
1981 function &MetaColumnNames($table)
\r
1983 $objarr =& $this->MetaColumns($table);
\r
1984 if (!is_array($objarr)) return false;
\r
1987 foreach($objarr as $v) {
\r
1988 $arr[strtoupper($v->name)] = $v->name;
\r
1994 * Different SQL databases used different methods to combine strings together.
\r
1995 * This function provides a wrapper.
\r
1997 * param s variable number of string parameters
\r
1999 * Usage: $db->Concat($str1,$str2);
\r
2001 * @return concatenated string
\r
2005 $arr = func_get_args();
\r
2006 return implode($this->concat_operator, $arr);
\r
2011 * Converts a date "d" to a string that the database can understand.
\r
2013 * @param d a date in Unix date time format.
\r
2015 * @return date string in database date format
\r
2017 function DBDate($d)
\r
2019 if (empty($d) && $d !== 0) return 'null';
\r
2021 if (is_string($d) && !is_numeric($d)) {
\r
2022 if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
\r
2023 if ($this->isoDates) return "'$d'";
\r
2024 $d = ADOConnection::UnixDate($d);
\r
2027 return adodb_date($this->fmtDate,$d);
\r
2032 * Converts a timestamp "ts" to a string that the database can understand.
\r
2034 * @param ts a timestamp in Unix date time format.
\r
2036 * @return timestamp string in database timestamp format
\r
2038 function DBTimeStamp($ts)
\r
2040 if (empty($ts) && $ts !== 0) return 'null';
\r
2042 # strlen(14) allows YYYYMMDDHHMMSS format
\r
2043 if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
\r
2044 return adodb_date($this->fmtTimeStamp,$ts);
\r
2046 if ($ts === 'null') return $ts;
\r
2047 if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
\r
2049 $ts = ADOConnection::UnixTimeStamp($ts);
\r
2050 return adodb_date($this->fmtTimeStamp,$ts);
\r
2054 * Also in ADORecordSet.
\r
2055 * @param $v is a date string in YYYY-MM-DD format
\r
2057 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
\r
2059 function UnixDate($v)
\r
2061 if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
\r
2062 ($v), $rr)) return false;
\r
2064 if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
\r
2066 return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
\r
2071 * Also in ADORecordSet.
\r
2072 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
\r
2074 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
\r
2076 function UnixTimeStamp($v)
\r
2079 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
\r
2080 ($v), $rr)) return false;
\r
2082 if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
\r
2085 if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
\r
2086 return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
\r
2090 * Also in ADORecordSet.
\r
2092 * Format database date based on user defined format.
\r
2094 * @param v is the character date in YYYY-MM-DD format, returned by database
\r
2095 * @param fmt is the format to apply to it, using date()
\r
2097 * @return a date formated as user desires
\r
2100 function UserDate($v,$fmt='Y-m-d')
\r
2102 $tt = $this->UnixDate($v);
\r
2103 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
\r
2104 if (($tt === false || $tt == -1) && $v != false) return $v;
\r
2105 else if ($tt == 0) return $this->emptyDate;
\r
2106 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
\r
2109 return adodb_date($fmt,$tt);
\r
2115 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
\r
2116 * @param fmt is the format to apply to it, using date()
\r
2118 * @return a timestamp formated as user desires
\r
2120 function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
\r
2122 # strlen(14) allows YYYYMMDDHHMMSS format
\r
2123 if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
\r
2124 $tt = $this->UnixTimeStamp($v);
\r
2125 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
\r
2126 if (($tt === false || $tt == -1) && $v != false) return $v;
\r
2127 if ($tt == 0) return $this->emptyTimeStamp;
\r
2128 return adodb_date($fmt,$tt);
\r
2132 * Quotes a string, without prefixing nor appending quotes.
\r
2134 function addq($s,$magicq=false)
\r
2136 if (!$magic_quotes) {
\r
2138 if ($this->replaceQuote[0] == '\\'){
\r
2139 // only since php 4.0.5
\r
2140 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
\r
2141 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
\r
2143 return str_replace("'",$this->replaceQuote,$s);
\r
2146 // undo magic quotes for "
\r
2147 $s = str_replace('\\"','"',$s);
\r
2149 if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
\r
2151 else {// change \' to '' for sybase/mssql
\r
2152 $s = str_replace('\\\\','\\',$s);
\r
2153 return str_replace("\\'",$this->replaceQuote,$s);
\r
2158 * Correctly quotes a string so that all strings are escaped. We prefix and append
\r
2159 * to the string single-quotes.
\r
2160 * An example is $db->qstr("Don't bother",magic_quotes_runtime());
\r
2162 * @param s the string to quote
\r
2163 * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
\r
2164 * This undoes the stupidity of magic quotes for GPC.
\r
2166 * @return quoted string to be sent back to database
\r
2168 function qstr($s,$magic_quotes=false)
\r
2170 if (!$magic_quotes) {
\r
2172 if ($this->replaceQuote[0] == '\\'){
\r
2173 // only since php 4.0.5
\r
2174 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
\r
2175 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
\r
2177 return "'".str_replace("'",$this->replaceQuote,$s)."'";
\r
2180 // undo magic quotes for "
\r
2181 $s = str_replace('\\"','"',$s);
\r
2183 if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
\r
2185 else {// change \' to '' for sybase/mssql
\r
2186 $s = str_replace('\\\\','\\',$s);
\r
2187 return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
\r
2193 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
\r
2194 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
\r
2195 * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
\r
2197 * See readme.htm#ex8 for an example of usage.
\r
2200 * @param nrows is the number of rows per page to get
\r
2201 * @param page is the page number to get (1-based)
\r
2202 * @param [inputarr] array of bind variables
\r
2203 * @param [secs2cache] is a private parameter only used by jlim
\r
2204 * @return the recordset ($rs->databaseType == 'array')
\r
2206 * NOTE: phpLens uses a different algorithm and does not use PageExecute().
\r
2209 function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0)
\r
2211 global $ADODB_INCLUDED_LIB;
\r
2212 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
\r
2213 if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
\r
2214 return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
\r
2220 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
\r
2221 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
\r
2222 * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
\r
2224 * @param secs2cache seconds to cache data, set to 0 to force query
\r
2226 * @param nrows is the number of rows per page to get
\r
2227 * @param page is the page number to get (1-based)
\r
2228 * @param [inputarr] array of bind variables
\r
2229 * @return the recordset ($rs->databaseType == 'array')
\r
2231 function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false)
\r
2233 /*switch($this->dataProvider) {
\r
2237 default: $secs2cache = 0; break;
\r
2239 $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
\r
2243 } // end class ADOConnection
\r
2247 //==============================================================================================
\r
2248 // CLASS ADOFetchObj
\r
2249 //==============================================================================================
\r
2252 * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
\r
2254 class ADOFetchObj {
\r
2257 //==============================================================================================
\r
2258 // CLASS ADORecordSet_empty
\r
2259 //==============================================================================================
\r
2262 * Lightweight recordset when there are no records to be returned
\r
2264 class ADORecordSet_empty
\r
2266 var $dataProvider = 'empty';
\r
2267 var $databaseType = false;
\r
2269 var $_numOfRows = 0;
\r
2270 var $fields = false;
\r
2271 var $connection = false;
\r
2272 function RowCount() {return 0;}
\r
2273 function RecordCount() {return 0;}
\r
2274 function PO_RecordCount(){return 0;}
\r
2275 function Close(){return true;}
\r
2276 function FetchRow() {return false;}
\r
2277 function FieldCount(){ return 0;}
\r
2280 //==============================================================================================
\r
2281 // DATE AND TIME FUNCTIONS
\r
2282 //==============================================================================================
\r
2283 include_once(ADODB_DIR.'/adodb-time.inc.php');
\r
2285 //==============================================================================================
\r
2286 // CLASS ADORecordSet
\r
2287 //==============================================================================================
\r
2289 if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
\r
2290 else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
\r
2292 * RecordSet class that represents the dataset returned by the database.
\r
2293 * To keep memory overhead low, this class holds only the current row in memory.
\r
2294 * No prefetching of data is done, so the RecordCount() can return -1 ( which
\r
2295 * means recordcount not known).
\r
2297 class ADORecordSet extends ADODB_BASE_RS {
\r
2299 * public variables
\r
2301 var $dataProvider = "native";
\r
2302 var $fields = false; /// holds the current row data
\r
2303 var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
\r
2304 /// in other words, we use a text area for editing.
\r
2305 var $canSeek = false; /// indicates that seek is supported
\r
2306 var $sql; /// sql text
\r
2307 var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
\r
2309 var $emptyTimeStamp = ' '; /// what to display when $time==0
\r
2310 var $emptyDate = ' '; /// what to display when $time==0
\r
2311 var $debug = false;
\r
2312 var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
\r
2314 var $bind = false; /// used by Fields() to hold array - should be private?
\r
2315 var $fetchMode; /// default fetch mode
\r
2316 var $connection = false; /// the parent connection
\r
2318 * private variables
\r
2320 var $_numOfRows = -1; /** number of rows, or -1 */
\r
2321 var $_numOfFields = -1; /** number of fields in recordset */
\r
2322 var $_queryID = -1; /** This variable keeps the result link identifier. */
\r
2323 var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
\r
2324 var $_closed = false; /** has recordset been closed */
\r
2325 var $_inited = false; /** Init() should only be called once */
\r
2326 var $_obj; /** Used by FetchObj */
\r
2327 var $_names; /** Used by FetchObj */
\r
2329 var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */
\r
2330 var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */
\r
2331 var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */
\r
2332 var $_lastPageNo = -1;
\r
2333 var $_maxRecordCount = 0;
\r
2334 var $datetime = false;
\r
2339 * @param queryID this is the queryID returned by ADOConnection->_query()
\r
2342 function ADORecordSet($queryID)
\r
2344 $this->_queryID = $queryID;
\r
2351 if ($this->_inited) return;
\r
2352 $this->_inited = true;
\r
2353 if ($this->_queryID) @$this->_initrs();
\r
2355 $this->_numOfRows = 0;
\r
2356 $this->_numOfFields = 0;
\r
2358 if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
\r
2360 $this->_currentRow = 0;
\r
2361 if ($this->EOF = ($this->_fetch() === false)) {
\r
2362 $this->_numOfRows = 0; // _numOfRows could be -1
\r
2365 $this->EOF = true;
\r
2371 * Generate a SELECT tag string from a recordset, and return the string.
\r
2372 * If the recordset has 2 cols, we treat the 1st col as the containing
\r
2373 * the text to display to the user, and 2nd col as the return value. Default
\r
2374 * strings are compared with the FIRST column.
\r
2376 * @param name name of SELECT tag
\r
2377 * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
\r
2378 * @param [blank1stItem] true to leave the 1st item in list empty
\r
2379 * @param [multiple] true for listbox, false for popup
\r
2380 * @param [size] #rows to show for listbox. not used by popup
\r
2381 * @param [selectAttr] additional attributes to defined for SELECT tag.
\r
2382 * useful for holding javascript onChange='...' handlers.
\r
2383 & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
\r
2384 * column 0 (1st col) if this is true. This is not documented.
\r
2388 * changes by glen.davies@cce.ac.nz to support multiple hilited items
\r
2390 function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
\r
2391 $size=0, $selectAttr='',$compareFields0=true)
\r
2393 global $ADODB_INCLUDED_LIB;
\r
2394 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
\r
2395 return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
\r
2396 $size, $selectAttr,$compareFields0);
\r
2400 * Generate a SELECT tag string from a recordset, and return the string.
\r
2401 * If the recordset has 2 cols, we treat the 1st col as the containing
\r
2402 * the text to display to the user, and 2nd col as the return value. Default
\r
2403 * strings are compared with the SECOND column.
\r
2406 function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
\r
2408 global $ADODB_INCLUDED_LIB;
\r
2409 if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
\r
2410 return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple,
\r
2411 $size, $selectAttr,false);
\r
2416 * return recordset as a 2-dimensional array.
\r
2418 * @param [nRows] is the number of rows to return. -1 means every row.
\r
2420 * @return an array indexed by the rows (0-based) from the recordset
\r
2422 function &GetArray($nRows = -1)
\r
2424 global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows);
\r
2426 $results = array();
\r
2428 while (!$this->EOF && $nRows != $cnt) {
\r
2429 $results[] = $this->fields;
\r
2430 $this->MoveNext();
\r
2436 function &GetAll($nRows = -1)
\r
2438 $arr =& $this->GetArray($nRows);
\r
2443 * Some databases allow multiple recordsets to be returned. This function
\r
2444 * will return true if there is a next recordset, or false if no more.
\r
2446 function NextRecordSet()
\r
2452 * return recordset as a 2-dimensional array.
\r
2453 * Helper function for ADOConnection->SelectLimit()
\r
2455 * @param offset is the row to start calculations from (1-based)
\r
2456 * @param [nrows] is the number of rows to return
\r
2458 * @return an array indexed by the rows (0-based) from the recordset
\r
2460 function &GetArrayLimit($nrows,$offset=-1)
\r
2462 if ($offset <= 0) {
\r
2463 $arr =& $this->GetArray($nrows);
\r
2467 $this->Move($offset);
\r
2469 $results = array();
\r
2471 while (!$this->EOF && $nrows != $cnt) {
\r
2472 $results[$cnt++] = $this->fields;
\r
2473 $this->MoveNext();
\r
2481 * Synonym for GetArray() for compatibility with ADO.
\r
2483 * @param [nRows] is the number of rows to return. -1 means every row.
\r
2485 * @return an array indexed by the rows (0-based) from the recordset
\r
2487 function &GetRows($nRows = -1)
\r
2489 $arr =& $this->GetArray($nRows);
\r
2494 * return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
\r
2495 * The first column is treated as the key and is not included in the array.
\r
2496 * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
\r
2497 * $force_array == true.
\r
2499 * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
\r
2500 * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
\r
2501 * read the source.
\r
2503 * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
\r
2504 * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
\r
2506 * @return an associative array indexed by the first column of the array,
\r
2507 * or false if the data has less than 2 cols.
\r
2509 function &GetAssoc($force_array = false, $first2cols = false) {
\r
2510 $cols = $this->_numOfFields;
\r
2514 $numIndex = isset($this->fields[0]);
\r
2515 $results = array();
\r
2517 if (!$first2cols && ($cols > 2 || $force_array)) {
\r
2519 while (!$this->EOF) {
\r
2520 $results[trim($this->fields[0])] = array_slice($this->fields, 1);
\r
2521 $this->MoveNext();
\r
2524 while (!$this->EOF) {
\r
2525 $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
\r
2526 $this->MoveNext();
\r
2530 // return scalar values
\r
2532 while (!$this->EOF) {
\r
2533 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
\r
2534 $results[trim(($this->fields[0]))] = $this->fields[1];
\r
2535 $this->MoveNext();
\r
2538 while (!$this->EOF) {
\r
2539 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
\r
2540 $v1 = trim(reset($this->fields));
\r
2541 $v2 = ''.next($this->fields);
\r
2542 $results[$v1] = $v2;
\r
2543 $this->MoveNext();
\r
2553 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
\r
2554 * @param fmt is the format to apply to it, using date()
\r
2556 * @return a timestamp formated as user desires
\r
2558 function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
\r
2560 if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
\r
2561 $tt = $this->UnixTimeStamp($v);
\r
2562 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
\r
2563 if (($tt === false || $tt == -1) && $v != false) return $v;
\r
2564 if ($tt === 0) return $this->emptyTimeStamp;
\r
2565 return adodb_date($fmt,$tt);
\r
2570 * @param v is the character date in YYYY-MM-DD format, returned by database
\r
2571 * @param fmt is the format to apply to it, using date()
\r
2573 * @return a date formated as user desires
\r
2575 function UserDate($v,$fmt='Y-m-d')
\r
2577 $tt = $this->UnixDate($v);
\r
2578 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
\r
2579 if (($tt === false || $tt == -1) && $v != false) return $v;
\r
2580 else if ($tt == 0) return $this->emptyDate;
\r
2581 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
\r
2583 return adodb_date($fmt,$tt);
\r
2589 * @param $v is a date string in YYYY-MM-DD format
\r
2591 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
\r
2593 function UnixDate($v)
\r
2596 if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
\r
2597 ($v), $rr)) return false;
\r
2599 if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
\r
2601 return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
\r
2606 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
\r
2608 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
\r
2610 function UnixTimeStamp($v)
\r
2614 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
\r
2615 ($v), $rr)) return false;
\r
2616 if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
\r
2619 if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
\r
2620 return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
\r
2625 * PEAR DB Compat - do not use internally
\r
2629 return $this->Close();
\r
2634 * PEAR DB compat, number of rows
\r
2636 function NumRows()
\r
2638 return $this->_numOfRows;
\r
2643 * PEAR DB compat, number of cols
\r
2645 function NumCols()
\r
2647 return $this->_numOfFields;
\r
2651 * Fetch a row, returning false if no more rows.
\r
2652 * This is PEAR DB compat mode.
\r
2654 * @return false or array containing the current record
\r
2656 function &FetchRow()
\r
2658 if ($this->EOF) return false;
\r
2659 $arr = $this->fields;
\r
2660 $this->_currentRow++;
\r
2661 if (!$this->_fetch()) $this->EOF = true;
\r
2667 * Fetch a row, returning PEAR_Error if no more rows.
\r
2668 * This is PEAR DB compat mode.
\r
2670 * @return DB_OK or error object
\r
2672 function FetchInto(&$arr)
\r
2674 if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
\r
2675 $arr = $this->fields;
\r
2676 $this->MoveNext();
\r
2677 return 1; // DB_OK
\r
2682 * Move to the first row in the recordset. Many databases do NOT support this.
\r
2684 * @return true or false
\r
2686 function MoveFirst()
\r
2688 if ($this->_currentRow == 0) return true;
\r
2689 return $this->Move(0);
\r
2694 * Move to the last row in the recordset.
\r
2696 * @return true or false
\r
2698 function MoveLast()
\r
2700 if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
\r
2701 if ($this->EOF) return false;
\r
2702 while (!$this->EOF) {
\r
2703 $f = $this->fields;
\r
2704 $this->MoveNext();
\r
2706 $this->fields = $f;
\r
2707 $this->EOF = false;
\r
2713 * Move to next record in the recordset.
\r
2715 * @return true if there still rows available, or false if there are no more rows (EOF).
\r
2717 function MoveNext()
\r
2719 if (!$this->EOF) {
\r
2720 $this->_currentRow++;
\r
2721 if ($this->_fetch()) return true;
\r
2723 $this->EOF = true;
\r
2724 /* -- tested error handling when scrolling cursor -- seems useless.
\r
2725 $conn = $this->connection;
\r
2726 if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
\r
2727 $fn = $conn->raiseErrorFn;
\r
2728 $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
\r
2735 * Random access to a specific row in the recordset. Some databases do not support
\r
2736 * access to previous rows in the databases (no scrolling backwards).
\r
2738 * @param rowNumber is the row to move to (0-based)
\r
2740 * @return true if there still rows available, or false if there are no more rows (EOF).
\r
2742 function Move($rowNumber = 0)
\r
2744 $this->EOF = false;
\r
2745 if ($rowNumber == $this->_currentRow) return true;
\r
2746 if ($rowNumber >= $this->_numOfRows)
\r
2747 if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
\r
2749 if ($this->canSeek) {
\r
2751 if ($this->_seek($rowNumber)) {
\r
2752 $this->_currentRow = $rowNumber;
\r
2753 if ($this->_fetch()) {
\r
2757 $this->EOF = true;
\r
2761 if ($rowNumber < $this->_currentRow) return false;
\r
2762 global $ADODB_EXTENSION;
\r
2763 if ($ADODB_EXTENSION) {
\r
2764 while (!$this->EOF && $this->_currentRow < $rowNumber) {
\r
2765 adodb_movenext($this);
\r
2769 while (! $this->EOF && $this->_currentRow < $rowNumber) {
\r
2770 $this->_currentRow++;
\r
2772 if (!$this->_fetch()) $this->EOF = true;
\r
2775 return !($this->EOF);
\r
2778 $this->fields = false;
\r
2779 $this->EOF = true;
\r
2785 * Get the value of a field in the current row by column name.
\r
2786 * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
\r
2788 * @param colname is the field to access
\r
2790 * @return the value of $colname column
\r
2792 function Fields($colname)
\r
2794 return $this->fields[$colname];
\r
2797 function GetAssocKeys($upper=true)
\r
2799 $this->bind = array();
\r
2800 for ($i=0; $i < $this->_numOfFields; $i++) {
\r
2801 $o =& $this->FetchField($i);
\r
2802 if ($upper === 2) $this->bind[$o->name] = $i;
\r
2803 else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
\r
2808 * Use associative array to get fields array for databases that do not support
\r
2809 * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it
\r
2811 * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
\r
2812 * before you execute your SQL statement, and access $rs->fields['col'] directly.
\r
2814 * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
\r
2816 function &GetRowAssoc($upper=1)
\r
2818 $record = array();
\r
2819 // if (!$this->fields) return $record;
\r
2821 if (!$this->bind) {
\r
2822 $this->GetAssocKeys($upper);
\r
2825 foreach($this->bind as $k => $v) {
\r
2826 $record[$k] = $this->fields[$v];
\r
2834 * Clean up recordset
\r
2836 * @return true or false
\r
2840 // free connection object - this seems to globally free the object
\r
2841 // and not merely the reference, so don't do this...
\r
2842 // $this->connection = false;
\r
2843 if (!$this->_closed) {
\r
2844 $this->_closed = true;
\r
2845 return $this->_close();
\r
2851 * synonyms RecordCount and RowCount
\r
2853 * @return the number of rows or -1 if this is not supported
\r
2855 function RecordCount() {return $this->_numOfRows;}
\r
2859 * If we are using PageExecute(), this will return the maximum possible rows
\r
2860 * that can be returned when paging a recordset.
\r
2862 function MaxRecordCount()
\r
2864 return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
\r
2868 * synonyms RecordCount and RowCount
\r
2870 * @return the number of rows or -1 if this is not supported
\r
2872 function RowCount() {return $this->_numOfRows;}
\r
2876 * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
\r
2878 * @return the number of records from a previous SELECT. All databases support this.
\r
2880 * But aware possible problems in multiuser environments. For better speed the table
\r
2881 * must be indexed by the condition. Heavy test this before deploying.
\r
2883 function PO_RecordCount($table="", $condition="") {
\r
2885 $lnumrows = $this->_numOfRows;
\r
2886 // the database doesn't support native recordcount, so we do a workaround
\r
2887 if ($lnumrows == -1 && $this->connection) {
\r
2889 if ($condition) $condition = " WHERE " . $condition;
\r
2890 $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
\r
2891 if ($resultrows) $lnumrows = reset($resultrows->fields);
\r
2898 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
\r
2900 function CurrentRow() {return $this->_currentRow;}
\r
2903 * synonym for CurrentRow -- for ADO compat
\r
2905 * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
\r
2907 function AbsolutePosition() {return $this->_currentRow;}
\r
2910 * @return the number of columns in the recordset. Some databases will set this to 0
\r
2911 * if no records are returned, others will return the number of columns in the query.
\r
2913 function FieldCount() {return $this->_numOfFields;}
\r
2917 * Get the ADOFieldObject of a specific column.
\r
2919 * @param fieldoffset is the column position to access(0-based).
\r
2921 * @return the ADOFieldObject for that column, or false.
\r
2923 function &FetchField($fieldoffset)
\r
2925 // must be defined by child class
\r
2929 * Get the ADOFieldObjects of all columns in an array.
\r
2932 function FieldTypesArray()
\r
2935 for ($i=0, $max=$this->_numOfFields; $i < $max; $i++)
\r
2936 $arr[] = $this->FetchField($i);
\r
2941 * Return the fields array of the current row as an object for convenience.
\r
2942 * The default case is lowercase field names.
\r
2944 * @return the object with the properties set to the fields of the current row
\r
2946 function &FetchObj()
\r
2948 $o =& $this->FetchObject(false);
\r
2953 * Return the fields array of the current row as an object for convenience.
\r
2954 * The default case is uppercase.
\r
2956 * @param $isupper to set the object property names to uppercase
\r
2958 * @return the object with the properties set to the fields of the current row
\r
2960 function &FetchObject($isupper=true)
\r
2962 if (empty($this->_obj)) {
\r
2963 $this->_obj =& new ADOFetchObj();
\r
2964 $this->_names = array();
\r
2965 for ($i=0; $i <$this->_numOfFields; $i++) {
\r
2966 $f = $this->FetchField($i);
\r
2967 $this->_names[] = $f->name;
\r
2971 $o = &$this->_obj;
\r
2972 for ($i=0; $i <$this->_numOfFields; $i++) {
\r
2973 $name = $this->_names[$i];
\r
2974 if ($isupper) $n = strtoupper($name);
\r
2977 $o->$n = $this->Fields($name);
\r
2983 * Return the fields array of the current row as an object for convenience.
\r
2984 * The default is lower-case field names.
\r
2986 * @return the object with the properties set to the fields of the current row,
\r
2989 * Fixed bug reported by tim@orotech.net
\r
2991 function &FetchNextObj()
\r
2993 return $this->FetchNextObject(false);
\r
2998 * Return the fields array of the current row as an object for convenience.
\r
2999 * The default is upper case field names.
\r
3001 * @param $isupper to set the object property names to uppercase
\r
3003 * @return the object with the properties set to the fields of the current row,
\r
3006 * Fixed bug reported by tim@orotech.net
\r
3008 function &FetchNextObject($isupper=true)
\r
3011 if ($this->_numOfRows != 0 && !$this->EOF) {
\r
3012 $o = $this->FetchObject($isupper);
\r
3013 $this->_currentRow++;
\r
3014 if ($this->_fetch()) return $o;
\r
3016 $this->EOF = true;
\r
3021 * Get the metatype of the column. This is used for formatting. This is because
\r
3022 * many databases use different names for the same type, so we transform the original
\r
3023 * type to our standardised version which uses 1 character codes:
\r
3025 * @param t is the type passed in. Normally is ADOFieldObject->type.
\r
3026 * @param len is the maximum length of that field. This is because we treat character
\r
3027 * fields bigger than a certain size as a 'B' (blob).
\r
3028 * @param fieldobj is the field object returned by the database driver. Can hold
\r
3029 * additional info (eg. primary_key for mysql).
\r
3031 * @return the general type of the data:
\r
3032 * C for character < 200 chars
\r
3033 * X for teXt (>= 200 chars)
\r
3035 * N for numeric floating point
\r
3038 * L for logical/Boolean
\r
3040 * R for autoincrement counter/integer
\r
3044 function MetaType($t,$len=-1,$fieldobj=false)
\r
3046 if (is_object($t)) {
\r
3048 $t = $fieldobj->type;
\r
3049 $len = $fieldobj->max_length;
\r
3051 // changed in 2.32 to hashing instead of switch stmt for speed...
\r
3052 static $typeMap = array(
\r
3054 'VARCHAR2' => 'C',
\r
3059 'NVARCHAR' => 'C',
\r
3062 'CHARACTER' => 'C',
\r
3063 'INTERVAL' => 'C', # Postgres
\r
3065 'LONGCHAR' => 'X',
\r
3072 'LVARCHAR' => 'X',
\r
3077 'VARBINARY' => 'B',
\r
3078 'LONGBINARY' => 'B',
\r
3081 'YEAR' => 'D', // mysql
\r
3086 'TIMESTAMP' => 'T',
\r
3087 'DATETIME' => 'T',
\r
3088 'TIMESTAMPTZ' => 'T',
\r
3092 'BOOLEAN' => 'L',
\r
3098 'SERIAL' => 'R', // ifx
\r
3099 'INT IDENTITY' => 'R',
\r
3103 'INTEGER UNSIGNED' => 'I',
\r
3106 'SMALLINT' => 'I',
\r
3109 'LONG' => 'N', // interbase is numeric, oci8 is blob
\r
3110 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
\r
3115 'DOUBLE PRECISION' => 'N',
\r
3116 'SMALLFLOAT' => 'N',
\r
3125 'SQLSERIAL' => 'I',
\r
3126 'SQLSMINT' => 'I',
\r
3127 'SQLSMFLOAT' => 'N',
\r
3128 'SQLFLOAT' => 'N',
\r
3129 'SQLMONEY' => 'N',
\r
3130 'SQLDECIMAL' => 'N',
\r
3131 'SQLDATE' => 'D',
\r
3132 'SQLVCHAR' => 'C',
\r
3133 'SQLCHAR' => 'C',
\r
3134 'SQLDTIME' => 'T',
\r
3135 'SQLINTERVAL' => 'N',
\r
3136 'SQLBYTES' => 'B',
\r
3141 $t = strtoupper($t);
\r
3142 $tmap = @$typeMap[$t];
\r
3146 // is the char field is too long, return as text field...
\r
3147 if ($this->blobSize >= 0) {
\r
3148 if ($len > $this->blobSize) return 'X';
\r
3149 } else if ($len > 250) {
\r
3155 if (!empty($fieldobj->primary_key)) return 'R';
\r
3162 if (isset($fieldobj->binary))
\r
3163 return ($fieldobj->binary) ? 'B' : 'X';
\r
3167 if (!empty($this->datetime)) return 'T';
\r
3171 if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
\r
3176 function _close() {}
\r
3179 * set/returns the current recordset page when paginating
\r
3181 function AbsolutePage($page=-1)
\r
3183 if ($page != -1) $this->_currentPage = $page;
\r
3184 return $this->_currentPage;
\r
3188 * set/returns the status of the atFirstPage flag when paginating
\r
3190 function AtFirstPage($status=false)
\r
3192 if ($status != false) $this->_atFirstPage = $status;
\r
3193 return $this->_atFirstPage;
\r
3196 function LastPageNo($page = false)
\r
3198 if ($page != false) $this->_lastPageNo = $page;
\r
3199 return $this->_lastPageNo;
\r
3203 * set/returns the status of the atLastPage flag when paginating
\r
3205 function AtLastPage($status=false)
\r
3207 if ($status != false) $this->_atLastPage = $status;
\r
3208 return $this->_atLastPage;
\r
3211 } // end class ADORecordSet
\r
3213 //==============================================================================================
\r
3214 // CLASS ADORecordSet_array
\r
3215 //==============================================================================================
\r
3218 * This class encapsulates the concept of a recordset created in memory
\r
3219 * as an array. This is useful for the creation of cached recordsets.
\r
3221 * Note that the constructor is different from the standard ADORecordSet
\r
3224 class ADORecordSet_array extends ADORecordSet
\r
3226 var $databaseType = 'array';
\r
3228 var $_array; // holds the 2-dimensional data array
\r
3229 var $_types; // the array of types of each column (C B I L M)
\r
3230 var $_colnames; // names of each column in array
\r
3231 var $_skiprow1; // skip 1st row because it holds column names
\r
3232 var $_fieldarr; // holds array of field objects
\r
3233 var $canSeek = true;
\r
3234 var $affectedrows = false;
\r
3235 var $insertid = false;
\r
3237 var $compat = false;
\r
3242 function ADORecordSet_array($fakeid=1)
\r
3244 global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
\r
3246 // fetch() on EOF does not delete $this->fields
\r
3247 $this->compat = !empty($ADODB_COMPAT_FETCH);
\r
3248 $this->ADORecordSet($fakeid); // fake queryID
\r
3249 $this->fetchMode = $ADODB_FETCH_MODE;
\r
3254 * Setup the array.
\r
3256 * @param array is a 2-dimensional array holding the data.
\r
3257 * The first row should hold the column names
\r
3258 * unless paramter $colnames is used.
\r
3259 * @param typearr holds an array of types. These are the same types
\r
3260 * used in MetaTypes (C,B,L,I,N).
\r
3261 * @param [colnames] array of column names. If set, then the first row of
\r
3262 * $array should not hold the column names.
\r
3264 function InitArray($array,$typearr,$colnames=false)
\r
3266 $this->_array = $array;
\r
3267 $this->_types = $typearr;
\r
3269 $this->_skiprow1 = false;
\r
3270 $this->_colnames = $colnames;
\r
3272 $this->_skiprow1 = true;
\r
3273 $this->_colnames = $array[0];
\r
3278 * Setup the Array and datatype file objects
\r
3280 * @param array is a 2-dimensional array holding the data.
\r
3281 * The first row should hold the column names
\r
3282 * unless paramter $colnames is used.
\r
3283 * @param fieldarr holds an array of ADOFieldObject's.
\r
3285 function InitArrayFields(&$array,&$fieldarr)
\r
3287 $this->_array =& $array;
\r
3288 $this->_skiprow1= false;
\r
3290 $this->_fieldobjects =& $fieldarr;
\r
3295 function &GetArray($nRows=-1)
\r
3297 if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
\r
3298 return $this->_array;
\r
3300 $arr =& ADORecordSet::GetArray($nRows);
\r
3305 function _initrs()
\r
3307 $this->_numOfRows = sizeof($this->_array);
\r
3308 if ($this->_skiprow1) $this->_numOfRows -= 1;
\r
3310 $this->_numOfFields =(isset($this->_fieldobjects)) ?
\r
3311 sizeof($this->_fieldobjects):sizeof($this->_types);
\r
3314 /* Use associative array to get fields array */
\r
3315 function Fields($colname)
\r
3317 if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
\r
3319 if (!$this->bind) {
\r
3320 $this->bind = array();
\r
3321 for ($i=0; $i < $this->_numOfFields; $i++) {
\r
3322 $o = $this->FetchField($i);
\r
3323 $this->bind[strtoupper($o->name)] = $i;
\r
3326 return $this->fields[$this->bind[strtoupper($colname)]];
\r
3329 function &FetchField($fieldOffset = -1)
\r
3331 if (isset($this->_fieldobjects)) {
\r
3332 return $this->_fieldobjects[$fieldOffset];
\r
3334 $o = new ADOFieldObject();
\r
3335 $o->name = $this->_colnames[$fieldOffset];
\r
3336 $o->type = $this->_types[$fieldOffset];
\r
3337 $o->max_length = -1; // length not known
\r
3342 function _seek($row)
\r
3344 if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
\r
3345 $this->_currentRow = $row;
\r
3346 if ($this->_skiprow1) $row += 1;
\r
3347 $this->fields = $this->_array[$row];
\r
3353 function MoveNext()
\r
3355 if (!$this->EOF) {
\r
3356 $this->_currentRow++;
\r
3358 $pos = $this->_currentRow;
\r
3360 if ($this->_numOfRows <= $pos) {
\r
3361 if (!$this->compat) $this->fields = false;
\r
3363 if ($this->_skiprow1) $pos += 1;
\r
3364 $this->fields = $this->_array[$pos];
\r
3367 $this->EOF = true;
\r
3375 $pos = $this->_currentRow;
\r
3377 if ($this->_numOfRows <= $pos) {
\r
3378 if (!$this->compat) $this->fields = false;
\r
3381 if ($this->_skiprow1) $pos += 1;
\r
3382 $this->fields = $this->_array[$pos];
\r
3386 function _close()
\r
3391 } // ADORecordSet_array
\r
3393 //==============================================================================================
\r
3394 // HELPER FUNCTIONS
\r
3395 //==============================================================================================
\r
3398 * Synonym for ADOLoadCode. Private function. Do not use.
\r
3402 function ADOLoadDB($dbType)
\r
3404 return ADOLoadCode($dbType);
\r
3408 * Load the code for a specific database driver. Private function. Do not use.
\r
3410 function ADOLoadCode($dbType)
\r
3412 global $ADODB_LASTDB;
\r
3414 if (!$dbType) return false;
\r
3415 $db = strtolower($dbType);
\r
3417 case 'maxsql': $db = 'mysqlt'; break;
\r
3419 case 'pgsql': $db = 'postgres7'; break;
\r
3421 @include_once(ADODB_DIR."/drivers/adodb-".$db.".inc.php");
\r
3422 $ADODB_LASTDB = $db;
\r
3424 $ok = class_exists("ADODB_" . $db);
\r
3425 if ($ok) return $db;
\r
3427 $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
\r
3428 if (!file_exists($file)) ADOConnection::outp("Missing file: $file");
\r
3429 else ADOConnection::outp("Syntax error in file: $file");
\r
3434 * synonym for ADONewConnection for people like me who cannot remember the correct name
\r
3436 function &NewADOConnection($db='')
\r
3438 $tmp =& ADONewConnection($db);
\r
3443 * Instantiate a new Connection class for a specific database driver.
\r
3445 * @param [db] is the database Connection object to create. If undefined,
\r
3446 * use the last database driver that was loaded by ADOLoadCode().
\r
3448 * @return the freshly created instance of the Connection class.
\r
3450 function &ADONewConnection($db='')
\r
3452 GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
\r
3454 if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
\r
3455 $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
\r
3457 if (!empty($ADODB_NEWCONNECTION)) {
\r
3458 $obj = $ADODB_NEWCONNECTION($db);
\r
3460 if ($errorfn) $obj->raiseErrorFn = $errorfn;
\r
3465 if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
\r
3466 if (empty($db)) $db = $ADODB_LASTDB;
\r
3468 if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
\r
3474 $errorfn('ADONewConnection', 'ADONewConnection', -998,
\r
3475 "could not load the database driver for '$db",
\r
3476 $db,false,$ignore);
\r
3478 ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
\r
3483 $cls = 'ADODB_'.$db;
\r
3484 if (!class_exists($cls)) {
\r
3485 adodb_backtrace();
\r
3489 $obj =& new $cls();
\r
3490 if ($errorfn) $obj->raiseErrorFn = $errorfn;
\r
3495 // $perf == true means called by NewPerfMonitor()
\r
3496 function _adodb_getdriver($provider,$drivername,$perf=false)
\r
3498 if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado')
\r
3499 $drivername = $provider;
\r
3501 if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5);
\r
3502 else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4);
\r
3504 switch($drivername) {
\r
3505 case 'oracle': $drivername = 'oci8';break;
\r
3506 //case 'sybase': $drivername = 'mssql';break;
\r
3508 if ($perf) $drivername = '';
\r
3513 $drivername = 'generic';
\r
3518 return $drivername;
\r
3521 function &NewPerfMonitor(&$conn)
\r
3523 $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
\r
3524 if (!$drivername || $drivername == 'generic') return false;
\r
3525 include_once(ADODB_DIR.'/adodb-perf.inc.php');
\r
3526 @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
\r
3527 $class = "Perf_$drivername";
\r
3528 if (!class_exists($class)) return false;
\r
3529 $perf =& new $class($conn);
\r
3534 function &NewDataDictionary(&$conn)
\r
3536 $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
\r
3538 include_once(ADODB_DIR.'/adodb-lib.inc.php');
\r
3539 include_once(ADODB_DIR.'/adodb-datadict.inc.php');
\r
3540 $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
\r
3542 if (!file_exists($path)) {
\r
3543 ADOConnection::outp("Database driver '$path' not available");
\r
3546 include_once($path);
\r
3547 $class = "ADODB2_$drivername";
\r
3548 $dict =& new $class();
\r
3549 $dict->dataProvider = $conn->dataProvider;
\r
3550 $dict->connection = &$conn;
\r
3551 $dict->upperName = strtoupper($drivername);
\r
3552 $dict->quote = $conn->nameQuote;
\r
3553 if (is_resource($conn->_connectionID))
\r
3554 $dict->serverInfo = $conn->ServerInfo();
\r
3561 * Save a file $filename and its $contents (normally for caching) with file locking
\r
3563 function adodb_write_file($filename, $contents,$debug=false)
\r
3565 # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows
\r
3566 # So to simulate locking, we assume that rename is an atomic operation.
\r
3567 # First we delete $filename, then we create a $tempfile write to it and
\r
3568 # rename to the desired $filename. If the rename works, then we successfully
\r
3569 # modified the file exclusively.
\r
3570 # What a stupid need - having to simulate locking.
\r
3572 # 1. $tempfile name is not unique -- very very low
\r
3573 # 2. unlink($filename) fails -- ok, rename will fail
\r
3574 # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs
\r
3575 # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated
\r
3576 if (strncmp(PHP_OS,'WIN',3) === 0) {
\r
3577 // skip the decimal place
\r
3578 $mtime = substr(str_replace(' ','_',microtime()),2);
\r
3579 // getmypid() actually returns 0 on Win98 - never mind!
\r
3580 $tmpname = $filename.uniqid($mtime).getmypid();
\r
3581 if (!($fd = fopen($tmpname,'a'))) return false;
\r
3582 $ok = ftruncate($fd,0);
\r
3583 if (!fwrite($fd,$contents)) $ok = false;
\r
3585 chmod($tmpname,0644);
\r
3586 // the tricky moment
\r
3587 @unlink($filename);
\r
3588 if (!@rename($tmpname,$filename)) {
\r
3593 if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));
\r
3597 if (!($fd = fopen($filename, 'a'))) return false;
\r
3598 if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {
\r
3599 $ok = fwrite( $fd, $contents );
\r
3601 chmod($filename,0644);
\r
3604 if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");
\r
3612 Perform a print_r, with pre tags for better formatting.
\r
3614 function adodb_pr($var)
\r
3616 if (isset($_SERVER['HTTP_USER_AGENT'])) {
\r
3617 echo " <pre>\n";print_r($var);echo "</pre>\n";
\r
3623 Perform a stack-crawl and pretty print it.
\r
3625 @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
\r
3626 @param levels Number of levels to display
\r
3628 function adodb_backtrace($printOrArr=true,$levels=9999)
\r
3631 if (PHPVERSION() < 4.3) return;
\r
3633 $html = (isset($_SERVER['HTTP_USER_AGENT']));
\r
3634 $fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
\r
3638 $s = ($html) ? '<pre align=left>' : '';
\r
3640 if (is_array($printOrArr)) $traceArr = $printOrArr;
\r
3641 else $traceArr = debug_backtrace();
\r
3642 array_shift($traceArr);
\r
3643 $tabs = sizeof($traceArr)-1;
\r
3645 foreach ($traceArr as $arr) {
\r
3647 if ($levels < 0) break;
\r
3650 for ($i=0; $i < $tabs; $i++) $s .= ($html) ? ' ' : "\t";
\r
3652 if ($html) $s .= '<font face="Courier New,Courier">';
\r
3653 if (isset($arr['class'])) $s .= $arr['class'].'.';
\r
3654 if (isset($arr['args']))
\r
3655 foreach($arr['args'] as $v) {
\r
3656 if (is_null($v)) $args[] = 'null';
\r
3657 else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
\r
3658 else if (is_object($v)) $args[] = 'Object:'.get_class($v);
\r
3659 else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
\r
3661 $v = (string) @$v;
\r
3662 $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
\r
3663 if (strlen($v) > $MAXSTRLEN) $str .= '...';
\r
3667 $s .= $arr['function'].'('.implode(', ',$args).')';
\r
3670 $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
\r
3674 if ($html) $s .= '</pre>';
\r
3675 if ($printOrArr) print $s;
\r