]> git.mjollnir.org Git - moodle.git/commitdiff
Latest version ADOdb 4.20
authormoodler <moodler>
Sun, 7 Mar 2004 02:33:26 +0000 (02:33 +0000)
committermoodler <moodler>
Sun, 7 Mar 2004 02:33:26 +0000 (02:33 +0000)
99 files changed:
lib/adodb/adodb-csvlib.inc.php
lib/adodb/adodb-datadict.inc.php
lib/adodb/adodb-error.inc.php
lib/adodb/adodb-errorhandler.inc.php
lib/adodb/adodb-errorpear.inc.php
lib/adodb/adodb-exceptions.inc.php
lib/adodb/adodb-iterator.inc.php
lib/adodb/adodb-lib.inc.php
lib/adodb/adodb-pager.inc.php
lib/adodb/adodb-pear.inc.php
lib/adodb/adodb-perf.inc.php
lib/adodb/adodb-php4.inc.php
lib/adodb/adodb-xmlschema.inc.php
lib/adodb/adodb.inc.php
lib/adodb/datadict/datadict-access.inc.php
lib/adodb/datadict/datadict-db2.inc.php
lib/adodb/datadict/datadict-generic.inc.php
lib/adodb/datadict/datadict-ibase.inc.php
lib/adodb/datadict/datadict-informix.inc.php
lib/adodb/datadict/datadict-mssql.inc.php
lib/adodb/datadict/datadict-mysql.inc.php
lib/adodb/datadict/datadict-oci8.inc.php
lib/adodb/datadict/datadict-postgres.inc.php
lib/adodb/datadict/datadict-sybase.inc.php
lib/adodb/docs-adodb.htm
lib/adodb/docs-datadict.htm
lib/adodb/docs-perf.htm
lib/adodb/docs-session.htm
lib/adodb/drivers/adodb-access.inc.php
lib/adodb/drivers/adodb-ado.inc.php
lib/adodb/drivers/adodb-ado_access.inc.php
lib/adodb/drivers/adodb-ado_mssql.inc.php
lib/adodb/drivers/adodb-borland_ibase.inc.php
lib/adodb/drivers/adodb-csv.inc.php
lib/adodb/drivers/adodb-db2.inc.php
lib/adodb/drivers/adodb-fbsql.inc.php
lib/adodb/drivers/adodb-firebird.inc.php
lib/adodb/drivers/adodb-ibase.inc.php
lib/adodb/drivers/adodb-informix.inc.php
lib/adodb/drivers/adodb-informix72.inc.php
lib/adodb/drivers/adodb-mssql.inc.php
lib/adodb/drivers/adodb-mssqlpo.inc.php
lib/adodb/drivers/adodb-mysql.inc.php
lib/adodb/drivers/adodb-mysqli.inc.php
lib/adodb/drivers/adodb-mysqlt.inc.php
lib/adodb/drivers/adodb-oci8.inc.php
lib/adodb/drivers/adodb-oci805.inc.php
lib/adodb/drivers/adodb-oci8po.inc.php
lib/adodb/drivers/adodb-odbc.inc.php
lib/adodb/drivers/adodb-odbc_mssql.inc.php
lib/adodb/drivers/adodb-odbc_oracle.inc.php
lib/adodb/drivers/adodb-oracle.inc.php
lib/adodb/drivers/adodb-postgres.inc.php
lib/adodb/drivers/adodb-postgres64.inc.php
lib/adodb/drivers/adodb-postgres7.inc.php
lib/adodb/drivers/adodb-proxy.inc.php
lib/adodb/drivers/adodb-sapdb.inc.php
lib/adodb/drivers/adodb-sqlanywhere.inc.php
lib/adodb/drivers/adodb-sqlite.inc.php
lib/adodb/drivers/adodb-sybase.inc.php
lib/adodb/drivers/adodb-vfp.inc.php
lib/adodb/license.txt
lib/adodb/perf/perf-db2.inc.php
lib/adodb/perf/perf-informix.inc.php
lib/adodb/perf/perf-mssql.inc.php
lib/adodb/perf/perf-mysql.inc.php
lib/adodb/perf/perf-oci8.inc.php
lib/adodb/perf/perf-postgres.inc.php
lib/adodb/pivottable.inc.php
lib/adodb/rsfilter.inc.php
lib/adodb/server.php
lib/adodb/tests/benchmark.php
lib/adodb/tests/client.php
lib/adodb/tests/test-datadict.php
lib/adodb/tests/test-pgblob.php
lib/adodb/tests/test-php5.php
lib/adodb/tests/test-xmlschema.php
lib/adodb/tests/test.php
lib/adodb/tests/test2.php
lib/adodb/tests/test3.php
lib/adodb/tests/test4.php
lib/adodb/tests/test5.php
lib/adodb/tests/testcache.php
lib/adodb/tests/testdatabases.inc.php
lib/adodb/tests/testgenid.php
lib/adodb/tests/testmssql.php
lib/adodb/tests/testoci8.php
lib/adodb/tests/testoci8cursor.php
lib/adodb/tests/testpaging.php
lib/adodb/tests/testpear.php
lib/adodb/tests/testsessions.php
lib/adodb/tests/tmssql.php
lib/adodb/tests/xmlschema.xml
lib/adodb/toexport.inc.php
lib/adodb/tohtml.inc.php
lib/adodb/tute.htm
lib/adodb/xmlschema.dtd [new file with mode: 0644]
lib/adodb/xsl/convert-0.1-0.2.xsl [new file with mode: 0644]
lib/adodb/xsl/convert-0.2-0.1.xsl [new file with mode: 0644]

index 37c46794cebed0c916f06158fa139331d05642e5..ba0697ab83e20add813b76e8a553a56d1a5f8cd4 100644 (file)
-<?php\r
-global $ADODB_INCLUDED_CSV;\r
-$ADODB_INCLUDED_CSV = 1;\r
-\r
-/* \r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. See License.txt. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Library for CSV serialization. This is used by the csv/proxy driver and is the \r
-  CacheExecute() serialization format. \r
-  \r
-  ==== NOTE ====\r
-  Format documented at http://php.weblogs.com/ADODB_CSV\r
-  ==============\r
-*/\r
-\r
-       /**\r
-        * convert a recordset into special format\r
-        *\r
-        * @param rs    the recordset\r
-        *\r
-        * @return      the CSV formated data\r
-        */\r
-       function _rs2serialize(&$rs,$conn=false,$sql='')\r
-       {\r
-               $max = ($rs) ? $rs->FieldCount() : 0;\r
-               \r
-               if ($sql) $sql = urlencode($sql);\r
-               // metadata setup\r
-               \r
-               if ($max <= 0 || $rs->dataProvider == 'empty') { // is insert/update/delete\r
-                       if (is_object($conn)) {\r
-                               $sql .= ','.$conn->Affected_Rows();\r
-                               $sql .= ','.$conn->Insert_ID();\r
-                       } else\r
-                               $sql .= ',,';\r
-                       \r
-                       $text = "====-1,0,$sql\n";\r
-                       return $text;\r
-               } else {\r
-                       $tt = ($rs->timeCreated) ? $rs->timeCreated : time();\r
-                       $line = "====0,$tt,$sql\n";\r
-               }\r
-               // column definitions\r
-               for($i=0; $i < $max; $i++) {\r
-                       $o = $rs->FetchField($i);\r
-                       $line .= urlencode($o->name).':'.$rs->MetaType($o->type,$o->max_length,$o).":$o->max_length,";\r
-               }\r
-               $text = substr($line,0,strlen($line)-1)."\n";\r
-               \r
-               \r
-               // get data\r
-               if ($rs->databaseType == 'array') {\r
-                       $text .= serialize($rs->_array);\r
-               } else {\r
-                       $rows = array();\r
-                       while (!$rs->EOF) {     \r
-                               $rows[] = $rs->fields;\r
-                               $rs->MoveNext();\r
-                       } \r
-                       $text .= serialize($rows);\r
-               }\r
-               $rs->MoveFirst();\r
-               return $text;\r
-       }\r
-\r
-       \r
-/**\r
-* Open CSV file and convert it into Data. \r
-*\r
-* @param url           file/ftp/http url\r
-* @param err           returns the error message\r
-* @param timeout       dispose if recordset has been alive for $timeout secs\r
-*\r
-* @return              recordset, or false if error occured. If no\r
-*                      error occurred in sql INSERT/UPDATE/DELETE, \r
-*                      empty recordset is returned\r
-*/\r
-       function &csv2rs($url,&$err,$timeout=0)\r
-       {\r
-               $err = false;\r
-               $fp = @fopen($url,'r');\r
-               if (!$fp) {\r
-                       $err = $url.' file/URL not found';\r
-                       return false;\r
-               }\r
-               flock($fp, LOCK_SH);\r
-               $arr = array();\r
-               $ttl = 0;\r
-               \r
-               if ($meta = fgetcsv ($fp, 32000, ",")) {\r
-                       // check if error message\r
-                       if (substr($meta[0],0,4) === '****') {\r
-                               $err = trim(substr($meta[0],4,1024));\r
-                               fclose($fp);\r
-                               return false;\r
-                       }\r
-                       // check for meta data\r
-                       // $meta[0] is -1 means return an empty recordset\r
-                       // $meta[1] contains a time \r
-       \r
-                       if (substr($meta[0],0,4) ===  '====') {\r
-                       \r
-                               if ($meta[0] == "====-1") {\r
-                                       if (sizeof($meta) < 5) {\r
-                                               $err = "Corrupt first line for format -1";\r
-                                               fclose($fp);\r
-                                               return false;\r
-                                       }\r
-                                       fclose($fp);\r
-                                       \r
-                                       if ($timeout > 0) {\r
-                                               $err = " Illegal Timeout $timeout ";\r
-                                               return false;\r
-                                       }\r
-                                       $rs->fields = array();\r
-                                       $rs->timeCreated = $meta[1];\r
-                                       $rs = new ADORecordSet($val=true);\r
-                                       $rs->EOF = true;\r
-                                       $rs->_numOfFields=0;\r
-                                       $rs->sql = urldecode($meta[2]);\r
-                                       $rs->affectedrows = (integer)$meta[3];\r
-                                       $rs->insertid = $meta[4];       \r
-                                       return $rs;\r
-                               }\r
-                       # Under high volume loads, we want only 1 thread/process to _write_file\r
-                       # so that we don't have 50 processes queueing to write the same data.\r
-                       # Would require probabilistic blocking write \r
-                       #\r
-                       # -2 sec before timeout, give processes 1/16 chance of writing to file with blocking io\r
-                       # -1 sec after timeout give processes 1/4 chance of writing with blocking\r
-                       # +0 sec after timeout, give processes 100% chance writing with blocking\r
-                               if (sizeof($meta) > 1) {\r
-                                       if($timeout >0){ \r
-                                               $tdiff = $meta[1]+$timeout - time();\r
-                                               if ($tdiff <= 2) {\r
-                                                       switch($tdiff) {\r
-                                                       case 2: \r
-                                                               if ((rand() & 15) == 0) {\r
-                                                                       fclose($fp);\r
-                                                                       $err = "Timeout 2";\r
-                                                                       return false;\r
-                                                               }\r
-                                                               break;\r
-                                                       case 1:\r
-                                                               if ((rand() & 3) == 0) {\r
-                                                                       fclose($fp);\r
-                                                                       $err = "Timeout 1";\r
-                                                                       return false;\r
-                                                               }\r
-                                                               break;\r
-                                                       default: \r
-                                                               fclose($fp);\r
-                                                               $err = "Timeout 0";\r
-                                                               return false;\r
-                                                       } // switch\r
-                                                       \r
-                                               } // if check flush cache\r
-                                       }// (timeout>0)\r
-                                       $ttl = $meta[1];\r
-                               }\r
-                               $meta = false;\r
-                               $meta = fgetcsv($fp, 16000, ",");\r
-                               if (!$meta) {\r
-                                       fclose($fp);\r
-                                       $err = "Unexpected EOF 1";\r
-                                       return false;\r
-                               }\r
-                       }\r
-\r
-                       // Get Column definitions\r
-                       $flds = array();\r
-                       foreach($meta as $o) {\r
-                               $o2 = explode(':',$o);\r
-                               if (sizeof($o2)!=3) {\r
-                                       $arr[] = $meta;\r
-                                       $flds = false;\r
-                                       break;\r
-                               }\r
-                               $fld = new ADOFieldObject();\r
-                               $fld->name = urldecode($o2[0]);\r
-                               $fld->type = $o2[1];\r
-                               $fld->max_length = $o2[2];\r
-                               $flds[] = $fld;\r
-                       }\r
-               } else {\r
-                       fclose($fp);\r
-                       $err = "Recordset had unexpected EOF 2";\r
-                       return false;\r
-               }\r
-               \r
-               // slurp in the data\r
-               $MAXSIZE = 128000;\r
-               \r
-               $text = '';\r
-               while ($txt = fread($fp,$MAXSIZE)) {\r
-                       $text .= $txt;\r
-               }\r
-                       \r
-               fclose($fp);\r
-               $arr = @unserialize($text);\r
-               //var_dump($arr);\r
-               if (!is_array($arr)) {\r
-                       $err = "Recordset had unexpected EOF (in serialized recordset)";\r
-                       if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!";\r
-                       return false;\r
-               }\r
-               $rs = new ADORecordSet_array();\r
-               $rs->timeCreated = $ttl;\r
-               $rs->InitArrayFields($arr,$flds);\r
-               return $rs;\r
-       }\r
+<?php
+global $ADODB_INCLUDED_CSV;
+$ADODB_INCLUDED_CSV = 1;
+
+/* 
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Library for CSV serialization. This is used by the csv/proxy driver and is the 
+  CacheExecute() serialization format. 
+  
+  ==== NOTE ====
+  Format documented at http://php.weblogs.com/ADODB_CSV
+  ==============
+*/
+
+       /**
+        * convert a recordset into special format
+        *
+        * @param rs    the recordset
+        *
+        * @return      the CSV formated data
+        */
+       function _rs2serialize(&$rs,$conn=false,$sql='')
+       {
+               $max = ($rs) ? $rs->FieldCount() : 0;
+               
+               if ($sql) $sql = urlencode($sql);
+               // metadata setup
+               
+               if ($max <= 0 || $rs->dataProvider == 'empty') { // is insert/update/delete
+                       if (is_object($conn)) {
+                               $sql .= ','.$conn->Affected_Rows();
+                               $sql .= ','.$conn->Insert_ID();
+                       } else
+                               $sql .= ',,';
+                       
+                       $text = "====-1,0,$sql\n";
+                       return $text;
+               } else {
+                       $tt = ($rs->timeCreated) ? $rs->timeCreated : time();
+                       $line = "====0,$tt,$sql\n";
+               }
+               // column definitions
+               for($i=0; $i < $max; $i++) {
+                       $o = $rs->FetchField($i);
+                       $line .= urlencode($o->name).':'.$rs->MetaType($o->type,$o->max_length,$o).":$o->max_length,";
+               }
+               $text = substr($line,0,strlen($line)-1)."\n";
+               
+               
+               // get data
+               if ($rs->databaseType == 'array') {
+                       $text .= serialize($rs->_array);
+               } else {
+                       $rows = array();
+                       while (!$rs->EOF) {     
+                               $rows[] = $rs->fields;
+                               $rs->MoveNext();
+                       } 
+                       $text .= serialize($rows);
+               }
+               $rs->MoveFirst();
+               return $text;
+       }
+
+       
+/**
+* Open CSV file and convert it into Data. 
+*
+* @param url           file/ftp/http url
+* @param err           returns the error message
+* @param timeout       dispose if recordset has been alive for $timeout secs
+*
+* @return              recordset, or false if error occured. If no
+*                      error occurred in sql INSERT/UPDATE/DELETE, 
+*                      empty recordset is returned
+*/
+       function &csv2rs($url,&$err,$timeout=0)
+       {
+               $err = false;
+               $fp = @fopen($url,'r');
+               if (!$fp) {
+                       $err = $url.' file/URL not found';
+                       return false;
+               }
+               flock($fp, LOCK_SH);
+               $arr = array();
+               $ttl = 0;
+               
+               if ($meta = fgetcsv ($fp, 32000, ",")) {
+                       // check if error message
+                       if (substr($meta[0],0,4) === '****') {
+                               $err = trim(substr($meta[0],4,1024));
+                               fclose($fp);
+                               return false;
+                       }
+                       // check for meta data
+                       // $meta[0] is -1 means return an empty recordset
+                       // $meta[1] contains a time 
+       
+                       if (substr($meta[0],0,4) ===  '====') {
+                       
+                               if ($meta[0] == "====-1") {
+                                       if (sizeof($meta) < 5) {
+                                               $err = "Corrupt first line for format -1";
+                                               fclose($fp);
+                                               return false;
+                                       }
+                                       fclose($fp);
+                                       
+                                       if ($timeout > 0) {
+                                               $err = " Illegal Timeout $timeout ";
+                                               return false;
+                                       }
+                                       $rs->fields = array();
+                                       $rs->timeCreated = $meta[1];
+                                       $rs = new ADORecordSet($val=true);
+                                       $rs->EOF = true;
+                                       $rs->_numOfFields=0;
+                                       $rs->sql = urldecode($meta[2]);
+                                       $rs->affectedrows = (integer)$meta[3];
+                                       $rs->insertid = $meta[4];       
+                                       return $rs;
+                               }
+                       # Under high volume loads, we want only 1 thread/process to _write_file
+                       # so that we don't have 50 processes queueing to write the same data.
+                       # Would require probabilistic blocking write 
+                       #
+                       # -2 sec before timeout, give processes 1/16 chance of writing to file with blocking io
+                       # -1 sec after timeout give processes 1/4 chance of writing with blocking
+                       # +0 sec after timeout, give processes 100% chance writing with blocking
+                               if (sizeof($meta) > 1) {
+                                       if($timeout >0){ 
+                                               $tdiff = $meta[1]+$timeout - time();
+                                               if ($tdiff <= 2) {
+                                                       switch($tdiff) {
+                                                       case 2: 
+                                                               if ((rand() & 15) == 0) {
+                                                                       fclose($fp);
+                                                                       $err = "Timeout 2";
+                                                                       return false;
+                                                               }
+                                                               break;
+                                                       case 1:
+                                                               if ((rand() & 3) == 0) {
+                                                                       fclose($fp);
+                                                                       $err = "Timeout 1";
+                                                                       return false;
+                                                               }
+                                                               break;
+                                                       default: 
+                                                               fclose($fp);
+                                                               $err = "Timeout 0";
+                                                               return false;
+                                                       } // switch
+                                                       
+                                               } // if check flush cache
+                                       }// (timeout>0)
+                                       $ttl = $meta[1];
+                               }
+                               $meta = false;
+                               $meta = fgetcsv($fp, 16000, ",");
+                               if (!$meta) {
+                                       fclose($fp);
+                                       $err = "Unexpected EOF 1";
+                                       return false;
+                               }
+                       }
+
+                       // Get Column definitions
+                       $flds = array();
+                       foreach($meta as $o) {
+                               $o2 = explode(':',$o);
+                               if (sizeof($o2)!=3) {
+                                       $arr[] = $meta;
+                                       $flds = false;
+                                       break;
+                               }
+                               $fld = new ADOFieldObject();
+                               $fld->name = urldecode($o2[0]);
+                               $fld->type = $o2[1];
+                               $fld->max_length = $o2[2];
+                               $flds[] = $fld;
+                       }
+               } else {
+                       fclose($fp);
+                       $err = "Recordset had unexpected EOF 2";
+                       return false;
+               }
+               
+               // slurp in the data
+               $MAXSIZE = 128000;
+               
+               $text = '';
+               while ($txt = fread($fp,$MAXSIZE)) {
+                       $text .= $txt;
+               }
+                       
+               fclose($fp);
+               $arr = @unserialize($text);
+               //var_dump($arr);
+               if (!is_array($arr)) {
+                       $err = "Recordset had unexpected EOF (in serialized recordset)";
+                       if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!";
+                       return false;
+               }
+               $rs = new ADORecordSet_array();
+               $rs->timeCreated = $ttl;
+               $rs->InitArrayFields($arr,$flds);
+               return $rs;
+       }
 ?>
\ No newline at end of file
index db9c2016dfa7a6a3d91f1e3e8010a6ad0d1196d1..1959de22f4ebd3bc8170ddfd73010c5c30ce16aa 100644 (file)
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-       DOCUMENTATION:\r
-       \r
-               See adodb/tests/test-datadict.php for docs and examples.\r
-*/\r
-\r
-/*\r
-       Test script for parser\r
-*/\r
-function Lens_ParseTest()\r
-{\r
-$str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0";\r
-print "<p>$str</p>";\r
-$a= Lens_ParseArgs($str);\r
-print "<pre>";\r
-print_r($a);\r
-print "</pre>";\r
-}\r
-\r
-if (!function_exists('ctype_alnum')) {\r
-       function ctype_alnum($text) {\r
-               return preg_match('/^[a-z0-9]*$/i', $text);\r
-       }\r
-}\r
-\r
-//Lens_ParseTest();\r
-\r
-/**\r
-       Parse arguments, treat "text" (text) and 'text' as quotation marks.\r
-       To escape, use "" or '' or ))\r
-       \r
-       Will read in "abc def" sans quotes, as: abc def\r
-       Same with 'abc def'.\r
-       However if `abc def`, then will read in as `abc def`\r
-       \r
-       @param endstmtchar    Character that indicates end of statement\r
-       @param tokenchars     Include the following characters in tokens apart from A-Z and 0-9 \r
-       @returns 2 dimensional array containing parsed tokens.\r
-*/\r
-function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')\r
-{\r
-       $pos = 0;\r
-       $intoken = false;\r
-       $stmtno = 0;\r
-       $endquote = false;\r
-       $tokens = array();\r
-       $tokens[$stmtno] = array();\r
-       $max = strlen($args);\r
-       $quoted = false;\r
-       \r
-       while ($pos < $max) {\r
-               $ch = substr($args,$pos,1);\r
-               switch($ch) {\r
-               case ' ':\r
-               case "\t":\r
-               case "\n":\r
-               case "\r":\r
-                       if (!$quoted) {\r
-                               if ($intoken) {\r
-                                       $intoken = false;\r
-                                       $tokens[$stmtno][] = implode('',$tokarr);\r
-                               }\r
-                               break;\r
-                       }\r
-                       \r
-                       $tokarr[] = $ch;\r
-                       break;\r
-               \r
-               case '`':\r
-                       if ($intoken) $tokarr[] = $ch;\r
-               case '(':\r
-               case ')':       \r
-               case '"':\r
-               case "'":\r
-                       \r
-                       if ($intoken) {\r
-                               if (empty($endquote)) {\r
-                                       $tokens[$stmtno][] = implode('',$tokarr);\r
-                                       if ($ch == '(') $endquote = ')';\r
-                                       else $endquote = $ch;\r
-                                       $quoted = true;\r
-                                       $intoken = true;\r
-                                       $tokarr = array();\r
-                               } else if ($endquote == $ch) {\r
-                                       $ch2 = substr($args,$pos+1,1);\r
-                                       if ($ch2 == $endquote) {\r
-                                               $pos += 1;\r
-                                               $tokarr[] = $ch2;\r
-                                       } else {\r
-                                               $quoted = false;\r
-                                               $intoken = false;\r
-                                               $tokens[$stmtno][] = implode('',$tokarr);\r
-                                               $endquote = '';\r
-                                       }\r
-                               } else\r
-                                       $tokarr[] = $ch;\r
-                                       \r
-                       }else {\r
-                       \r
-                               if ($ch == '(') $endquote = ')';\r
-                               else $endquote = $ch;\r
-                               $quoted = true;\r
-                               $intoken = true;\r
-                               $tokarr = array();\r
-                               if ($ch == '`') $tokarr[] = '`';\r
-                       }\r
-                       break;\r
-                       \r
-               default:\r
-                       \r
-                       if (!$intoken) {\r
-                               if ($ch == $endstmtchar) {\r
-                                       $stmtno += 1;\r
-                                       $tokens[$stmtno] = array();\r
-                                       break;\r
-                               }\r
-                       \r
-                               $intoken = true;\r
-                               $quoted = false;\r
-                               $endquote = false;\r
-                               $tokarr = array();\r
-       \r
-                       }\r
-                       \r
-                       if ($quoted) $tokarr[] = $ch;\r
-                       else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;\r
-                       else {\r
-                               if ($ch == $endstmtchar) {                      \r
-                                       $tokens[$stmtno][] = implode('',$tokarr);\r
-                                       $stmtno += 1;\r
-                                       $tokens[$stmtno] = array();\r
-                                       $intoken = false;\r
-                                       $tokarr = array();\r
-                                       break;\r
-                               }\r
-                               $tokens[$stmtno][] = implode('',$tokarr);\r
-                               $tokens[$stmtno][] = $ch;\r
-                               $intoken = false;\r
-                       }\r
-               }\r
-               $pos += 1;\r
-       }\r
-       \r
-       return $tokens;\r
-}\r
-\r
-\r
-class ADODB_DataDict {\r
-       var $connection;\r
-       var $debug = false;\r
-       var $dropTable = 'DROP TABLE %s';\r
-       var $dropIndex = 'DROP INDEX %s';\r
-       var $addCol = ' ADD';\r
-       var $alterCol = ' ALTER COLUMN';\r
-       var $dropCol = ' DROP COLUMN';\r
-       var $schema = false;\r
-       var $serverInfo = array();\r
-       var $autoIncrement = false;\r
-       var $dataProvider;\r
-       var $blobSize = 100;    /// any varchar/char field this size or greater is treated as a blob\r
-                                                       /// in other words, we use a text area for editting.\r
-       \r
-       function GetCommentSQL($table,$col)\r
-       {\r
-               return false;\r
-       }\r
-       \r
-       function SetCommentSQL($table,$col,$cmt)\r
-       {\r
-               return false;\r
-       }\r
-       \r
-       function &MetaTables()\r
-       {\r
-               return $this->connection->MetaTables();\r
-       }\r
-       \r
-       function &MetaColumns($tab,$schema=false,$upper=true)\r
-       {\r
-               return $this->connection->MetaColumns($tab,$schema,$upper);\r
-       }\r
-       \r
-       function &MetaPrimaryKeys($tab,$owner=false,$intkey=false)\r
-       {\r
-               return $this->connection->MetaPrimaryKeys($tab.$owner,$intkey);\r
-       }\r
-       \r
-       function &MetaIndexes($table, $primary = false, $owner = false)\r
-       {\r
-               return $this->connection->MetaIndexes($table, $primary, $owner);\r
-       }\r
-       \r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               return ADORecordSet::MetaType($t,$len,$fieldobj);\r
-       }\r
-       \r
-       function NameQuote($name)\r
-       {\r
-               if ( !is_object($this->connection) ) {\r
-                       return $name;\r
-               }\r
-               \r
-               $replace = $this->connection->nameQuote .'$1'. $this->connection->nameQuote;\r
-               return preg_replace('/^`([^`]+)`$/', $replace, $name);\r
-       }\r
-       \r
-       function TableName($name)\r
-       {\r
-               if ( $this->schema ) {\r
-                       return $this->NameQuote($this->schema) .'.'. $this->NameQuote($name);\r
-               }\r
-               return $this->NameQuote($name);\r
-       }\r
-       \r
-       // Executes the sql array returned by GetTableSQL and GetIndexSQL\r
-       function ExecuteSQLArray($sql, $continueOnError = true)\r
-       {\r
-               $rez = 2;\r
-               $conn = &$this->connection;\r
-               $saved = $conn->debug;\r
-               foreach($sql as $line) {\r
-                       \r
-                       if ($this->debug) $conn->debug = true;\r
-                       $ok = $conn->Execute($line);\r
-                       $conn->debug = $saved;\r
-                       if (!$ok) {\r
-                               if ($this->debug) ADOConnection::outp($conn->ErrorMsg());\r
-                               if (!$continueOnError) return 0;\r
-                               $rez = 1;\r
-                       }\r
-               }\r
-               return 2;\r
-       }\r
-       \r
-       /*\r
-               Returns the actual type given a character code.\r
-               \r
-               C:  varchar\r
-               X:  CLOB (character large object) or largest varchar size if CLOB is not supported\r
-               C2: Multibyte varchar\r
-               X2: Multibyte CLOB\r
-               \r
-               B:  BLOB (binary large object)\r
-               \r
-               D:  Date\r
-               T:  Date-time \r
-               L:  Integer field suitable for storing booleans (0 or 1)\r
-               I:  Integer\r
-               F:  Floating point number\r
-               N:  Numeric or decimal number\r
-       */\r
-       \r
-       function ActualType($meta)\r
-       {\r
-               return $meta;\r
-       }\r
-       \r
-       function CreateDatabase($dbname,$options=false)\r
-       {\r
-               $options = $this->_Options($options);\r
-               $sql = array();\r
-               \r
-               $s = 'CREATE DATABASE ' . $this->NameQuote($dbname);\r
-               if (isset($options[$this->upperName]))\r
-                       $s .= ' '.$options[$this->upperName];\r
-               \r
-               $sql[] = $s;\r
-               return $sql;\r
-       }\r
-       \r
-       /*\r
-        Generates the SQL to create index. Returns an array of sql strings.\r
-       */\r
-       function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)\r
-       {\r
-               return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));\r
-       }\r
-       \r
-       function DropIndexSQL ($idxname, $tabname = NULL)\r
-       {\r
-               return array(sprintf($this->dropIndex, $this->NameQuote($idxname)));\r
-       }\r
-       \r
-       function SetSchema($schema)\r
-       {\r
-               $this->schema = $schema;\r
-       }\r
-       \r
-       function AddColumnSQL($tabname, $flds)\r
-       {\r
-               $tabname = $this->TableName ($tabname);\r
-               $sql = array();\r
-               list($lines,$pkey) = $this->_GenFields($flds);\r
-               $alter = 'ALTER TABLE ' . $tabname . ' ' . $this->addCol . ' ';\r
-               foreach($lines as $v) {\r
-                       $sql[] = $alter . $v;\r
-               }\r
-               return $sql;\r
-       }\r
-       \r
-       function AlterColumnSQL($tabname, $flds)\r
-       {\r
-               $tabname = $this->TableName ($tabname);\r
-               $sql = array();\r
-               list($lines,$pkey) = $this->_GenFields($flds);\r
-               $alter = 'ALTER TABLE ' . $tabname . ' ' . $this->alterCol . ' ';\r
-               foreach($lines as $v) {\r
-                       $sql[] = $alter . $v;\r
-               }\r
-               return $sql;\r
-       }\r
-       \r
-       function DropColumnSQL($tabname, $flds)\r
-       {\r
-               $tabname = $this->TableName ($tabname);\r
-               if (!is_array($flds)) $flds = explode(',',$flds);\r
-               $sql = array();\r
-               $alter = 'ALTER TABLE ' . $tabname . ' ' . $this->dropCol . ' ';\r
-               foreach($flds as $v) {\r
-                       $sql[] = $alter . $v;\r
-               }\r
-               return $sql;\r
-       }\r
-       \r
-       function DropTableSQL($tabname)\r
-       {\r
-               return array (sprintf($this->dropTable, $this->TableName($tabname)));\r
-       }\r
-       \r
-       /*\r
-        Generate the SQL to create table. Returns an array of sql strings.\r
-       */\r
-       function CreateTableSQL($tabname, $flds, $tableoptions=false)\r
-       {\r
-               if (!$tableoptions) $tableoptions = array();\r
-               \r
-               list($lines,$pkey) = $this->_GenFields($flds);\r
-               \r
-               $taboptions = $this->_Options($tableoptions);\r
-               $tabname = $this->TableName ($tabname);\r
-               $sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);\r
-               \r
-               $tsql = $this->_Triggers($tabname,$taboptions);\r
-               foreach($tsql as $s) $sql[] = $s;\r
-               \r
-               return $sql;\r
-       }\r
-       \r
-       function _GenFields($flds)\r
-       {\r
-               if (is_string($flds)) {\r
-                       $padding = '     ';\r
-                       $txt = $flds.$padding;\r
-                       $flds = array();\r
-                       $flds0 = Lens_ParseArgs($txt,',');\r
-                       $hasparam = false;\r
-                       foreach($flds0 as $f0) {\r
-                               $f1 = array();\r
-                               foreach($f0 as $token) {\r
-                                       switch (strtoupper($token)) {\r
-                                       case 'CONSTRAINT':\r
-                                       case 'DEFAULT': \r
-                                               $hasparam = $token;\r
-                                               break;\r
-                                       default:\r
-                                               if ($hasparam) $f1[$hasparam] = $token;\r
-                                               else $f1[] = $token;\r
-                                               $hasparam = false;\r
-                                               break;\r
-                                       }\r
-                               }\r
-                               $flds[] = $f1;\r
-                               \r
-                       }\r
-               }\r
-               $this->autoIncrement = false;\r
-               $lines = array();\r
-               $pkey = array();\r
-               foreach($flds as $fld) {\r
-                       $fld = _array_change_key_case($fld);\r
-               \r
-                       $fname = false;\r
-                       $fdefault = false;\r
-                       $fautoinc = false;\r
-                       $ftype = false;\r
-                       $fsize = false;\r
-                       $fprec = false;\r
-                       $fprimary = false;\r
-                       $fnoquote = false;\r
-                       $fdefts = false;\r
-                       $fdefdate = false;\r
-                       $fconstraint = false;\r
-                       $fnotnull = false;\r
-                       $funsigned = false;\r
-                       \r
-                       //-----------------\r
-                       // Parse attributes\r
-                       foreach($fld as $attr => $v) {\r
-                               if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';\r
-                               else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);\r
-                               \r
-                               switch($attr) {\r
-                               case '0':\r
-                               case 'NAME':    $fname = $v; break;\r
-                               case '1':\r
-                               case 'TYPE':    $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;\r
-                               \r
-                               case 'SIZE':    \r
-                                                               $dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');\r
-                                                               if ($dotat === false) $fsize = $v;\r
-                                                               else {\r
-                                                                       $fsize = substr($v,0,$dotat);\r
-                                                                       $fprec = substr($v,$dotat+1);\r
-                                                               }\r
-                                                               break;\r
-                               case 'UNSIGNED': $funsigned = true; break;\r
-                               case 'AUTOINCREMENT':\r
-                               case 'AUTO':    $fautoinc = true; $fnotnull = true; break;\r
-                               case 'KEY':\r
-                               case 'PRIMARY': $fprimary = $v; $fnotnull = true; break;\r
-                               case 'DEF':\r
-                               case 'DEFAULT': $fdefault = $v; break;\r
-                               case 'NOTNULL': $fnotnull = $v; break;\r
-                               case 'NOQUOTE': $fnoquote = $v; break;\r
-                               case 'DEFDATE': $fdefdate = $v; break;\r
-                               case 'DEFTIMESTAMP': $fdefts = $v; break;\r
-                               case 'CONSTRAINT': $fconstraint = $v; break;\r
-                               } //switch\r
-                       } // foreach $fld\r
-                       \r
-                       //--------------------\r
-                       // VALIDATE FIELD INFO\r
-                       if (!strlen($fname)) {\r
-                               if ($this->debug) ADOConnection::outp("Undefined NAME");\r
-                               return false;\r
-                       }\r
-                       \r
-                       $fname = $this->NameQuote($fname);\r
-                       \r
-                       if (!strlen($ftype)) {\r
-                               if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");\r
-                               return false;\r
-                       } else {\r
-                               $ftype = strtoupper($ftype);\r
-                       }\r
-                       \r
-                       $ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);\r
-                       \r
-                       if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls\r
-                       \r
-                       if ($fprimary) $pkey[] = $fname;\r
-                       \r
-                       // some databases do not allow blobs to have defaults\r
-                       if ($ty == 'X') $fdefault = false;\r
-                       \r
-                       //--------------------\r
-                       // CONSTRUCT FIELD SQL\r
-                       if ($fdefts) {\r
-                               if (substr($this->connection->databaseType,0,5) == 'mysql') {\r
-                                       $ftype = 'TIMESTAMP';\r
-                               } else {\r
-                                       $fdefault = $this->connection->sysTimeStamp;\r
-                               }\r
-                       } else if ($fdefdate) {\r
-                               if (substr($this->connection->databaseType,0,5) == 'mysql') {\r
-                                       $ftype = 'TIMESTAMP';\r
-                               } else {\r
-                                       $fdefault = $this->connection->sysDate;\r
-                               }\r
-                       } else if (strlen($fdefault) && !$fnoquote)\r
-                               if ($ty == 'C' or $ty == 'X' or \r
-                                       ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault)))\r
-                                       if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') \r
-                                               $fdefault = trim($fdefault);\r
-                                       else if (strtolower($fdefault) != 'null')\r
-                                               $fdefault = $this->connection->qstr($fdefault);\r
-                       $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);\r
-                       \r
-                       $fname = str_pad($fname,16);\r
-                       $lines[] = "$fname $ftype$suffix";\r
-                       \r
-                       if ($fautoinc) $this->autoIncrement = true;\r
-               } // foreach $flds\r
-               \r
-               \r
-               return array($lines,$pkey);\r
-       }\r
-       /*\r
-                GENERATE THE SIZE PART OF THE DATATYPE\r
-                       $ftype is the actual type\r
-                       $ty is the type defined originally in the DDL\r
-       */\r
-       function _GetSize($ftype, $ty, $fsize, $fprec)\r
-       {\r
-               if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {\r
-                       $ftype .= "(".$fsize;\r
-                       if (strlen($fprec)) $ftype .= ",".$fprec;\r
-                       $ftype .= ')';\r
-               }\r
-               return $ftype;\r
-       }\r
-       \r
-       \r
-       // return string must begin with space\r
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)\r
-       {       \r
-               $suffix = '';\r
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
-               if ($fnotnull) $suffix .= ' NOT NULL';\r
-               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
-               return $suffix;\r
-       }\r
-       \r
-       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)\r
-       {\r
-               $sql = array();\r
-               \r
-               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
-                       $sql[] = sprintf ($this->dropIndex, $idxname);\r
-                       if ( isset($idxoptions['DROP']) )\r
-                               return $sql;\r
-               }\r
-               \r
-               if ( empty ($flds) ) {\r
-                       return $sql;\r
-               }\r
-               \r
-               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';\r
-               \r
-               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';\r
-               \r
-               if ( isset($idxoptions[$this->upperName]) )\r
-                       $s .= $idxoptions[$this->upperName];\r
-               \r
-               if ( is_array($flds) )\r
-                       $flds = implode(', ',$flds);\r
-               $s .= '(' . $flds . ')';\r
-               $sql[] = $s;\r
-               \r
-               return $sql;\r
-       }\r
-       \r
-       function _DropAutoIncrement($tabname)\r
-       {\r
-               return false;\r
-       }\r
-       \r
-       function _TableSQL($tabname,$lines,$pkey,$tableoptions)\r
-       {\r
-               $sql = array();\r
-               \r
-               if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {\r
-                       $sql[] = sprintf($this->dropTable,$tabname);\r
-                       if ($this->autoIncrement) {\r
-                               $sInc = $this->_DropAutoIncrement($tabname);\r
-                               if ($sInc) $sql[] = $sInc;\r
-                       }\r
-                       if ( isset ($tableoptions['DROP']) ) {\r
-                               return $sql;\r
-                       }\r
-               }\r
-               $s = "CREATE TABLE $tabname (\n";\r
-               $s .= implode(",\n", $lines);\r
-               if (sizeof($pkey)>0) {\r
-                       $s .= ",\n                 PRIMARY KEY (";\r
-                       $s .= implode(", ",$pkey).")";\r
-               }\r
-               if (isset($tableoptions['CONSTRAINTS'])) \r
-                       $s .= "\n".$tableoptions['CONSTRAINTS'];\r
-               \r
-               if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) \r
-                       $s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];\r
-               \r
-               $s .= "\n)";\r
-               if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];\r
-               $sql[] = $s;\r
-               \r
-               return $sql;\r
-       }\r
-       \r
-       /*\r
-               GENERATE TRIGGERS IF NEEDED\r
-               used when table has auto-incrementing field that is emulated using triggers\r
-       */\r
-       function _Triggers($tabname,$taboptions)\r
-       {\r
-               return array();\r
-       }\r
-       \r
-       /*\r
-               Sanitize options, so that array elements with no keys are promoted to keys\r
-       */\r
-       function _Options($opts)\r
-       {\r
-               if (!is_array($opts)) return array();\r
-               $newopts = array();\r
-               foreach($opts as $k => $v) {\r
-                       if (is_numeric($k)) $newopts[strtoupper($v)] = $v;\r
-                       else $newopts[strtoupper($k)] = $v;\r
-               }\r
-               return $newopts;\r
-       }\r
-\r
-\r
-/*\r
-"Florian Buzin [ easywe ]" <florian.buzin@easywe.de>\r
-\r
-This function changes/adds new fields to your table. You  \r
- dont have to know if the col is new or not. It will check on its \r
-own.\r
-\r
-*/\r
-       function ChangeTableSQL($tablename, $flds,$tableoptions=false)\r
-       {\r
-               $tabname = $this->TableName ($tablename);\r
-               \r
-               $conn = &$this->connection;\r
-               if (!is_object ($conn)) {\r
-                       return false;\r
-               }\r
-               \r
-               $colarr = &$conn->MetaColumns($tabname);\r
-               if (!$colarr) {\r
-                       return $this->CreateTableSQL($tablename,$flds,$tableoptions);\r
-               }\r
-               \r
-               foreach($colarr as $col) {\r
-                       $cols[strtoupper($col->name)] = " ALTER ";\r
-               }\r
-               \r
-               $sql = array();\r
-               list($lines,$pkey) = $this->_GenFields($flds);\r
-               \r
-               foreach($lines as $v) {\r
-                       $f = explode(" ",$v);\r
-                       if(!empty($cols[strtoupper($f[0])])){\r
-                               $sql[] = "ALTER TABLE $tabname $this->alterCol $v";\r
-                       }else{\r
-                               $sql[] = "ALTER TABLE $tabname $this->addCol $v";\r
-                       }\r
-               }\r
-               return $sql;\r
-       }\r
-} // class\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+       DOCUMENTATION:
+       
+               See adodb/tests/test-datadict.php for docs and examples.
+*/
+
+/*
+       Test script for parser
+*/
+function Lens_ParseTest()
+{
+$str = "`zcol ACOL` NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0";
+print "<p>$str</p>";
+$a= Lens_ParseArgs($str);
+print "<pre>";
+print_r($a);
+print "</pre>";
+}
+
+if (!function_exists('ctype_alnum')) {
+       function ctype_alnum($text) {
+               return preg_match('/^[a-z0-9]*$/i', $text);
+       }
+}
+
+//Lens_ParseTest();
+
+/**
+       Parse arguments, treat "text" (text) and 'text' as quotation marks.
+       To escape, use "" or '' or ))
+       
+       Will read in "abc def" sans quotes, as: abc def
+       Same with 'abc def'.
+       However if `abc def`, then will read in as `abc def`
+       
+       @param endstmtchar    Character that indicates end of statement
+       @param tokenchars     Include the following characters in tokens apart from A-Z and 0-9 
+       @returns 2 dimensional array containing parsed tokens.
+*/
+function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
+{
+       $pos = 0;
+       $intoken = false;
+       $stmtno = 0;
+       $endquote = false;
+       $tokens = array();
+       $tokens[$stmtno] = array();
+       $max = strlen($args);
+       $quoted = false;
+       
+       while ($pos < $max) {
+               $ch = substr($args,$pos,1);
+               switch($ch) {
+               case ' ':
+               case "\t":
+               case "\n":
+               case "\r":
+                       if (!$quoted) {
+                               if ($intoken) {
+                                       $intoken = false;
+                                       $tokens[$stmtno][] = implode('',$tokarr);
+                               }
+                               break;
+                       }
+                       
+                       $tokarr[] = $ch;
+                       break;
+               
+               case '`':
+                       if ($intoken) $tokarr[] = $ch;
+               case '(':
+               case ')':       
+               case '"':
+               case "'":
+                       
+                       if ($intoken) {
+                               if (empty($endquote)) {
+                                       $tokens[$stmtno][] = implode('',$tokarr);
+                                       if ($ch == '(') $endquote = ')';
+                                       else $endquote = $ch;
+                                       $quoted = true;
+                                       $intoken = true;
+                                       $tokarr = array();
+                               } else if ($endquote == $ch) {
+                                       $ch2 = substr($args,$pos+1,1);
+                                       if ($ch2 == $endquote) {
+                                               $pos += 1;
+                                               $tokarr[] = $ch2;
+                                       } else {
+                                               $quoted = false;
+                                               $intoken = false;
+                                               $tokens[$stmtno][] = implode('',$tokarr);
+                                               $endquote = '';
+                                       }
+                               } else
+                                       $tokarr[] = $ch;
+                                       
+                       }else {
+                       
+                               if ($ch == '(') $endquote = ')';
+                               else $endquote = $ch;
+                               $quoted = true;
+                               $intoken = true;
+                               $tokarr = array();
+                               if ($ch == '`') $tokarr[] = '`';
+                       }
+                       break;
+                       
+               default:
+                       
+                       if (!$intoken) {
+                               if ($ch == $endstmtchar) {
+                                       $stmtno += 1;
+                                       $tokens[$stmtno] = array();
+                                       break;
+                               }
+                       
+                               $intoken = true;
+                               $quoted = false;
+                               $endquote = false;
+                               $tokarr = array();
+       
+                       }
+                       
+                       if ($quoted) $tokarr[] = $ch;
+                       else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;
+                       else {
+                               if ($ch == $endstmtchar) {                      
+                                       $tokens[$stmtno][] = implode('',$tokarr);
+                                       $stmtno += 1;
+                                       $tokens[$stmtno] = array();
+                                       $intoken = false;
+                                       $tokarr = array();
+                                       break;
+                               }
+                               $tokens[$stmtno][] = implode('',$tokarr);
+                               $tokens[$stmtno][] = $ch;
+                               $intoken = false;
+                       }
+               }
+               $pos += 1;
+       }
+       
+       return $tokens;
+}
+
+
+class ADODB_DataDict {
+       var $connection;
+       var $debug = false;
+       var $dropTable = 'DROP TABLE %s';
+       var $dropIndex = 'DROP INDEX %s';
+       var $addCol = ' ADD';
+       var $alterCol = ' ALTER COLUMN';
+       var $dropCol = ' DROP COLUMN';
+       var $nameRegex = '\w';
+       var $schema = false;
+       var $serverInfo = array();
+       var $autoIncrement = false;
+       var $dataProvider;
+       var $blobSize = 100;    /// any varchar/char field this size or greater is treated as a blob
+                                                       /// in other words, we use a text area for editting.
+       
+       function GetCommentSQL($table,$col)
+       {
+               return false;
+       }
+       
+       function SetCommentSQL($table,$col,$cmt)
+       {
+               return false;
+       }
+       
+       function &MetaTables()
+       {
+               return $this->connection->MetaTables();
+       }
+       
+       function &MetaColumns($tab, $upper=true, $schema=false)
+       {
+               return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
+       }
+       
+       function &MetaPrimaryKeys($tab,$owner=false,$intkey=false)
+       {
+               return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
+       }
+       
+       function &MetaIndexes($table, $primary = false, $owner = false)
+       {
+               return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
+       }
+       
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               return ADORecordSet::MetaType($t,$len,$fieldobj);
+       }
+       
+       function NameQuote($name = NULL)
+       {
+               if (!is_string($name)) {
+                       return FALSE;
+               }
+               
+               $name = trim($name);
+               
+               if ( !is_object($this->connection) ) {
+                       return $name;
+               }
+               
+               $quote = $this->connection->nameQuote;
+               
+               // if name is of the form `name`, quote it
+               if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
+                       return $quote . $matches[1] . $quote;
+               }
+               
+               // if name contains special characters, quote it
+               if ( !preg_match('/^[' . $this->nameRegex . ']+$/', $name) ) {
+                       return $quote . $name . $quote;
+               }
+               
+               return $name;
+       }
+       
+       function TableName($name)
+       {
+               if ( $this->schema ) {
+                       return $this->NameQuote($this->schema) .'.'. $this->NameQuote($name);
+               }
+               return $this->NameQuote($name);
+       }
+       
+       // Executes the sql array returned by GetTableSQL and GetIndexSQL
+       function ExecuteSQLArray($sql, $continueOnError = true)
+       {
+               $rez = 2;
+               $conn = &$this->connection;
+               $saved = $conn->debug;
+               foreach($sql as $line) {
+                       
+                       if ($this->debug) $conn->debug = true;
+                       $ok = $conn->Execute($line);
+                       $conn->debug = $saved;
+                       if (!$ok) {
+                               if ($this->debug) ADOConnection::outp($conn->ErrorMsg());
+                               if (!$continueOnError) return 0;
+                               $rez = 1;
+                       }
+               }
+               return 2;
+       }
+       
+       /*
+               Returns the actual type given a character code.
+               
+               C:  varchar
+               X:  CLOB (character large object) or largest varchar size if CLOB is not supported
+               C2: Multibyte varchar
+               X2: Multibyte CLOB
+               
+               B:  BLOB (binary large object)
+               
+               D:  Date
+               T:  Date-time 
+               L:  Integer field suitable for storing booleans (0 or 1)
+               I:  Integer
+               F:  Floating point number
+               N:  Numeric or decimal number
+       */
+       
+       function ActualType($meta)
+       {
+               return $meta;
+       }
+       
+       function CreateDatabase($dbname,$options=false)
+       {
+               $options = $this->_Options($options);
+               $sql = array();
+               
+               $s = 'CREATE DATABASE ' . $this->NameQuote($dbname);
+               if (isset($options[$this->upperName]))
+                       $s .= ' '.$options[$this->upperName];
+               
+               $sql[] = $s;
+               return $sql;
+       }
+       
+       /*
+        Generates the SQL to create index. Returns an array of sql strings.
+       */
+       function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)
+       {
+               if (!is_array($flds)) {
+                       $flds = explode(',',$flds);
+               }
+               
+               foreach($flds as $key => $fld) {
+                       $flds[$key] = $this->NameQuote($fld);
+               }
+               
+               return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));
+       }
+       
+       function DropIndexSQL ($idxname, $tabname = NULL)
+       {
+               return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));
+       }
+       
+       function SetSchema($schema)
+       {
+               $this->schema = $schema;
+       }
+       
+       function AddColumnSQL($tabname, $flds)
+       {
+               $tabname = $this->TableName ($tabname);
+               $sql = array();
+               list($lines,$pkey) = $this->_GenFields($flds);
+               $alter = 'ALTER TABLE ' . $tabname . $this->addCol . ' ';
+               foreach($lines as $v) {
+                       $sql[] = $alter . $v;
+               }
+               return $sql;
+       }
+       
+       function AlterColumnSQL($tabname, $flds)
+       {
+               $tabname = $this->TableName ($tabname);
+               $sql = array();
+               list($lines,$pkey) = $this->_GenFields($flds);
+               $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' ';
+               foreach($lines as $v) {
+                       $sql[] = $alter . $v;
+               }
+               return $sql;
+       }
+       
+       function DropColumnSQL($tabname, $flds)
+       {
+               $tabname = $this->TableName ($tabname);
+               if (!is_array($flds)) $flds = explode(',',$flds);
+               $sql = array();
+               $alter = 'ALTER TABLE ' . $tabname . $this->dropCol . ' ';
+               foreach($flds as $v) {
+                       $sql[] = $alter . $this->NameQuote($v);
+               }
+               return $sql;
+       }
+       
+       function DropTableSQL($tabname)
+       {
+               return array (sprintf($this->dropTable, $this->TableName($tabname)));
+       }
+       
+       /*
+        Generate the SQL to create table. Returns an array of sql strings.
+       */
+       function CreateTableSQL($tabname, $flds, $tableoptions=false)
+       {
+               if (!$tableoptions) $tableoptions = array();
+               
+               list($lines,$pkey) = $this->_GenFields($flds);
+               
+               $taboptions = $this->_Options($tableoptions);
+               $tabname = $this->TableName ($tabname);
+               $sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
+               
+               $tsql = $this->_Triggers($tabname,$taboptions);
+               foreach($tsql as $s) $sql[] = $s;
+               
+               return $sql;
+       }
+       
+       function _GenFields($flds)
+       {
+               if (is_string($flds)) {
+                       $padding = '     ';
+                       $txt = $flds.$padding;
+                       $flds = array();
+                       $flds0 = Lens_ParseArgs($txt,',');
+                       $hasparam = false;
+                       foreach($flds0 as $f0) {
+                               $f1 = array();
+                               foreach($f0 as $token) {
+                                       switch (strtoupper($token)) {
+                                       case 'CONSTRAINT':
+                                       case 'DEFAULT': 
+                                               $hasparam = $token;
+                                               break;
+                                       default:
+                                               if ($hasparam) $f1[$hasparam] = $token;
+                                               else $f1[] = $token;
+                                               $hasparam = false;
+                                               break;
+                                       }
+                               }
+                               $flds[] = $f1;
+                               
+                       }
+               }
+               $this->autoIncrement = false;
+               $lines = array();
+               $pkey = array();
+               foreach($flds as $fld) {
+                       $fld = _array_change_key_case($fld);
+               
+                       $fname = false;
+                       $fdefault = false;
+                       $fautoinc = false;
+                       $ftype = false;
+                       $fsize = false;
+                       $fprec = false;
+                       $fprimary = false;
+                       $fnoquote = false;
+                       $fdefts = false;
+                       $fdefdate = false;
+                       $fconstraint = false;
+                       $fnotnull = false;
+                       $funsigned = false;
+                       
+                       //-----------------
+                       // Parse attributes
+                       foreach($fld as $attr => $v) {
+                               if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
+                               else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
+                               
+                               switch($attr) {
+                               case '0':
+                               case 'NAME':    $fname = $v; break;
+                               case '1':
+                               case 'TYPE':    $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
+                               
+                               case 'SIZE':    
+                                                               $dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');
+                                                               if ($dotat === false) $fsize = $v;
+                                                               else {
+                                                                       $fsize = substr($v,0,$dotat);
+                                                                       $fprec = substr($v,$dotat+1);
+                                                               }
+                                                               break;
+                               case 'UNSIGNED': $funsigned = true; break;
+                               case 'AUTOINCREMENT':
+                               case 'AUTO':    $fautoinc = true; $fnotnull = true; break;
+                               case 'KEY':
+                               case 'PRIMARY': $fprimary = $v; $fnotnull = true; break;
+                               case 'DEF':
+                               case 'DEFAULT': $fdefault = $v; break;
+                               case 'NOTNULL': $fnotnull = $v; break;
+                               case 'NOQUOTE': $fnoquote = $v; break;
+                               case 'DEFDATE': $fdefdate = $v; break;
+                               case 'DEFTIMESTAMP': $fdefts = $v; break;
+                               case 'CONSTRAINT': $fconstraint = $v; break;
+                               } //switch
+                       } // foreach $fld
+                       
+                       //--------------------
+                       // VALIDATE FIELD INFO
+                       if (!strlen($fname)) {
+                               if ($this->debug) ADOConnection::outp("Undefined NAME");
+                               return false;
+                       }
+                       
+                       $fid = strtoupper(preg_replace('/^`(.+)`$/', '$1', $fname));
+                       $fname = $this->NameQuote($fname);
+                       
+                       if (!strlen($ftype)) {
+                               if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
+                               return false;
+                       } else {
+                               $ftype = strtoupper($ftype);
+                       }
+                       
+                       $ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
+                       
+                       if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls
+                       
+                       if ($fprimary) $pkey[] = $fname;
+                       
+                       // some databases do not allow blobs to have defaults
+                       if ($ty == 'X') $fdefault = false;
+                       
+                       //--------------------
+                       // CONSTRUCT FIELD SQL
+                       if ($fdefts) {
+                               if (substr($this->connection->databaseType,0,5) == 'mysql') {
+                                       $ftype = 'TIMESTAMP';
+                               } else {
+                                       $fdefault = $this->connection->sysTimeStamp;
+                               }
+                       } else if ($fdefdate) {
+                               if (substr($this->connection->databaseType,0,5) == 'mysql') {
+                                       $ftype = 'TIMESTAMP';
+                               } else {
+                                       $fdefault = $this->connection->sysDate;
+                               }
+                       } else if (strlen($fdefault) && !$fnoquote)
+                               if ($ty == 'C' or $ty == 'X' or 
+                                       ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault)))
+                                       if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') 
+                                               $fdefault = trim($fdefault);
+                                       else if (strtolower($fdefault) != 'null')
+                                               $fdefault = $this->connection->qstr($fdefault);
+                       $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
+                       
+                       $fname = str_pad($fname,16);
+                       $lines[$fid] = $fname.' '.$ftype.$suffix;
+                       
+                       if ($fautoinc) $this->autoIncrement = true;
+               } // foreach $flds
+               
+               return array($lines,$pkey);
+       }
+       /*
+                GENERATE THE SIZE PART OF THE DATATYPE
+                       $ftype is the actual type
+                       $ty is the type defined originally in the DDL
+       */
+       function _GetSize($ftype, $ty, $fsize, $fprec)
+       {
+               if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {
+                       $ftype .= "(".$fsize;
+                       if (strlen($fprec)) $ftype .= ",".$fprec;
+                       $ftype .= ')';
+               }
+               return $ftype;
+       }
+       
+       
+       // return string must begin with space
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
+       {       
+               $suffix = '';
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+               if ($fnotnull) $suffix .= ' NOT NULL';
+               if ($fconstraint) $suffix .= ' '.$fconstraint;
+               return $suffix;
+       }
+       
+       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+       {
+               $sql = array();
+               
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+                       $sql[] = sprintf ($this->dropIndex, $idxname);
+                       if ( isset($idxoptions['DROP']) )
+                               return $sql;
+               }
+               
+               if ( empty ($flds) ) {
+                       return $sql;
+               }
+               
+               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
+       
+               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
+               
+               if ( isset($idxoptions[$this->upperName]) )
+                       $s .= $idxoptions[$this->upperName];
+               
+               if ( is_array($flds) )
+                       $flds = implode(', ',$flds);
+               $s .= '(' . $flds . ')';
+               $sql[] = $s;
+               
+               return $sql;
+       }
+       
+       function _DropAutoIncrement($tabname)
+       {
+               return false;
+       }
+       
+       function _TableSQL($tabname,$lines,$pkey,$tableoptions)
+       {
+               $sql = array();
+               
+               if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {
+                       $sql[] = sprintf($this->dropTable,$tabname);
+                       if ($this->autoIncrement) {
+                               $sInc = $this->_DropAutoIncrement($tabname);
+                               if ($sInc) $sql[] = $sInc;
+                       }
+                       if ( isset ($tableoptions['DROP']) ) {
+                               return $sql;
+                       }
+               }
+               $s = "CREATE TABLE $tabname (\n";
+               $s .= implode(",\n", $lines);
+               if (sizeof($pkey)>0) {
+                       $s .= ",\n                 PRIMARY KEY (";
+                       $s .= implode(", ",$pkey).")";
+               }
+               if (isset($tableoptions['CONSTRAINTS'])) 
+                       $s .= "\n".$tableoptions['CONSTRAINTS'];
+               
+               if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) 
+                       $s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
+               
+               $s .= "\n)";
+               if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
+               $sql[] = $s;
+               
+               return $sql;
+       }
+       
+       /*
+               GENERATE TRIGGERS IF NEEDED
+               used when table has auto-incrementing field that is emulated using triggers
+       */
+       function _Triggers($tabname,$taboptions)
+       {
+               return array();
+       }
+       
+       /*
+               Sanitize options, so that array elements with no keys are promoted to keys
+       */
+       function _Options($opts)
+       {
+               if (!is_array($opts)) return array();
+               $newopts = array();
+               foreach($opts as $k => $v) {
+                       if (is_numeric($k)) $newopts[strtoupper($v)] = $v;
+                       else $newopts[strtoupper($k)] = $v;
+               }
+               return $newopts;
+       }
+       
+       /*
+       "Florian Buzin [ easywe ]" <florian.buzin@easywe.de>
+       
+       This function changes/adds new fields to your table. You don't
+       have to know if the col is new or not. It will check on its own.
+       */
+       function ChangeTableSQL($tablename, $flds, $tableoptions = false)
+       {
+               if ( !is_array($cols = &$this->MetaColumns($tablename)) ) {
+                       return $this->CreateTableSQL($tablename, $flds, $tableoptions);
+               }
+               
+               list($lines,$pkey) = $this->_GenFields($flds);
+               $alter = 'ALTER TABLE ' . $this->TableName($tablename);
+               $sql = array();
+               
+               foreach ( $lines as $id => $v ) {
+                       if ( isset($cols[$id]) && is_object($cols[$id]) ) {
+                               $sql[] = $alter . $this->alterCol . ' ' . $v;
+                       } else {
+                               $sql[] = $alter . $this->addCol . ' ' . $v;
+                       }
+               }
+               
+               return $sql;
+       }
+} // class
 ?>
\ No newline at end of file
index f874caf922cd7844d5078f7282840cc3a64f84c5..b21f809e53c093601a6fbe5aa26b4ad72f0b058d 100644 (file)
-<?php\r
-/** \r
- * @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license. \r
- * Whenever there is any discrepancy between the two licenses, \r
- * the BSD license will take precedence. \r
- *\r
- * Set tabs to 4 for best viewing.\r
- * \r
- * The following code is adapted from the PEAR DB error handling code.\r
- * Portions (c)1997-2002 The PHP Group.\r
- */\r
-\r
-if (!defined("DB_ERROR")) define("DB_ERROR",-1);\r
-\r
-if (!defined("DB_ERROR_SYNTAX")) {\r
-       define("DB_ERROR_SYNTAX",              -2);\r
-       define("DB_ERROR_CONSTRAINT",          -3);\r
-       define("DB_ERROR_NOT_FOUND",           -4);\r
-       define("DB_ERROR_ALREADY_EXISTS",      -5);\r
-       define("DB_ERROR_UNSUPPORTED",         -6);\r
-       define("DB_ERROR_MISMATCH",            -7);\r
-       define("DB_ERROR_INVALID",             -8);\r
-       define("DB_ERROR_NOT_CAPABLE",         -9);\r
-       define("DB_ERROR_TRUNCATED",          -10);\r
-       define("DB_ERROR_INVALID_NUMBER",     -11);\r
-       define("DB_ERROR_INVALID_DATE",       -12);\r
-       define("DB_ERROR_DIVZERO",            -13);\r
-       define("DB_ERROR_NODBSELECTED",       -14);\r
-       define("DB_ERROR_CANNOT_CREATE",      -15);\r
-       define("DB_ERROR_CANNOT_DELETE",      -16);\r
-       define("DB_ERROR_CANNOT_DROP",        -17);\r
-       define("DB_ERROR_NOSUCHTABLE",        -18);\r
-       define("DB_ERROR_NOSUCHFIELD",        -19);\r
-       define("DB_ERROR_NEED_MORE_DATA",     -20);\r
-       define("DB_ERROR_NOT_LOCKED",         -21);\r
-       define("DB_ERROR_VALUE_COUNT_ON_ROW", -22);\r
-       define("DB_ERROR_INVALID_DSN",        -23);\r
-       define("DB_ERROR_CONNECT_FAILED",     -24);\r
-       define("DB_ERROR_EXTENSION_NOT_FOUND",-25);\r
-       define("DB_ERROR_NOSUCHDB",           -25);\r
-       define("DB_ERROR_ACCESS_VIOLATION",   -26);\r
-}\r
-\r
-function adodb_errormsg($value)\r
-{\r
-global $ADODB_LANG,$ADODB_LANG_ARRAY;\r
-\r
-       if (empty($ADODB_LANG)) $ADODB_LANG = 'en';\r
-       if (isset($ADODB_LANG_ARRAY['LANG']) && $ADODB_LANG_ARRAY['LANG'] == $ADODB_LANG) ;\r
-       else {\r
-               include_once(ADODB_DIR."/lang/adodb-$ADODB_LANG.inc.php");\r
-    }\r
-       return isset($ADODB_LANG_ARRAY[$value]) ? $ADODB_LANG_ARRAY[$value] : $ADODB_LANG_ARRAY[DB_ERROR];\r
-}\r
-\r
-function adodb_error($provider,$dbType,$errno)\r
-{\r
-       //var_dump($errno);\r
-       if (is_numeric($errno) && $errno == 0) return 0;\r
-       switch($provider) { \r
-       case 'mysql': $map = adodb_error_mysql(); break;\r
-       \r
-       case 'oracle':\r
-       case 'oci8': $map = adodb_error_oci8(); break;\r
-       \r
-       case 'ibase': $map = adodb_error_ibase(); break;\r
-       \r
-       case 'odbc': $map = adodb_error_odbc(); break;\r
-       \r
-       case 'mssql':\r
-       case 'sybase': $map = adodb_error_mssql(); break;\r
-       \r
-       case 'informix': $map = adodb_error_ifx(); break;\r
-       \r
-       case 'postgres': return adodb_error_pg($errno); break;\r
-       \r
-       case 'sqlite': return $map = adodb_error_sqlite(); break;\r
-       default:\r
-               return DB_ERROR;\r
-       }       \r
-       //print_r($map);\r
-       //var_dump($errno);\r
-       if (isset($map[$errno])) return $map[$errno];\r
-       return DB_ERROR;\r
-}\r
-\r
-//**************************************************************************************\r
-\r
-function adodb_error_pg($errormsg)\r
-{\r
-    static $error_regexps = array(\r
-            '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => DB_ERROR_NOSUCHTABLE,\r
-            '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/'      => DB_ERROR_ALREADY_EXISTS,\r
-            '/divide by zero$/'                     => DB_ERROR_DIVZERO,\r
-            '/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER,\r
-            '/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD,\r
-            '/parser: parse error at or near \"/'   => DB_ERROR_SYNTAX,\r
-            '/referential integrity violation/'     => DB_ERROR_CONSTRAINT\r
-        );\r
-       reset($error_regexps);\r
-    while (list($regexp,$code) = each($error_regexps)) {\r
-        if (preg_match($regexp, $errormsg)) {\r
-            return $code;\r
-        }\r
-    }\r
-    // Fall back to DB_ERROR if there was no mapping.\r
-    return DB_ERROR;\r
-}\r
-       \r
-function adodb_error_odbc()\r
-{\r
-static $MAP = array(\r
-            '01004' => DB_ERROR_TRUNCATED,\r
-            '07001' => DB_ERROR_MISMATCH,\r
-            '21S01' => DB_ERROR_MISMATCH,\r
-            '21S02' => DB_ERROR_MISMATCH,\r
-            '22003' => DB_ERROR_INVALID_NUMBER,\r
-            '22008' => DB_ERROR_INVALID_DATE,\r
-            '22012' => DB_ERROR_DIVZERO,\r
-            '23000' => DB_ERROR_CONSTRAINT,\r
-            '24000' => DB_ERROR_INVALID,\r
-            '34000' => DB_ERROR_INVALID,\r
-            '37000' => DB_ERROR_SYNTAX,\r
-            '42000' => DB_ERROR_SYNTAX,\r
-            'IM001' => DB_ERROR_UNSUPPORTED,\r
-            'S0000' => DB_ERROR_NOSUCHTABLE,\r
-            'S0001' => DB_ERROR_NOT_FOUND,\r
-            'S0002' => DB_ERROR_NOSUCHTABLE,\r
-            'S0011' => DB_ERROR_ALREADY_EXISTS,\r
-            'S0012' => DB_ERROR_NOT_FOUND,\r
-            'S0021' => DB_ERROR_ALREADY_EXISTS,\r
-            'S0022' => DB_ERROR_NOT_FOUND,\r
-                       'S1000' => DB_ERROR_NOSUCHTABLE,\r
-            'S1009' => DB_ERROR_INVALID,\r
-            'S1090' => DB_ERROR_INVALID,\r
-            'S1C00' => DB_ERROR_NOT_CAPABLE\r
-        );\r
-               return $MAP;\r
-}\r
-\r
-function adodb_error_ibase()\r
-{\r
-static $MAP = array(\r
-            -104 => DB_ERROR_SYNTAX,\r
-            -150 => DB_ERROR_ACCESS_VIOLATION,\r
-            -151 => DB_ERROR_ACCESS_VIOLATION,\r
-            -155 => DB_ERROR_NOSUCHTABLE,\r
-            -157 => DB_ERROR_NOSUCHFIELD,\r
-            -158 => DB_ERROR_VALUE_COUNT_ON_ROW,\r
-            -170 => DB_ERROR_MISMATCH,\r
-            -171 => DB_ERROR_MISMATCH,\r
-            -172 => DB_ERROR_INVALID,\r
-            -204 => DB_ERROR_INVALID,\r
-            -205 => DB_ERROR_NOSUCHFIELD,\r
-            -206 => DB_ERROR_NOSUCHFIELD,\r
-            -208 => DB_ERROR_INVALID,\r
-            -219 => DB_ERROR_NOSUCHTABLE,\r
-            -297 => DB_ERROR_CONSTRAINT,\r
-            -530 => DB_ERROR_CONSTRAINT,\r
-            -803 => DB_ERROR_CONSTRAINT,\r
-            -551 => DB_ERROR_ACCESS_VIOLATION,\r
-            -552 => DB_ERROR_ACCESS_VIOLATION,\r
-            -922 => DB_ERROR_NOSUCHDB,\r
-            -923 => DB_ERROR_CONNECT_FAILED,\r
-            -924 => DB_ERROR_CONNECT_FAILED\r
-        );\r
-               \r
-               return $MAP;\r
-}\r
-\r
-function adodb_error_ifx()\r
-{\r
-static $MAP = array(\r
-            '-201'    => DB_ERROR_SYNTAX,\r
-            '-206'    => DB_ERROR_NOSUCHTABLE,\r
-            '-217'    => DB_ERROR_NOSUCHFIELD,\r
-            '-329'    => DB_ERROR_NODBSELECTED,\r
-            '-1204'   => DB_ERROR_INVALID_DATE,\r
-            '-1205'   => DB_ERROR_INVALID_DATE,\r
-            '-1206'   => DB_ERROR_INVALID_DATE,\r
-            '-1209'   => DB_ERROR_INVALID_DATE,\r
-            '-1210'   => DB_ERROR_INVALID_DATE,\r
-            '-1212'   => DB_ERROR_INVALID_DATE\r
-       );\r
-          \r
-          return $MAP;\r
-}\r
-\r
-function adodb_error_oci8()\r
-{\r
-static $MAP = array(\r
-                        1 => DB_ERROR_ALREADY_EXISTS,\r
-            900 => DB_ERROR_SYNTAX,\r
-            904 => DB_ERROR_NOSUCHFIELD,\r
-            923 => DB_ERROR_SYNTAX,\r
-            942 => DB_ERROR_NOSUCHTABLE,\r
-            955 => DB_ERROR_ALREADY_EXISTS,\r
-            1476 => DB_ERROR_DIVZERO,\r
-            1722 => DB_ERROR_INVALID_NUMBER,\r
-            2289 => DB_ERROR_NOSUCHTABLE,\r
-            2291 => DB_ERROR_CONSTRAINT,\r
-            2449 => DB_ERROR_CONSTRAINT\r
-        );\r
-          \r
-       return $MAP;\r
-}\r
-\r
-function adodb_error_mssql()\r
-{\r
-static $MAP = array(\r
-                 208 => DB_ERROR_NOSUCHTABLE,\r
-          2601 => DB_ERROR_ALREADY_EXISTS\r
-       );\r
-          \r
-       return $MAP;\r
-}\r
-\r
-function adodb_error_sqlite()\r
-{\r
-static $MAP = array(\r
-                 1 => DB_ERROR_SYNTAX\r
-       );\r
-          \r
-       return $MAP;\r
-}\r
-\r
-function adodb_error_mysql()\r
-{\r
-static $MAP = array(\r
-           1004 => DB_ERROR_CANNOT_CREATE,\r
-           1005 => DB_ERROR_CANNOT_CREATE,\r
-           1006 => DB_ERROR_CANNOT_CREATE,\r
-           1007 => DB_ERROR_ALREADY_EXISTS,\r
-           1008 => DB_ERROR_CANNOT_DROP,\r
-                  1045 => DB_ERROR_ACCESS_VIOLATION,\r
-           1046 => DB_ERROR_NODBSELECTED,\r
-                  1049 => DB_ERROR_NOSUCHDB,\r
-           1050 => DB_ERROR_ALREADY_EXISTS,\r
-           1051 => DB_ERROR_NOSUCHTABLE,\r
-           1054 => DB_ERROR_NOSUCHFIELD,\r
-           1062 => DB_ERROR_ALREADY_EXISTS,\r
-           1064 => DB_ERROR_SYNTAX,\r
-           1100 => DB_ERROR_NOT_LOCKED,\r
-           1136 => DB_ERROR_VALUE_COUNT_ON_ROW,\r
-           1146 => DB_ERROR_NOSUCHTABLE,\r
-           1048 => DB_ERROR_CONSTRAINT,\r
-                   2002 => DB_ERROR_CONNECT_FAILED\r
-       );\r
-          \r
-       return $MAP;\r
-}\r
+<?php
+/** 
+ * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * The following code is adapted from the PEAR DB error handling code.
+ * Portions (c)1997-2002 The PHP Group.
+ */
+
+if (!defined("DB_ERROR")) define("DB_ERROR",-1);
+
+if (!defined("DB_ERROR_SYNTAX")) {
+       define("DB_ERROR_SYNTAX",              -2);
+       define("DB_ERROR_CONSTRAINT",          -3);
+       define("DB_ERROR_NOT_FOUND",           -4);
+       define("DB_ERROR_ALREADY_EXISTS",      -5);
+       define("DB_ERROR_UNSUPPORTED",         -6);
+       define("DB_ERROR_MISMATCH",            -7);
+       define("DB_ERROR_INVALID",             -8);
+       define("DB_ERROR_NOT_CAPABLE",         -9);
+       define("DB_ERROR_TRUNCATED",          -10);
+       define("DB_ERROR_INVALID_NUMBER",     -11);
+       define("DB_ERROR_INVALID_DATE",       -12);
+       define("DB_ERROR_DIVZERO",            -13);
+       define("DB_ERROR_NODBSELECTED",       -14);
+       define("DB_ERROR_CANNOT_CREATE",      -15);
+       define("DB_ERROR_CANNOT_DELETE",      -16);
+       define("DB_ERROR_CANNOT_DROP",        -17);
+       define("DB_ERROR_NOSUCHTABLE",        -18);
+       define("DB_ERROR_NOSUCHFIELD",        -19);
+       define("DB_ERROR_NEED_MORE_DATA",     -20);
+       define("DB_ERROR_NOT_LOCKED",         -21);
+       define("DB_ERROR_VALUE_COUNT_ON_ROW", -22);
+       define("DB_ERROR_INVALID_DSN",        -23);
+       define("DB_ERROR_CONNECT_FAILED",     -24);
+       define("DB_ERROR_EXTENSION_NOT_FOUND",-25);
+       define("DB_ERROR_NOSUCHDB",           -25);
+       define("DB_ERROR_ACCESS_VIOLATION",   -26);
+}
+
+function adodb_errormsg($value)
+{
+global $ADODB_LANG,$ADODB_LANG_ARRAY;
+
+       if (empty($ADODB_LANG)) $ADODB_LANG = 'en';
+       if (isset($ADODB_LANG_ARRAY['LANG']) && $ADODB_LANG_ARRAY['LANG'] == $ADODB_LANG) ;
+       else {
+               include_once(ADODB_DIR."/lang/adodb-$ADODB_LANG.inc.php");
+    }
+       return isset($ADODB_LANG_ARRAY[$value]) ? $ADODB_LANG_ARRAY[$value] : $ADODB_LANG_ARRAY[DB_ERROR];
+}
+
+function adodb_error($provider,$dbType,$errno)
+{
+       //var_dump($errno);
+       if (is_numeric($errno) && $errno == 0) return 0;
+       switch($provider) { 
+       case 'mysql': $map = adodb_error_mysql(); break;
+       
+       case 'oracle':
+       case 'oci8': $map = adodb_error_oci8(); break;
+       
+       case 'ibase': $map = adodb_error_ibase(); break;
+       
+       case 'odbc': $map = adodb_error_odbc(); break;
+       
+       case 'mssql':
+       case 'sybase': $map = adodb_error_mssql(); break;
+       
+       case 'informix': $map = adodb_error_ifx(); break;
+       
+       case 'postgres': return adodb_error_pg($errno); break;
+       
+       case 'sqlite': return $map = adodb_error_sqlite(); break;
+       default:
+               return DB_ERROR;
+       }       
+       //print_r($map);
+       //var_dump($errno);
+       if (isset($map[$errno])) return $map[$errno];
+       return DB_ERROR;
+}
+
+//**************************************************************************************
+
+function adodb_error_pg($errormsg)
+{
+    static $error_regexps = array(
+            '/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => DB_ERROR_NOSUCHTABLE,
+            '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/'      => DB_ERROR_ALREADY_EXISTS,
+            '/divide by zero$/'                     => DB_ERROR_DIVZERO,
+            '/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER,
+            '/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD,
+            '/parser: parse error at or near \"/'   => DB_ERROR_SYNTAX,
+            '/referential integrity violation/'     => DB_ERROR_CONSTRAINT
+        );
+       reset($error_regexps);
+    while (list($regexp,$code) = each($error_regexps)) {
+        if (preg_match($regexp, $errormsg)) {
+            return $code;
+        }
+    }
+    // Fall back to DB_ERROR if there was no mapping.
+    return DB_ERROR;
+}
+       
+function adodb_error_odbc()
+{
+static $MAP = array(
+            '01004' => DB_ERROR_TRUNCATED,
+            '07001' => DB_ERROR_MISMATCH,
+            '21S01' => DB_ERROR_MISMATCH,
+            '21S02' => DB_ERROR_MISMATCH,
+            '22003' => DB_ERROR_INVALID_NUMBER,
+            '22008' => DB_ERROR_INVALID_DATE,
+            '22012' => DB_ERROR_DIVZERO,
+            '23000' => DB_ERROR_CONSTRAINT,
+            '24000' => DB_ERROR_INVALID,
+            '34000' => DB_ERROR_INVALID,
+            '37000' => DB_ERROR_SYNTAX,
+            '42000' => DB_ERROR_SYNTAX,
+            'IM001' => DB_ERROR_UNSUPPORTED,
+            'S0000' => DB_ERROR_NOSUCHTABLE,
+            'S0001' => DB_ERROR_NOT_FOUND,
+            'S0002' => DB_ERROR_NOSUCHTABLE,
+            'S0011' => DB_ERROR_ALREADY_EXISTS,
+            'S0012' => DB_ERROR_NOT_FOUND,
+            'S0021' => DB_ERROR_ALREADY_EXISTS,
+            'S0022' => DB_ERROR_NOT_FOUND,
+                       'S1000' => DB_ERROR_NOSUCHTABLE,
+            'S1009' => DB_ERROR_INVALID,
+            'S1090' => DB_ERROR_INVALID,
+            'S1C00' => DB_ERROR_NOT_CAPABLE
+        );
+               return $MAP;
+}
+
+function adodb_error_ibase()
+{
+static $MAP = array(
+            -104 => DB_ERROR_SYNTAX,
+            -150 => DB_ERROR_ACCESS_VIOLATION,
+            -151 => DB_ERROR_ACCESS_VIOLATION,
+            -155 => DB_ERROR_NOSUCHTABLE,
+            -157 => DB_ERROR_NOSUCHFIELD,
+            -158 => DB_ERROR_VALUE_COUNT_ON_ROW,
+            -170 => DB_ERROR_MISMATCH,
+            -171 => DB_ERROR_MISMATCH,
+            -172 => DB_ERROR_INVALID,
+            -204 => DB_ERROR_INVALID,
+            -205 => DB_ERROR_NOSUCHFIELD,
+            -206 => DB_ERROR_NOSUCHFIELD,
+            -208 => DB_ERROR_INVALID,
+            -219 => DB_ERROR_NOSUCHTABLE,
+            -297 => DB_ERROR_CONSTRAINT,
+            -530 => DB_ERROR_CONSTRAINT,
+            -803 => DB_ERROR_CONSTRAINT,
+            -551 => DB_ERROR_ACCESS_VIOLATION,
+            -552 => DB_ERROR_ACCESS_VIOLATION,
+            -922 => DB_ERROR_NOSUCHDB,
+            -923 => DB_ERROR_CONNECT_FAILED,
+            -924 => DB_ERROR_CONNECT_FAILED
+        );
+               
+               return $MAP;
+}
+
+function adodb_error_ifx()
+{
+static $MAP = array(
+            '-201'    => DB_ERROR_SYNTAX,
+            '-206'    => DB_ERROR_NOSUCHTABLE,
+            '-217'    => DB_ERROR_NOSUCHFIELD,
+            '-329'    => DB_ERROR_NODBSELECTED,
+            '-1204'   => DB_ERROR_INVALID_DATE,
+            '-1205'   => DB_ERROR_INVALID_DATE,
+            '-1206'   => DB_ERROR_INVALID_DATE,
+            '-1209'   => DB_ERROR_INVALID_DATE,
+            '-1210'   => DB_ERROR_INVALID_DATE,
+            '-1212'   => DB_ERROR_INVALID_DATE
+       );
+          
+          return $MAP;
+}
+
+function adodb_error_oci8()
+{
+static $MAP = array(
+                        1 => DB_ERROR_ALREADY_EXISTS,
+            900 => DB_ERROR_SYNTAX,
+            904 => DB_ERROR_NOSUCHFIELD,
+            923 => DB_ERROR_SYNTAX,
+            942 => DB_ERROR_NOSUCHTABLE,
+            955 => DB_ERROR_ALREADY_EXISTS,
+            1476 => DB_ERROR_DIVZERO,
+            1722 => DB_ERROR_INVALID_NUMBER,
+            2289 => DB_ERROR_NOSUCHTABLE,
+            2291 => DB_ERROR_CONSTRAINT,
+            2449 => DB_ERROR_CONSTRAINT
+        );
+          
+       return $MAP;
+}
+
+function adodb_error_mssql()
+{
+static $MAP = array(
+                 208 => DB_ERROR_NOSUCHTABLE,
+          2601 => DB_ERROR_ALREADY_EXISTS
+       );
+          
+       return $MAP;
+}
+
+function adodb_error_sqlite()
+{
+static $MAP = array(
+                 1 => DB_ERROR_SYNTAX
+       );
+          
+       return $MAP;
+}
+
+function adodb_error_mysql()
+{
+static $MAP = array(
+           1004 => DB_ERROR_CANNOT_CREATE,
+           1005 => DB_ERROR_CANNOT_CREATE,
+           1006 => DB_ERROR_CANNOT_CREATE,
+           1007 => DB_ERROR_ALREADY_EXISTS,
+           1008 => DB_ERROR_CANNOT_DROP,
+                  1045 => DB_ERROR_ACCESS_VIOLATION,
+           1046 => DB_ERROR_NODBSELECTED,
+                  1049 => DB_ERROR_NOSUCHDB,
+           1050 => DB_ERROR_ALREADY_EXISTS,
+           1051 => DB_ERROR_NOSUCHTABLE,
+           1054 => DB_ERROR_NOSUCHFIELD,
+           1062 => DB_ERROR_ALREADY_EXISTS,
+           1064 => DB_ERROR_SYNTAX,
+           1100 => DB_ERROR_NOT_LOCKED,
+           1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
+           1146 => DB_ERROR_NOSUCHTABLE,
+           1048 => DB_ERROR_CONSTRAINT,
+                   2002 => DB_ERROR_CONNECT_FAILED
+       );
+          
+       return $MAP;
+}
 ?>
\ No newline at end of file
index f57263f0c1d22644261e491e4b36f18ca0ded2f0..94b4d4742a4b49699c4ea3fbb7fa8d405e658cda 100644 (file)
@@ -1,78 +1,78 @@
-<?php\r
-/**\r
- * @version V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license.\r
- * Whenever there is any discrepancy between the two licenses,\r
- * the BSD license will take precedence.\r
- *\r
- * Set tabs to 4 for best viewing.\r
- *\r
- * Latest version is available at http://php.weblogs.com\r
- *\r
-*/\r
-\r
-// added Claudio Bustos  clbustos#entelchile.net\r
-if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); \r
-\r
-define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');\r
-\r
-/**\r
-* Default Error Handler. This will be called with the following params\r
-*\r
-* @param $dbms         the RDBMS you are connecting to\r
-* @param $fn           the name of the calling function (in uppercase)\r
-* @param $errno                the native error number from the database\r
-* @param $errmsg       the native error msg from the database\r
-* @param $p1           $fn specific parameter - see below\r
-* @param $p2           $fn specific parameter - see below\r
-* @param $thisConn     $current connection object - can be false if no connection object created\r
-*/\r
-function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)\r
-{\r
-       if (error_reporting() == 0) return; // obey @ protocol\r
-       switch($fn) {\r
-       case 'EXECUTE':\r
-               $sql = $p1;\r
-               $inputparams = $p2;\r
-\r
-               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n";\r
-               break;\r
-\r
-       case 'PCONNECT':\r
-       case 'CONNECT':\r
-               $host = $p1;\r
-               $database = $p2;\r
-\r
-               $s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n";\r
-               break;\r
-       default:\r
-               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";\r
-               break;\r
-       }\r
-       /*\r
-       * Log connection error somewhere\r
-       *       0 message is sent to PHP's system logger, using the Operating System's system\r
-       *               logging mechanism or a file, depending on what the error_log configuration\r
-       *               directive is set to.\r
-       *       1 message is sent by email to the address in the destination parameter.\r
-       *               This is the only message type where the fourth parameter, extra_headers is used.\r
-       *               This message type uses the same internal function as mail() does.\r
-       *       2 message is sent through the PHP debugging connection.\r
-       *               This option is only available if remote debugging has been enabled.\r
-       *               In this case, the destination parameter specifies the host name or IP address\r
-       *               and optionally, port number, of the socket receiving the debug information.\r
-       *       3 message is appended to the file destination\r
-       */\r
-       if (defined('ADODB_ERROR_LOG_TYPE')) {\r
-               $t = date('Y-m-d H:i:s');\r
-               if (defined('ADODB_ERROR_LOG_DEST'))\r
-                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST);\r
-               else\r
-                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE);\r
-       }\r
-\r
-\r
-       //print "<p>$s</p>";\r
-       trigger_error($s,ADODB_ERROR_HANDLER_TYPE); \r
-}\r
-?>\r
+<?php
+/**
+ * @version V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license.
+ * Whenever there is any discrepancy between the two licenses,
+ * the BSD license will take precedence.
+ *
+ * Set tabs to 4 for best viewing.
+ *
+ * Latest version is available at http://php.weblogs.com
+ *
+*/
+
+// added Claudio Bustos  clbustos#entelchile.net
+if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); 
+
+define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');
+
+/**
+* Default Error Handler. This will be called with the following params
+*
+* @param $dbms         the RDBMS you are connecting to
+* @param $fn           the name of the calling function (in uppercase)
+* @param $errno                the native error number from the database
+* @param $errmsg       the native error msg from the database
+* @param $p1           $fn specific parameter - see below
+* @param $p2           $fn specific parameter - see below
+* @param $thisConn     $current connection object - can be false if no connection object created
+*/
+function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
+{
+       if (error_reporting() == 0) return; // obey @ protocol
+       switch($fn) {
+       case 'EXECUTE':
+               $sql = $p1;
+               $inputparams = $p2;
+
+               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n";
+               break;
+
+       case 'PCONNECT':
+       case 'CONNECT':
+               $host = $p1;
+               $database = $p2;
+
+               $s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n";
+               break;
+       default:
+               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
+               break;
+       }
+       /*
+       * Log connection error somewhere
+       *       0 message is sent to PHP's system logger, using the Operating System's system
+       *               logging mechanism or a file, depending on what the error_log configuration
+       *               directive is set to.
+       *       1 message is sent by email to the address in the destination parameter.
+       *               This is the only message type where the fourth parameter, extra_headers is used.
+       *               This message type uses the same internal function as mail() does.
+       *       2 message is sent through the PHP debugging connection.
+       *               This option is only available if remote debugging has been enabled.
+       *               In this case, the destination parameter specifies the host name or IP address
+       *               and optionally, port number, of the socket receiving the debug information.
+       *       3 message is appended to the file destination
+       */
+       if (defined('ADODB_ERROR_LOG_TYPE')) {
+               $t = date('Y-m-d H:i:s');
+               if (defined('ADODB_ERROR_LOG_DEST'))
+                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST);
+               else
+                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE);
+       }
+
+
+       //print "<p>$s</p>";
+       trigger_error($s,ADODB_ERROR_HANDLER_TYPE); 
+}
+?>
index c83f73334a19e71bc9b46d6d9f95d829b09d6565..ddc13aebb393a5d074e4cbaf4d0bd09d275ef9b4 100644 (file)
@@ -1,88 +1,88 @@
-<?php\r
-/** \r
- * @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
- *\r
- * Set tabs to 4 for best viewing.\r
- * \r
- * Latest version is available at http://php.weblogs.com\r
- * \r
-*/\r
-include_once('PEAR.php');\r
-\r
-define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR');\r
-\r
-/*\r
-* Enabled the following if you want to terminate scripts when an error occurs\r
-*/\r
-//PEAR::setErrorHandling (PEAR_ERROR_DIE);\r
-\r
-/*\r
-* Name of the PEAR_Error derived class to call.\r
-*/\r
-if (!defined('ADODB_PEAR_ERROR_CLASS')) define('ADODB_PEAR_ERROR_CLASS','PEAR_Error');\r
-\r
-/*\r
-* Store the last PEAR_Error object here\r
-*/\r
-global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false;\r
-\r
-  /**\r
-* Error Handler with PEAR support. This will be called with the following params\r
-*\r
-* @param $dbms         the RDBMS you are connecting to\r
-* @param $fn           the name of the calling function (in uppercase)\r
-* @param $errno                the native error number from the database \r
-* @param $errmsg       the native error msg from the database\r
-* @param $p1           $fn specific parameter - see below\r
-* @param $P2           $fn specific parameter - see below\r
-       */\r
-function ADODB_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)\r
-{\r
-global $ADODB_Last_PEAR_Error;\r
-       \r
-       if (error_reporting() == 0) return; // obey @ protocol\r
-       switch($fn) {\r
-       case 'EXECUTE':\r
-               $sql = $p1;\r
-               $inputparams = $p2;\r
-               \r
-               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")";\r
-               break;\r
-               \r
-       case 'PCONNECT':\r
-       case 'CONNECT':\r
-               $host = $p1;\r
-               $database = $p2;\r
-               \r
-               $s = "$dbms error: [$errno: $errmsg] in $fn('$host', ?, ?, '$database')";\r
-               break;\r
-               \r
-       default:\r
-               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)";\r
-               break;\r
-       }\r
-       \r
-       $class = ADODB_PEAR_ERROR_CLASS;\r
-       $ADODB_Last_PEAR_Error = new $class($s, $errno,\r
-               $GLOBALS['_PEAR_default_error_mode'],\r
-               $GLOBALS['_PEAR_default_error_options'], \r
-               $errmsg);\r
-               \r
-       //print "<p>!$s</p>";\r
-}\r
-\r
-/**\r
-* Returns last PEAR_Error object. This error might be for an error that\r
-* occured several sql statements ago.\r
-*/\r
-function &ADODB_PEAR_Error()\r
-{\r
-global $ADODB_Last_PEAR_Error;\r
-\r
-       return $ADODB_Last_PEAR_Error;\r
-}\r
-               \r
+<?php
+/** 
+ * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com
+ * 
+*/
+include_once('PEAR.php');
+
+define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR');
+
+/*
+* Enabled the following if you want to terminate scripts when an error occurs
+*/
+//PEAR::setErrorHandling (PEAR_ERROR_DIE);
+
+/*
+* Name of the PEAR_Error derived class to call.
+*/
+if (!defined('ADODB_PEAR_ERROR_CLASS')) define('ADODB_PEAR_ERROR_CLASS','PEAR_Error');
+
+/*
+* Store the last PEAR_Error object here
+*/
+global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false;
+
+  /**
+* Error Handler with PEAR support. This will be called with the following params
+*
+* @param $dbms         the RDBMS you are connecting to
+* @param $fn           the name of the calling function (in uppercase)
+* @param $errno                the native error number from the database 
+* @param $errmsg       the native error msg from the database
+* @param $p1           $fn specific parameter - see below
+* @param $P2           $fn specific parameter - see below
+       */
+function ADODB_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)
+{
+global $ADODB_Last_PEAR_Error;
+       
+       if (error_reporting() == 0) return; // obey @ protocol
+       switch($fn) {
+       case 'EXECUTE':
+               $sql = $p1;
+               $inputparams = $p2;
+               
+               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")";
+               break;
+               
+       case 'PCONNECT':
+       case 'CONNECT':
+               $host = $p1;
+               $database = $p2;
+               
+               $s = "$dbms error: [$errno: $errmsg] in $fn('$host', ?, ?, '$database')";
+               break;
+               
+       default:
+               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)";
+               break;
+       }
+       
+       $class = ADODB_PEAR_ERROR_CLASS;
+       $ADODB_Last_PEAR_Error = new $class($s, $errno,
+               $GLOBALS['_PEAR_default_error_mode'],
+               $GLOBALS['_PEAR_default_error_options'], 
+               $errmsg);
+               
+       //print "<p>!$s</p>";
+}
+
+/**
+* Returns last PEAR_Error object. This error might be for an error that
+* occured several sql statements ago.
+*/
+function &ADODB_PEAR_Error()
+{
+global $ADODB_Last_PEAR_Error;
+
+       return $ADODB_Last_PEAR_Error;
+}
+               
 ?>
\ No newline at end of file
index 0e70ac1489879890a411064869acc9be7c6383d2..e4378e3283a18293cce893ea25a37f137c8e290f 100644 (file)
@@ -1,77 +1,78 @@
-<?php\r
-\r
-/**\r
- * @version V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license.\r
- * Whenever there is any discrepancy between the two licenses,\r
- * the BSD license will take precedence.\r
- *\r
- * Set tabs to 4 for best viewing.\r
- *\r
- * Latest version is available at http://php.weblogs.com\r
- *\r
- * Exception-handling code using PHP5 exceptions (try-catch-throw).\r
- */\r
-       \r
-if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); \r
-define('ADODB_ERROR_HANDLER','adodb_throw');\r
-\r
-class ADODB_Exception extends Exception {\r
-var $dbms;\r
-var $fn;\r
-var $sql = '';\r
-var $params = '';\r
-var $host = '';\r
-var $database = '';\r
-\r
-       function __construct($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)\r
-       {\r
-               switch($fn) {\r
-               case 'EXECUTE':\r
-                       $this->sql = $p1;\r
-                       $this->params = $p2;\r
-                       $s = "$dbms error: [$errno: $errmsg] in $fn(\"$p1\")\n";\r
-                       break;\r
-       \r
-               case 'PCONNECT':\r
-               case 'CONNECT':\r
-                       $user = $thisConnection->user;\r
-                       $s = "$dbms error: [$errno: $errmsg] in $fn($p1, '$user', '****', $p2)\n";\r
-                       break;\r
-               default:\r
-                       $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";\r
-                       break;\r
-               }\r
-       \r
-               $this->dbms = $dbms;\r
-               $this->host = $thisConnection->host;\r
-               $this->database = $thisConnection->database;\r
-               $this->fn = $fn;\r
-               $this->msg = $errmsg;\r
-                               \r
-               parent::__construct($s,$errno);\r
-       }\r
-}\r
-\r
-/**\r
-* Default Error Handler. This will be called with the following params\r
-*\r
-* @param $dbms         the RDBMS you are connecting to\r
-* @param $fn           the name of the calling function (in uppercase)\r
-* @param $errno                the native error number from the database\r
-* @param $errmsg       the native error msg from the database\r
-* @param $p1           $fn specific parameter - see below\r
-* @param $P2           $fn specific parameter - see below\r
-*/\r
-\r
-function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)\r
-{\r
-global $ADODB_EXCEPTION;\r
-\r
-       if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION;\r
-       else $errfn = 'ADODB_EXCEPTION';\r
-       throw new $errfn($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection);\r
-}\r
-\r
-\r
+<?php
+
+/**
+ * @version V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license.
+ * Whenever there is any discrepancy between the two licenses,
+ * the BSD license will take precedence.
+ *
+ * Set tabs to 4 for best viewing.
+ *
+ * Latest version is available at http://php.weblogs.com
+ *
+ * Exception-handling code using PHP5 exceptions (try-catch-throw).
+ */
+       
+if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); 
+define('ADODB_ERROR_HANDLER','adodb_throw');
+
+class ADODB_Exception extends Exception {
+var $dbms;
+var $fn;
+var $sql = '';
+var $params = '';
+var $host = '';
+var $database = '';
+       
+       function __construct($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
+       {
+               switch($fn) {
+               case 'EXECUTE':
+                       $this->sql = $p1;
+                       $this->params = $p2;
+                       $s = "$dbms error: [$errno: $errmsg] in $fn(\"$p1\")\n";
+                       break;
+       
+               case 'PCONNECT':
+               case 'CONNECT':
+                       $user = $thisConnection->user;
+                       $s = "$dbms error: [$errno: $errmsg] in $fn($p1, '$user', '****', $p2)\n";
+                       break;
+               default:
+                       $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
+                       break;
+               }
+       
+               $this->dbms = $dbms;
+               $this->host = $thisConnection->host;
+               $this->database = $thisConnection->database;
+               $this->fn = $fn;
+               $this->msg = $errmsg;
+                               
+               if (!is_numeric($errno)) $errno = -1;
+               parent::__construct($s,$errno);
+       }
+}
+
+/**
+* Default Error Handler. This will be called with the following params
+*
+* @param $dbms         the RDBMS you are connecting to
+* @param $fn           the name of the calling function (in uppercase)
+* @param $errno                the native error number from the database
+* @param $errmsg       the native error msg from the database
+* @param $p1           $fn specific parameter - see below
+* @param $P2           $fn specific parameter - see below
+*/
+
+function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
+{
+global $ADODB_EXCEPTION;
+
+       if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION;
+       else $errfn = 'ADODB_EXCEPTION';
+       throw new $errfn($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection);
+}
+
+
 ?>
\ No newline at end of file
index 1817fade3042853d306029aa0604d9ef6b1c257c..f1d794f9a44d581ce4f3c35ce8690ead55ff3dd3 100644 (file)
@@ -1,56 +1,56 @@
-<?php\r
-\r
-/*\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  \r
-  Set tabs to 4.\r
-  \r
-  PHP5 Iterator Class:\r
-  \r
-               $rs = $db->Execute("select * from adoxyz");\r
-               foreach($rs as $k => $v) {\r
-                       echo $k; print_r($v); echo "<br>";\r
-               }\r
- */\r
\r
-class ADODB_Iterator implements Iterator {\r
-\r
-    private $rs;\r
-\r
-    function __construct($rs) \r
-       {\r
-        $this->rs = $rs;\r
-    }\r
-    function rewind() \r
-       {\r
-        $this->rs->MoveFirst();\r
-    }\r
-    function hasMore() \r
-       {\r
-        return !$this->rs->EOF;\r
-    }\r
-    function key() \r
-       {\r
-        return $this->rs->_currentRow;\r
-    }\r
-    function current() \r
-       {\r
-        return $this->rs->fields;\r
-    }\r
-    function next() \r
-       {\r
-        $this->rs->MoveNext();\r
-    }\r
-}\r
-\r
-\r
-class ADODB_BASE_RS implements IteratorAggregate {\r
-    function getIterator() {\r
-        return new ADODB_Iterator($this);\r
-    }\r
-} \r
-\r
+<?php
+
+/*
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  
+  Set tabs to 4.
+  
+  PHP5 Iterator Class:
+  
+               $rs = $db->Execute("select * from adoxyz");
+               foreach($rs as $k => $v) {
+                       echo $k; print_r($v); echo "<br>";
+               }
+ */
+class ADODB_Iterator implements Iterator {
+
+    private $rs;
+
+    function __construct($rs) 
+       {
+        $this->rs = $rs;
+    }
+    function rewind() 
+       {
+        $this->rs->MoveFirst();
+    }
+    function hasMore() 
+       {
+        return !$this->rs->EOF;
+    }
+    function key() 
+       {
+        return $this->rs->_currentRow;
+    }
+    function current() 
+       {
+        return $this->rs->fields;
+    }
+    function next() 
+       {
+        $this->rs->MoveNext();
+    }
+}
+
+
+class ADODB_BASE_RS implements IteratorAggregate {
+    function getIterator() {
+        return new ADODB_Iterator($this);
+    }
+} 
+
 ?>
\ No newline at end of file
index 1c8d360d519fadb77ce747b9bf13fee7a3fbce2d..271de9d1fd21984be01459230e9c21e80a584ab8 100644 (file)
-<?php\r
-\r
-global $ADODB_INCLUDED_LIB;\r
-$ADODB_INCLUDED_LIB = 1;\r
-\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. See License.txt. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Less commonly used functions are placed here to reduce size of adodb.inc.php. \r
-*/ \r
-\r
-\r
-// Force key to upper. \r
-// See also http://www.php.net/manual/en/function.array-change-key-case.php\r
-function _array_change_key_case($an_array)\r
-{\r
-       if (is_array($an_array)) {\r
-               foreach($an_array as $key=>$value)\r
-               $new_array[strtoupper($key)] = $value;\r
-\r
-               return $new_array;\r
-   }\r
-\r
-       return $an_array;\r
-}\r
-\r
-function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)\r
-{\r
-               if (count($fieldArray) == 0) return 0;\r
-               $first = true;\r
-               $uSet = '';\r
-               \r
-               if (!is_array($keyCol)) {\r
-                       $keyCol = array($keyCol);\r
-               }\r
-               foreach($fieldArray as $k => $v) {\r
-                       if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=0) {\r
-                               $v = $zthis->qstr($v);\r
-                               $fieldArray[$k] = $v;\r
-                       }\r
-                       if (in_array($k,$keyCol)) continue; // skip UPDATE if is key\r
-                       \r
-                       if ($first) {\r
-                               $first = false;                 \r
-                               $uSet = "$k=$v";\r
-                       } else\r
-                               $uSet .= ",$k=$v";\r
-               }\r
-                \r
-               $where = false;\r
-               foreach ($keyCol as $v) {\r
-                       if ($where) $where .= " and $v=$fieldArray[$v]";\r
-                       else $where = "$v=$fieldArray[$v]";\r
-               }\r
-               \r
-               if ($uSet && $where) {\r
-                       $update = "UPDATE $table SET $uSet WHERE $where";\r
-                       \r
-                       $rs = $zthis->Execute($update);\r
-                       if ($rs) {\r
-                               if ($zthis->poorAffectedRows) {\r
-                               /*\r
-                                The Select count(*) wipes out any errors that the update would have returned. \r
-                               http://phplens.com/lens/lensforum/msgs.php?id=5696\r
-                               */\r
-                                       if ($zthis->ErrorNo()<>0) return 0;\r
-                                       \r
-                               # affected_rows == 0 if update field values identical to old values\r
-                               # for mysql - which is silly. \r
-                       \r
-                                       $cnt = $zthis->GetOne("select count(*) from $table where $where");\r
-                                       if ($cnt > 0) return 1; // record already exists\r
-                               } else\r
-                                        if (($zthis->Affected_Rows()>0)) return 1;\r
-                       }\r
-               }\r
-       //      print "<p>Error=".$this->ErrorNo().'<p>';\r
-               $first = true;\r
-               foreach($fieldArray as $k => $v) {\r
-                       if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col\r
-                       \r
-                       if ($first) {\r
-                               $first = false;                 \r
-                               $iCols = "$k";\r
-                               $iVals = "$v";\r
-                       } else {\r
-                               $iCols .= ",$k";\r
-                               $iVals .= ",$v";\r
-                       }                               \r
-               }\r
-               $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; \r
-               $rs = $zthis->Execute($insert);\r
-               return ($rs) ? 2 : 0;\r
-}\r
-\r
-// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM\r
-function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,\r
-                       $size=0, $selectAttr='',$compareFields0=true)\r
-{\r
-       $hasvalue = false;\r
-\r
-       if ($multiple or is_array($defstr)) {\r
-               if ($size==0) $size=5;\r
-               $attr = " multiple size=$size";\r
-               if (!strpos($name,'[]')) $name .= '[]';\r
-       } else if ($size) $attr = " size=$size";\r
-       else $attr ='';\r
-\r
-       $s = "<select name=\"$name\"$attr $selectAttr>";\r
-       if ($blank1stItem) \r
-               if (is_string($blank1stItem))  {\r
-                       $barr = explode(':',$blank1stItem);\r
-                       if (sizeof($barr) == 1) $barr[] = '';\r
-                       $s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";\r
-               } else $s .= "\n<option></option>";\r
-\r
-       if ($zthis->FieldCount() > 1) $hasvalue=true;\r
-       else $compareFields0 = true;\r
-       \r
-       $value = '';\r
-       while(!$zthis->EOF) {\r
-               $zval = trim(reset($zthis->fields));\r
-               if (sizeof($zthis->fields) > 1) {\r
-                       if (isset($zthis->fields[1]))\r
-                               $zval2 = trim($zthis->fields[1]);\r
-                       else\r
-                               $zval2 = trim(next($zthis->fields));\r
-               }\r
-               $selected = ($compareFields0) ? $zval : $zval2;\r
-               \r
-               if ($blank1stItem && $zval=="") {\r
-                       $zthis->MoveNext();\r
-                       continue;\r
-               }\r
-               if ($hasvalue) \r
-                       $value = ' value="'.htmlspecialchars($zval2).'"';\r
-               \r
-               if (is_array($defstr))  {\r
-                       \r
-                       if (in_array($selected,$defstr)) \r
-                               $s .= "<option selected$value>".htmlspecialchars($zval).'</option>';\r
-                       else \r
-                               $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';\r
-               }\r
-               else {\r
-                       if (strcasecmp($selected,$defstr)==0) \r
-                               $s .= "<option selected$value>".htmlspecialchars($zval).'</option>';\r
-                       else\r
-                               $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';\r
-               }\r
-               $zthis->MoveNext();\r
-       } // while\r
-       \r
-       return $s ."\n</select>\n";\r
-}\r
-\r
-/*\r
-       Count the number of records this sql statement will return by using\r
-       query rewriting techniques...\r
-       \r
-       Does not work with UNIONs.\r
-*/\r
-function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) \r
-{\r
-       $qryRecs = 0;\r
-       \r
-        if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) {\r
-               // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias\r
-               // but this is only supported by oracle and postgresql...\r
-               if ($zthis->dataProvider == 'oci8') {\r
-                       \r
-                       $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);\r
-                       $rewritesql = "SELECT COUNT(*) FROM ($rewritesql)"; \r
-                       \r
-               } else if ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7')  {\r
-                       \r
-                       $info = $zthis->ServerInfo();\r
-                       if (substr($info['version'],0,3) >= 7.1) { // good till version 999\r
-                               $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);\r
-                               $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";\r
-                       }\r
-               }\r
-       } else { \r
-               // now replace SELECT ... FROM with SELECT COUNT(*) FROM\r
-               \r
-               $rewritesql = preg_replace(\r
-                                       '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);\r
-               \r
-               // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails \r
-               // with mssql, access and postgresql. Also a good speedup optimization - skips sorting!\r
-               $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql); \r
-       }\r
-       \r
-       if (isset($rewritesql) && $rewritesql != $sql) {\r
-               if ($secs2cache) {\r
-                       // we only use half the time of secs2cache because the count can quickly\r
-                       // become inaccurate if new records are added\r
-                       $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);\r
-                       \r
-               } else {\r
-                       $qryRecs = $zthis->GetOne($rewritesql,$inputarr);\r
-               }\r
-               if ($qryRecs !== false) return $qryRecs;\r
-       }\r
-       \r
-       //--------------------------------------------\r
-       // query rewrite failed - so try slower way...\r
-       \r
-       // strip off unneeded ORDER BY\r
-       $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); \r
-       $rstest = &$zthis->Execute($rewritesql,$inputarr);\r
-       if ($rstest) {\r
-               $qryRecs = $rstest->RecordCount();\r
-               if ($qryRecs == -1) { \r
-               global $ADODB_EXTENSION;\r
-               // some databases will return -1 on MoveLast() - change to MoveNext()\r
-                       if ($ADODB_EXTENSION) {\r
-                               while(!$rstest->EOF) {\r
-                                       adodb_movenext($rstest);\r
-                               }\r
-                       } else {\r
-                               while(!$rstest->EOF) {\r
-                                       $rstest->MoveNext();\r
-                               }\r
-                       }\r
-                       $qryRecs = $rstest->_currentRow;\r
-               }\r
-               $rstest->Close();\r
-               if ($qryRecs == -1) return 0;\r
-       }\r
-\r
-       return $qryRecs;\r
-}\r
-\r
-/*\r
-       Code originally from "Cornel G" <conyg@fx.ro>\r
-\r
-       This code will not work with SQL that has UNION in it   \r
-       \r
-       Also if you are using CachePageExecute(), there is a strong possibility that\r
-       data will get out of synch. use CachePageExecute() only with tables that\r
-       rarely change.\r
-*/\r
-function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, \r
-                                               $inputarr=false, $secs2cache=0) \r
-{\r
-       $atfirstpage = false;\r
-       $atlastpage = false;\r
-       $lastpageno=1;\r
-\r
-       // If an invalid nrows is supplied, \r
-       // we assume a default value of 10 rows per page\r
-       if (!isset($nrows) || $nrows <= 0) $nrows = 10;\r
-\r
-       $qryRecs = false; //count records for no offset\r
-       \r
-       $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);\r
-       $lastpageno = (int) ceil($qryRecs / $nrows);\r
-       $zthis->_maxRecordCount = $qryRecs;\r
-       \r
-       // If page number <= 1, then we are at the first page\r
-       if (!isset($page) || $page <= 1) {      \r
-               $page = 1;\r
-               $atfirstpage = true;\r
-       }\r
-\r
-       // ***** Here we check whether $page is the last page or \r
-       // whether we are trying to retrieve \r
-       // a page number greater than the last page number.\r
-       if ($page >= $lastpageno) {\r
-               $page = $lastpageno;\r
-               $atlastpage = true;\r
-       }\r
-       \r
-       // We get the data we want\r
-       $offset = $nrows * ($page-1);\r
-       if ($secs2cache > 0) \r
-               $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);\r
-       else \r
-               $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);\r
-\r
-       \r
-       // Before returning the RecordSet, we set the pagination properties we need\r
-       if ($rsreturn) {\r
-               $rsreturn->_maxRecordCount = $qryRecs;\r
-               $rsreturn->rowsPerPage = $nrows;\r
-               $rsreturn->AbsolutePage($page);\r
-               $rsreturn->AtFirstPage($atfirstpage);\r
-               $rsreturn->AtLastPage($atlastpage);\r
-               $rsreturn->LastPageNo($lastpageno);\r
-       }\r
-       return $rsreturn;\r
-}\r
-\r
-// Iván Oliva version\r
-function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) \r
-{\r
-\r
-       $atfirstpage = false;\r
-       $atlastpage = false;\r
-       \r
-       if (!isset($page) || $page <= 1) {      // If page number <= 1, then we are at the first page\r
-               $page = 1;\r
-               $atfirstpage = true;\r
-       }\r
-       if ($nrows <= 0) $nrows = 10;   // If an invalid nrows is supplied, we assume a default value of 10 rows per page\r
-       \r
-       // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than \r
-       // the last page number.\r
-       $pagecounter = $page + 1;\r
-       $pagecounteroffset = ($pagecounter * $nrows) - $nrows;\r
-       if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);\r
-       else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);\r
-       if ($rstest) {\r
-               while ($rstest && $rstest->EOF && $pagecounter>0) {\r
-                       $atlastpage = true;\r
-                       $pagecounter--;\r
-                       $pagecounteroffset = $nrows * ($pagecounter - 1);\r
-                       $rstest->Close();\r
-                       if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);\r
-                       else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);\r
-               }\r
-               if ($rstest) $rstest->Close();\r
-       }\r
-       if ($atlastpage) {      // If we are at the last page or beyond it, we are going to retrieve it\r
-               $page = $pagecounter;\r
-               if ($page == 1) $atfirstpage = true;    // We have to do this again in case the last page is the same as the first\r
-                       //... page, that is, the recordset has only 1 page.\r
-       }\r
-       \r
-       // We get the data we want\r
-       $offset = $nrows * ($page-1);\r
-       if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);\r
-       else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);\r
-       \r
-       // Before returning the RecordSet, we set the pagination properties we need\r
-       if ($rsreturn) {\r
-               $rsreturn->rowsPerPage = $nrows;\r
-               $rsreturn->AbsolutePage($page);\r
-               $rsreturn->AtFirstPage($atfirstpage);\r
-               $rsreturn->AtLastPage($atlastpage);\r
-       }\r
-       return $rsreturn;\r
-}\r
-\r
-function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false)\r
-{\r
-               if (!$rs) {\r
-                       printf(ADODB_BAD_RS,'GetUpdateSQL');\r
-                       return false;\r
-               }\r
-       \r
-               $fieldUpdatedCount = 0;\r
-               $arrFields = _array_change_key_case($arrFields);\r
-\r
-               $hasnumeric = isset($rs->fields[0]);\r
-               $updateSQL = '';\r
-               \r
-               // Loop through all of the fields in the recordset\r
-               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {\r
-               \r
-                       // Get the field from the recordset\r
-                       $field = $rs->FetchField($i);\r
-\r
-                       // If the recordset field is one\r
-                       // of the fields passed in then process.\r
-                       $upperfname = strtoupper($field->name);\r
-                       if (adodb_key_exists($upperfname,$arrFields)) {\r
-\r
-                               // If the existing field value in the recordset\r
-                               // is different from the value passed in then\r
-                               // go ahead and append the field name and new value to\r
-                               // the update query.\r
-                               \r
-                               if ($hasnumeric) $val = $rs->fields[$i];\r
-                               else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];\r
-                               else if (isset($rs->fields[$field->name])) $val =  $rs->fields[$field->name];\r
-                               else if (isset($rs->fields[strtolower($upperfname)])) $val =  $rs->fields[strtolower($upperfname)];\r
-                               else $val = '';\r
-                               \r
-                               if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {\r
-                                       // Set the counter for the number of fields that will be updated.\r
-                                       $fieldUpdatedCount++;\r
-\r
-                                       // Based on the datatype of the field\r
-                                       // Format the value properly for the database\r
-                                       $mt = $rs->MetaType($field->type);\r
-                                       \r
-                                       // "mike" <mike@partner2partner.com> patch and "Ryan Bailey" <rebel@windriders.com> \r
-                                       //PostgreSQL uses a 't' or 'f' and therefore needs to be processed as a string ('C') type field.\r
-                                       if ((strncmp($zthis->databaseType,"postgres",8) === 0) && ($mt == "L")) $mt = "C";\r
-                                       // is_null requires php 4.0.4\r
-                                       if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) || $arrFields[$upperfname] === 'null') \r
-                                               $updateSQL .= $field->name . " = null, ";\r
-                                       else            \r
-                                       switch($mt) {\r
-                                               case 'null':\r
-                                               case "C":\r
-                                               case "X":\r
-                                               case 'B':\r
-                                                       $updateSQL .= $field->name . " = " . $zthis->qstr($arrFields[$upperfname],$magicq) . ", ";\r
-                                                       break;\r
-                                               case "D":\r
-                                                       $updateSQL .= $field->name . " = " . $zthis->DBDate($arrFields[$upperfname]) . ", ";\r
-                                                       break;\r
-                                               case "T":\r
-                                                       $updateSQL .= $field->name . " = " . $zthis->DBTimeStamp($arrFields[$upperfname]) . ", ";\r
-                                                       break;\r
-                                               default:\r
-                                                       $val = $arrFields[$upperfname];\r
-                                                       if (!is_numeric($val)) $val = (float) $val;\r
-                                                       $updateSQL .= $field->name . " = " . $val  . ", ";\r
-                                                       break;\r
-                                       };\r
-                               };\r
-                       };\r
-               };\r
-\r
-               // If there were any modified fields then build the rest of the update query.\r
-               if ($fieldUpdatedCount > 0 || $forceUpdate) {\r
-               \r
-                                       // Get the table name from the existing query.\r
-                       preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);\r
-       \r
-                       // Get the full where clause excluding the word "WHERE" from\r
-                       // the existing query.\r
-                       preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);\r
-                       \r
-                       $discard = false;\r
-                       // not a good hack, improvements?\r
-                       if ($whereClause)\r
-                               preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard);\r
-                       else\r
-                               $whereClause = array(false,false);\r
-                               \r
-                       if ($discard)\r
-                               $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));\r
-                       \r
-                       // updateSQL will contain the full update query when all\r
-                       // processing has completed.\r
-                       $updateSQL = "UPDATE " . $tableName[1] . " SET ".substr($updateSQL, 0, -2);\r
-\r
-                       // If the recordset has a where clause then use that same where clause\r
-                       // for the update.\r
-                       if ($whereClause[1]) $updateSQL .= " WHERE " . $whereClause[1];\r
-\r
-                       return $updateSQL;\r
-               } else {\r
-                       return false;\r
-               };\r
-}\r
-\r
-function adodb_key_exists($key, &$arr)\r
-{\r
-       if (!defined('ADODB_FORCE_NULLS')) {\r
-               // the following is the old behaviour where null or empty fields are ignored\r
-               return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0);\r
-       }\r
-\r
-       if (isset($arr[$key])) return true;\r
-       ## null check below\r
-       if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr);\r
-       return false;\r
-}\r
-\r
-function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false)\r
-{\r
-       $values = '';\r
-       $fields = '';\r
-       $arrFields = _array_change_key_case($arrFields);\r
-       \r
-       if (!$rs) {\r
-               printf(ADODB_BAD_RS,'GetInsertSQL');\r
-               return false;\r
-       }\r
-\r
-       $fieldInsertedCount = 0;\r
-\r
-       // Loop through all of the fields in the recordset\r
-       for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {\r
-\r
-               // Get the field from the recordset\r
-               $field = $rs->FetchField($i);\r
-               // If the recordset field is one\r
-               // of the fields passed in then process.\r
-               $upperfname = strtoupper($field->name);\r
-               if (adodb_key_exists($upperfname,$arrFields)) {\r
-\r
-                       // Set the counter for the number of fields that will be inserted.\r
-                       $fieldInsertedCount++;\r
-\r
-                       // Get the name of the fields to insert\r
-                       $fields .= $field->name . ", ";\r
-                       \r
-                       $mt = $rs->MetaType($field->type);\r
-                       \r
-                       // "mike" <mike@partner2partner.com> patch and "Ryan Bailey" <rebel@windriders.com> \r
-                       //PostgreSQL uses a 't' or 'f' and therefore needs to be processed as a string ('C') type field.\r
-                       if ((strncmp($zthis->databaseType,"postgres",8) === 0) && ($mt == "L")) $mt = "C";\r
-\r
-                       // Based on the datatype of the field\r
-                       // Format the value properly for the database\r
-                       if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) || $arrFields[$upperfname] === 'null') \r
-                                       $values .= "null, ";\r
-                       else            \r
-                       switch($mt) {\r
-                               case "C":\r
-                               case "X":\r
-                               case 'B':\r
-                                       $values .= $zthis->qstr($arrFields[$upperfname],$magicq) . ", ";\r
-                                       break;\r
-                               case "D":\r
-                                       $values .= $zthis->DBDate($arrFields[$upperfname]) . ", ";\r
-                                       break;\r
-                               case "T":\r
-                                       $values .= $zthis->DBTimeStamp($arrFields[$upperfname]) . ", ";\r
-                                       break;\r
-                               default:\r
-                                       $val = $arrFields[$upperfname];\r
-                                       if (!is_numeric($val)) $val = (float) $val;\r
-                                       $values .= $val . ", ";\r
-                                       break;\r
-                       };\r
-               };\r
-       };\r
-\r
-       // If there were any inserted fields then build the rest of the insert query.\r
-       if ($fieldInsertedCount <= 0)  return false;\r
-       \r
-       // Get the table name from the existing query.\r
-       preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);\r
-\r
-       // Strip off the comma and space on the end of both the fields\r
-       // and their values.\r
-       $fields = substr($fields, 0, -2);\r
-       $values = substr($values, 0, -2);\r
-\r
-       // Append the fields and their values to the insert query.\r
-       $insertSQL = "INSERT INTO " . $tableName[1] . " ( $fields ) VALUES ( $values )";\r
-\r
-       return $insertSQL;\r
-}\r
-\r
-\r
+<?php
+
+global $ADODB_INCLUDED_LIB;
+$ADODB_INCLUDED_LIB = 1;
+
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Less commonly used functions are placed here to reduce size of adodb.inc.php. 
+*/ 
+
+
+// Force key to upper. 
+// See also http://www.php.net/manual/en/function.array-change-key-case.php
+function _array_change_key_case($an_array)
+{
+       if (is_array($an_array)) {
+               foreach($an_array as $key=>$value)
+               $new_array[strtoupper($key)] = $value;
+
+               return $new_array;
+   }
+
+       return $an_array;
+}
+
+function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)
+{
+               if (count($fieldArray) == 0) return 0;
+               $first = true;
+               $uSet = '';
+               
+               if (!is_array($keyCol)) {
+                       $keyCol = array($keyCol);
+               }
+               foreach($fieldArray as $k => $v) {
+                       if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=0) {
+                               $v = $zthis->qstr($v);
+                               $fieldArray[$k] = $v;
+                       }
+                       if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
+                       
+                       if ($first) {
+                               $first = false;                 
+                               $uSet = "$k=$v";
+                       } else
+                               $uSet .= ",$k=$v";
+               }
+                
+               $where = false;
+               foreach ($keyCol as $v) {
+                       if ($where) $where .= " and $v=$fieldArray[$v]";
+                       else $where = "$v=$fieldArray[$v]";
+               }
+               
+               if ($uSet && $where) {
+                       $update = "UPDATE $table SET $uSet WHERE $where";
+                       
+                       $rs = $zthis->Execute($update);
+                       if ($rs) {
+                               if ($zthis->poorAffectedRows) {
+                               /*
+                                The Select count(*) wipes out any errors that the update would have returned. 
+                               http://phplens.com/lens/lensforum/msgs.php?id=5696
+                               */
+                                       if ($zthis->ErrorNo()<>0) return 0;
+                                       
+                               # affected_rows == 0 if update field values identical to old values
+                               # for mysql - which is silly. 
+                       
+                                       $cnt = $zthis->GetOne("select count(*) from $table where $where");
+                                       if ($cnt > 0) return 1; // record already exists
+                               } else
+                                        if (($zthis->Affected_Rows()>0)) return 1;
+                       }
+               }
+       //      print "<p>Error=".$this->ErrorNo().'<p>';
+               $first = true;
+               foreach($fieldArray as $k => $v) {
+                       if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
+                       
+                       if ($first) {
+                               $first = false;                 
+                               $iCols = "$k";
+                               $iVals = "$v";
+                       } else {
+                               $iCols .= ",$k";
+                               $iVals .= ",$v";
+                       }                               
+               }
+               $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; 
+               $rs = $zthis->Execute($insert);
+               return ($rs) ? 2 : 0;
+}
+
+// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
+function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
+                       $size=0, $selectAttr='',$compareFields0=true)
+{
+       $hasvalue = false;
+
+       if ($multiple or is_array($defstr)) {
+               if ($size==0) $size=5;
+               $attr = " multiple size=$size";
+               if (!strpos($name,'[]')) $name .= '[]';
+       } else if ($size) $attr = " size=$size";
+       else $attr ='';
+
+       $s = "<select name=\"$name\"$attr $selectAttr>";
+       if ($blank1stItem) 
+               if (is_string($blank1stItem))  {
+                       $barr = explode(':',$blank1stItem);
+                       if (sizeof($barr) == 1) $barr[] = '';
+                       $s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
+               } else $s .= "\n<option></option>";
+
+       if ($zthis->FieldCount() > 1) $hasvalue=true;
+       else $compareFields0 = true;
+       
+       $value = '';
+       while(!$zthis->EOF) {
+               $zval = trim(reset($zthis->fields));
+               if (sizeof($zthis->fields) > 1) {
+                       if (isset($zthis->fields[1]))
+                               $zval2 = trim($zthis->fields[1]);
+                       else
+                               $zval2 = trim(next($zthis->fields));
+               }
+               $selected = ($compareFields0) ? $zval : $zval2;
+               
+               if ($blank1stItem && $zval=="") {
+                       $zthis->MoveNext();
+                       continue;
+               }
+               if ($hasvalue) 
+                       $value = ' value="'.htmlspecialchars($zval2).'"';
+               
+               if (is_array($defstr))  {
+                       
+                       if (in_array($selected,$defstr)) 
+                               $s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
+                       else 
+                               $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
+               }
+               else {
+                       if (strcasecmp($selected,$defstr)==0) 
+                               $s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
+                       else
+                               $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
+               }
+               $zthis->MoveNext();
+       } // while
+       
+       return $s ."\n</select>\n";
+}
+
+/*
+       Count the number of records this sql statement will return by using
+       query rewriting techniques...
+       
+       Does not work with UNIONs.
+*/
+function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) 
+{
+       $qryRecs = 0;
+       
+        if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) {
+               // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
+               // but this is only supported by oracle and postgresql...
+               if ($zthis->dataProvider == 'oci8') {
+                       
+                       $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
+                       $rewritesql = "SELECT COUNT(*) FROM ($rewritesql)"; 
+                       
+               } else if ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7')  {
+                       
+                       $info = $zthis->ServerInfo();
+                       if (substr($info['version'],0,3) >= 7.1) { // good till version 999
+                               $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
+                               $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
+                       }
+               }
+       } else { 
+               // now replace SELECT ... FROM with SELECT COUNT(*) FROM
+               
+               $rewritesql = preg_replace(
+                                       '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
+               
+               // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails 
+               // with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
+               $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql); 
+       }
+       
+       if (isset($rewritesql) && $rewritesql != $sql) {
+               if ($secs2cache) {
+                       // we only use half the time of secs2cache because the count can quickly
+                       // become inaccurate if new records are added
+                       $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
+                       
+               } else {
+                       $qryRecs = $zthis->GetOne($rewritesql,$inputarr);
+               }
+               if ($qryRecs !== false) return $qryRecs;
+       }
+       
+       //--------------------------------------------
+       // query rewrite failed - so try slower way...
+       
+       // strip off unneeded ORDER BY
+       $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); 
+       $rstest = &$zthis->Execute($rewritesql,$inputarr);
+       if ($rstest) {
+               $qryRecs = $rstest->RecordCount();
+               if ($qryRecs == -1) { 
+               global $ADODB_EXTENSION;
+               // some databases will return -1 on MoveLast() - change to MoveNext()
+                       if ($ADODB_EXTENSION) {
+                               while(!$rstest->EOF) {
+                                       adodb_movenext($rstest);
+                               }
+                       } else {
+                               while(!$rstest->EOF) {
+                                       $rstest->MoveNext();
+                               }
+                       }
+                       $qryRecs = $rstest->_currentRow;
+               }
+               $rstest->Close();
+               if ($qryRecs == -1) return 0;
+       }
+
+       return $qryRecs;
+}
+
+/*
+       Code originally from "Cornel G" <conyg@fx.ro>
+
+       This code will not work with SQL that has UNION in it   
+       
+       Also if you are using CachePageExecute(), there is a strong possibility that
+       data will get out of synch. use CachePageExecute() only with tables that
+       rarely change.
+*/
+function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, 
+                                               $inputarr=false, $secs2cache=0) 
+{
+       $atfirstpage = false;
+       $atlastpage = false;
+       $lastpageno=1;
+
+       // If an invalid nrows is supplied, 
+       // we assume a default value of 10 rows per page
+       if (!isset($nrows) || $nrows <= 0) $nrows = 10;
+
+       $qryRecs = false; //count records for no offset
+       
+       $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
+       $lastpageno = (int) ceil($qryRecs / $nrows);
+       $zthis->_maxRecordCount = $qryRecs;
+       
+       // If page number <= 1, then we are at the first page
+       if (!isset($page) || $page <= 1) {      
+               $page = 1;
+               $atfirstpage = true;
+       }
+
+       // ***** Here we check whether $page is the last page or 
+       // whether we are trying to retrieve 
+       // a page number greater than the last page number.
+       if ($page >= $lastpageno) {
+               $page = $lastpageno;
+               $atlastpage = true;
+       }
+       
+       // We get the data we want
+       $offset = $nrows * ($page-1);
+       if ($secs2cache > 0) 
+               $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
+       else 
+               $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
+
+       
+       // Before returning the RecordSet, we set the pagination properties we need
+       if ($rsreturn) {
+               $rsreturn->_maxRecordCount = $qryRecs;
+               $rsreturn->rowsPerPage = $nrows;
+               $rsreturn->AbsolutePage($page);
+               $rsreturn->AtFirstPage($atfirstpage);
+               $rsreturn->AtLastPage($atlastpage);
+               $rsreturn->LastPageNo($lastpageno);
+       }
+       return $rsreturn;
+}
+
+// Iván Oliva version
+function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
+{
+
+       $atfirstpage = false;
+       $atlastpage = false;
+       
+       if (!isset($page) || $page <= 1) {      // If page number <= 1, then we are at the first page
+               $page = 1;
+               $atfirstpage = true;
+       }
+       if ($nrows <= 0) $nrows = 10;   // If an invalid nrows is supplied, we assume a default value of 10 rows per page
+       
+       // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than 
+       // the last page number.
+       $pagecounter = $page + 1;
+       $pagecounteroffset = ($pagecounter * $nrows) - $nrows;
+       if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
+       else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
+       if ($rstest) {
+               while ($rstest && $rstest->EOF && $pagecounter>0) {
+                       $atlastpage = true;
+                       $pagecounter--;
+                       $pagecounteroffset = $nrows * ($pagecounter - 1);
+                       $rstest->Close();
+                       if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
+                       else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
+               }
+               if ($rstest) $rstest->Close();
+       }
+       if ($atlastpage) {      // If we are at the last page or beyond it, we are going to retrieve it
+               $page = $pagecounter;
+               if ($page == 1) $atfirstpage = true;    // We have to do this again in case the last page is the same as the first
+                       //... page, that is, the recordset has only 1 page.
+       }
+       
+       // We get the data we want
+       $offset = $nrows * ($page-1);
+       if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
+       else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
+       
+       // Before returning the RecordSet, we set the pagination properties we need
+       if ($rsreturn) {
+               $rsreturn->rowsPerPage = $nrows;
+               $rsreturn->AbsolutePage($page);
+               $rsreturn->AtFirstPage($atfirstpage);
+               $rsreturn->AtLastPage($atlastpage);
+       }
+       return $rsreturn;
+}
+
+function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false)
+{
+               if (!$rs) {
+                       printf(ADODB_BAD_RS,'GetUpdateSQL');
+                       return false;
+               }
+       
+               $fieldUpdatedCount = 0;
+               $arrFields = _array_change_key_case($arrFields);
+
+               $hasnumeric = isset($rs->fields[0]);
+               $updateSQL = '';
+               
+               // Loop through all of the fields in the recordset
+               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
+               
+                       // Get the field from the recordset
+                       $field = $rs->FetchField($i);
+
+                       // If the recordset field is one
+                       // of the fields passed in then process.
+                       $upperfname = strtoupper($field->name);
+                       if (adodb_key_exists($upperfname,$arrFields)) {
+
+                               // If the existing field value in the recordset
+                               // is different from the value passed in then
+                               // go ahead and append the field name and new value to
+                               // the update query.
+                               
+                               if ($hasnumeric) $val = $rs->fields[$i];
+                               else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
+                               else if (isset($rs->fields[$field->name])) $val =  $rs->fields[$field->name];
+                               else if (isset($rs->fields[strtolower($upperfname)])) $val =  $rs->fields[strtolower($upperfname)];
+                               else $val = '';
+                               
+                               if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
+                                       // Set the counter for the number of fields that will be updated.
+                                       $fieldUpdatedCount++;
+
+                                       // Based on the datatype of the field
+                                       // Format the value properly for the database
+                                       $mt = $rs->MetaType($field->type);
+                                       
+                                       // "mike" <mike@partner2partner.com> patch and "Ryan Bailey" <rebel@windriders.com> 
+                                       //PostgreSQL uses a 't' or 'f' and therefore needs to be processed as a string ('C') type field.
+                                       if ((strncmp($zthis->databaseType,"postgres",8) === 0) && ($mt == "L")) $mt = "C";
+                                       // is_null requires php 4.0.4
+                                       if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) || $arrFields[$upperfname] === 'null') 
+                                               $updateSQL .= $field->name . " = null, ";
+                                       else            
+                                       switch($mt) {
+                                               case 'null':
+                                               case "C":
+                                               case "X":
+                                               case 'B':
+                                                       $updateSQL .= $field->name . " = " . $zthis->qstr($arrFields[$upperfname],$magicq) . ", ";
+                                                       break;
+                                               case "D":
+                                                       $updateSQL .= $field->name . " = " . $zthis->DBDate($arrFields[$upperfname]) . ", ";
+                                                       break;
+                                               case "T":
+                                                       $updateSQL .= $field->name . " = " . $zthis->DBTimeStamp($arrFields[$upperfname]) . ", ";
+                                                       break;
+                                               default:
+                                                       $val = $arrFields[$upperfname];
+                                                       /*if (!is_numeric($val)) {
+                                                               if (strncmp($val,'=',1) == 0) $val = substr($val,1);
+                                                               else $val = (float) $val;
+                                                       }*/
+                                                       if (empty($val)) $val = '0';
+
+                                                       $updateSQL .= $field->name . " = " . $val  . ", ";
+                                                       break;
+                                       };
+                               };
+                       };
+               };
+
+               // If there were any modified fields then build the rest of the update query.
+               if ($fieldUpdatedCount > 0 || $forceUpdate) {
+               
+                                       // Get the table name from the existing query.
+                       preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
+       
+                       // Get the full where clause excluding the word "WHERE" from
+                       // the existing query.
+                       preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
+                       
+                       $discard = false;
+                       // not a good hack, improvements?
+                       if ($whereClause)
+                               preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard);
+                       else
+                               $whereClause = array(false,false);
+                               
+                       if ($discard)
+                               $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
+                       
+                       // updateSQL will contain the full update query when all
+                       // processing has completed.
+                       $updateSQL = "UPDATE " . $tableName[1] . " SET ".substr($updateSQL, 0, -2);
+
+                       // If the recordset has a where clause then use that same where clause
+                       // for the update.
+                       if ($whereClause[1]) $updateSQL .= " WHERE " . $whereClause[1];
+
+                       return $updateSQL;
+               } else {
+                       return false;
+               };
+}
+
+function adodb_key_exists($key, &$arr)
+{
+       if (!defined('ADODB_FORCE_NULLS')) {
+               // the following is the old behaviour where null or empty fields are ignored
+               return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0);
+       }
+
+       if (isset($arr[$key])) return true;
+       ## null check below
+       if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr);
+       return false;
+}
+
+function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false)
+{
+       $values = '';
+       $fields = '';
+       $arrFields = _array_change_key_case($arrFields);
+       
+       if (!$rs) {
+               printf(ADODB_BAD_RS,'GetInsertSQL');
+               return false;
+       }
+
+       $fieldInsertedCount = 0;
+
+       // Loop through all of the fields in the recordset
+       for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
+
+               // Get the field from the recordset
+               $field = $rs->FetchField($i);
+               // If the recordset field is one
+               // of the fields passed in then process.
+               $upperfname = strtoupper($field->name);
+               if (adodb_key_exists($upperfname,$arrFields)) {
+
+                       // Set the counter for the number of fields that will be inserted.
+                       $fieldInsertedCount++;
+
+                       // Get the name of the fields to insert
+                       $fields .= $field->name . ", ";
+                       
+                       $mt = $rs->MetaType($field->type);
+                       
+                       // "mike" <mike@partner2partner.com> patch and "Ryan Bailey" <rebel@windriders.com> 
+                       //PostgreSQL uses a 't' or 'f' and therefore needs to be processed as a string ('C') type field.
+                       if ((strncmp($zthis->databaseType,"postgres",8) === 0) && ($mt == "L")) $mt = "C";
+
+                       // Based on the datatype of the field
+                       // Format the value properly for the database
+                       if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) || $arrFields[$upperfname] === 'null') 
+                                       $values .= "null, ";
+                       else            
+                       switch($mt) {
+                               case "C":
+                               case "X":
+                               case 'B':
+                                       $values .= $zthis->qstr($arrFields[$upperfname],$magicq) . ", ";
+                                       break;
+                               case "D":
+                                       $values .= $zthis->DBDate($arrFields[$upperfname]) . ", ";
+                                       break;
+                               case "T":
+                                       $values .= $zthis->DBTimeStamp($arrFields[$upperfname]) . ", ";
+                                       break;
+                               default:
+                                       $val = $arrFields[$upperfname];
+                                       /*if (!is_numeric($val)) {
+                                               if (strncmp($val,'=',1) == 0) $val = substr($val,1);
+                                               else $val = (float) $val;
+                                       }*/
+                                       if (empty($val)) $val = '0';
+                                       $values .= $val . ", ";
+                                       break;
+                       };
+               };
+       };
+
+       // If there were any inserted fields then build the rest of the insert query.
+       if ($fieldInsertedCount <= 0)  return false;
+       
+       // Get the table name from the existing query.
+       preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
+
+       // Strip off the comma and space on the end of both the fields
+       // and their values.
+       $fields = substr($fields, 0, -2);
+       $values = substr($values, 0, -2);
+
+       // Append the fields and their values to the insert query.
+       $insertSQL = "INSERT INTO " . $tableName[1] . " ( $fields ) VALUES ( $values )";
+
+       return $insertSQL;
+}
+
+
 ?>
\ No newline at end of file
index ebff53faf125881cf97aee33d90f2764482c1124..037636d7e251e65f08a5dd01d6c20c1e4a241fb8 100644 (file)
-<?php\r
-/*\r
-       V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-         Released under both BSD license and Lesser GPL library license. \r
-         Whenever there is any discrepancy between the two licenses, \r
-         the BSD license will take precedence. \r
-         Set tabs to 4 for best viewing.\r
-\r
-       This class provides recordset pagination with \r
-       First/Prev/Next/Last links. \r
-       \r
-       Feel free to modify this class for your own use as\r
-       it is very basic. To learn how to use it, see the \r
-       example in adodb/tests/testpaging.php.\r
-       \r
-       "Pablo Costa" <pablo@cbsp.com.br> implemented Render_PageLinks().\r
-       \r
-       Please note, this class is entirely unsupported, \r
-       and no free support requests except for bug reports\r
-       will be entertained by the author.\r
-\r
-*/\r
-class ADODB_Pager {\r
-       var $id;        // unique id for pager (defaults to 'adodb')\r
-       var $db;        // ADODB connection object\r
-       var $sql;       // sql used\r
-       var $rs;        // recordset generated\r
-       var $curr_page; // current page number before Render() called, calculated in constructor\r
-       var $rows;              // number of rows per page\r
-    var $linksPerPage=10; // number of links per page in navigation bar\r
-    var $showPageLinks; \r
-\r
-       var $gridAttributes = 'width=100% border=1 bgcolor=white';\r
-       \r
-       // Localize text strings here\r
-       var $first = '<code>|&lt;</code>';\r
-       var $prev = '<code>&lt;&lt;</code>';\r
-       var $next = '<code>>></code>';\r
-       var $last = '<code>>|</code>';\r
-       var $moreLinks = '...';\r
-       var $startLinks = '...';\r
-       var $gridHeader = false;\r
-       var $htmlSpecialChars = true;\r
-       var $page = 'Page';\r
-       var $linkSelectedColor = 'red';\r
-       var $cache = 0;  #secs to cache with CachePageExecute()\r
-       \r
-       //----------------------------------------------\r
-       // constructor\r
-       //\r
-       // $db  adodb connection object\r
-       // $sql sql statement\r
-       // $id  optional id to identify which pager, \r
-       //              if you have multiple on 1 page. \r
-       //              $id should be only be [a-z0-9]*\r
-       //\r
-       function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)\r
-       {\r
-       global $HTTP_SERVER_VARS,$PHP_SELF,$HTTP_SESSION_VARS,$HTTP_GET_VARS;\r
-       \r
-               $curr_page = $id.'_curr_page';\r
-               if (empty($PHP_SELF)) $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];\r
-               \r
-               $this->sql = $sql;\r
-               $this->id = $id;\r
-               $this->db = $db;\r
-               $this->showPageLinks = $showPageLinks;\r
-               \r
-               $next_page = $id.'_next_page';  \r
-               \r
-               if (isset($HTTP_GET_VARS[$next_page])) {\r
-                       $HTTP_SESSION_VARS[$curr_page] = $HTTP_GET_VARS[$next_page];\r
-               }\r
-               if (empty($HTTP_SESSION_VARS[$curr_page])) $HTTP_SESSION_VARS[$curr_page] = 1; ## at first page\r
-               \r
-               $this->curr_page = $HTTP_SESSION_VARS[$curr_page];\r
-               \r
-       }\r
-       \r
-       //---------------------------\r
-       // Display link to first page\r
-       function Render_First($anchor=true)\r
-       {\r
-       global $PHP_SELF;\r
-               if ($anchor) {\r
-       ?>\r
-               <a href="<?php echo $PHP_SELF,'?',$this->id;?>_next_page=1"><?php echo $this->first;?></a> &nbsp; \r
-       <?php\r
-               } else {\r
-                       print "$this->first &nbsp; ";\r
-               }\r
-       }\r
-       \r
-       //--------------------------\r
-       // Display link to next page\r
-       function render_next($anchor=true)\r
-       {\r
-       global $PHP_SELF;\r
-       \r
-               if ($anchor) {\r
-               ?>\r
-               <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() + 1 ?>"><?php echo $this->next;?></a> &nbsp; \r
-               <?php\r
-               } else {\r
-                       print "$this->next &nbsp; ";\r
-               }\r
-       }\r
-       \r
-       //------------------\r
-       // Link to last page\r
-       // \r
-       // for better performance with large recordsets, you can set\r
-       // $this->db->pageExecuteCountRows = false, which disables\r
-       // last page counting.\r
-       function render_last($anchor=true)\r
-       {\r
-       global $PHP_SELF;\r
-       \r
-               if (!$this->db->pageExecuteCountRows) return;\r
-               \r
-               if ($anchor) {\r
-               ?>\r
-                       <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->LastPageNo() ?>"><?php echo $this->last;?></a> &nbsp; \r
-               <?php\r
-               } else {\r
-                       print "$this->last &nbsp; ";\r
-               }\r
-       }\r
-       \r
-       //---------------------------------------------------\r
-       // original code by "Pablo Costa" <pablo@cbsp.com.br> \r
-        function render_pagelinks()\r
-        {\r
-        global $PHP_SELF;\r
-            $pages        = $this->rs->LastPageNo();\r
-            $linksperpage = $this->linksPerPage ? $this->linksPerPage : $pages;\r
-            for($i=1; $i <= $pages; $i+=$linksperpage)\r
-            {\r
-                if($this->rs->AbsolutePage() >= $i)\r
-                {\r
-                    $start = $i;\r
-                }\r
-            }\r
-                       $numbers = '';\r
-            $end = $start+$linksperpage-1;\r
-                       $link = $this->id . "_next_page";\r
-            if($end > $pages) $end = $pages;\r
-                       \r
-                       \r
-                       if ($this->startLinks && $start > 1) {\r
-                               $pos = $start - 1;\r
-                               $numbers .= "<a href=$PHP_SELF?$link=$pos>$this->startLinks</a>  ";\r
-            } \r
-                       \r
-                       for($i=$start; $i <= $end; $i++) {\r
-                if ($this->rs->AbsolutePage() == $i)\r
-                    $numbers .= "<font color=$this->linkSelectedColor><b>$i</b></font>  ";\r
-                else \r
-                     $numbers .= "<a href=$PHP_SELF?$link=$i>$i</a>  ";\r
-            \r
-            }\r
-                       if ($this->moreLinks && $end < $pages) \r
-                               $numbers .= "<a href=$PHP_SELF?$link=$i>$this->moreLinks</a>  ";\r
-            print $numbers . ' &nbsp; ';\r
-        }\r
-       // Link to previous page\r
-       function render_prev($anchor=true)\r
-       {\r
-       global $PHP_SELF;\r
-               if ($anchor) {\r
-       ?>\r
-               <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() - 1 ?>"><?php echo $this->prev;?></a> &nbsp; \r
-       <?php \r
-               } else {\r
-                       print "$this->prev &nbsp; ";\r
-               }\r
-       }\r
-       \r
-       //--------------------------------------------------------\r
-       // Simply rendering of grid. You should override this for\r
-       // better control over the format of the grid\r
-       //\r
-       // We use output buffering to keep code clean and readable.\r
-       function RenderGrid()\r
-       {\r
-       global $gSQLBlockRows; // used by rs2html to indicate how many rows to display\r
-               include_once(ADODB_DIR.'/tohtml.inc.php');\r
-               ob_start();\r
-               $gSQLBlockRows = $this->rows;\r
-               rs2html($this->rs,$this->gridAttributes,$this->gridHeader,$this->htmlSpecialChars);\r
-               $s = ob_get_contents();\r
-               ob_end_clean();\r
-               return $s;\r
-       }\r
-       \r
-       //-------------------------------------------------------\r
-       // Navigation bar\r
-       //\r
-       // we use output buffering to keep the code easy to read.\r
-       function RenderNav()\r
-       {\r
-               ob_start();\r
-               if (!$this->rs->AtFirstPage()) {\r
-                       $this->Render_First();\r
-                       $this->Render_Prev();\r
-               } else {\r
-                       $this->Render_First(false);\r
-                       $this->Render_Prev(false);\r
-               }\r
-        if ($this->showPageLinks){\r
-            $this->Render_PageLinks();\r
-        }\r
-               if (!$this->rs->AtLastPage()) {\r
-                       $this->Render_Next();\r
-                       $this->Render_Last();\r
-               } else {\r
-                       $this->Render_Next(false);\r
-                       $this->Render_Last(false);\r
-               }\r
-               $s = ob_get_contents();\r
-               ob_end_clean();\r
-               return $s;\r
-       }\r
-       \r
-       //-------------------\r
-       // This is the footer\r
-       function RenderPageCount()\r
-       {\r
-               if (!$this->db->pageExecuteCountRows) return '';\r
-               $lastPage = $this->rs->LastPageNo();\r
-               if ($lastPage == -1) $lastPage = 1; // check for empty rs.\r
-               return "<font size=-1>$this->page ".$this->curr_page."/".$lastPage."</font>";\r
-       }\r
-       \r
-       //-----------------------------------\r
-       // Call this class to draw everything.\r
-       function Render($rows=10)\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-       \r
-               $this->rows = $rows;\r
-               \r
-               $savec = $ADODB_COUNTRECS;\r
-               if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true;\r
-               if ($this->cache)\r
-                       $rs = &$this->db->CachePageExecute($this->cache,$this->sql,$rows,$this->curr_page);\r
-               else\r
-                       $rs = &$this->db->PageExecute($this->sql,$rows,$this->curr_page);\r
-               $ADODB_COUNTRECS = $savec;\r
-               \r
-               $this->rs = &$rs;\r
-               if (!$rs) {\r
-                       print "<h3>Query failed: $this->sql</h3>";\r
-                       return;\r
-               }\r
-               \r
-               if (!$rs->EOF && (!$rs->AtFirstPage() || !$rs->AtLastPage())) \r
-                       $header = $this->RenderNav();\r
-               else\r
-                       $header = "&nbsp;";\r
-               \r
-               $grid = $this->RenderGrid();\r
-               $footer = $this->RenderPageCount();\r
-               $rs->Close();\r
-               $this->rs = false;\r
-               \r
-               $this->RenderLayout($header,$grid,$footer);\r
-       }\r
-       \r
-       //------------------------------------------------------\r
-       // override this to control overall layout and formating\r
-       function RenderLayout($header,$grid,$footer,$attributes='border=1 bgcolor=beige')\r
-       {\r
-               echo "<table ".$attributes."><tr><td>",\r
-                               $header,\r
-                       "</td></tr><tr><td>",\r
-                               $grid,\r
-                       "</td></tr><tr><td>",\r
-                               $footer,\r
-                       "</td></tr></table>";\r
-       }\r
-}\r
-\r
-\r
-?>\r
+<?php
+/*
+       V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+         Released under both BSD license and Lesser GPL library license. 
+         Whenever there is any discrepancy between the two licenses, 
+         the BSD license will take precedence. 
+         Set tabs to 4 for best viewing.
+
+       This class provides recordset pagination with 
+       First/Prev/Next/Last links. 
+       
+       Feel free to modify this class for your own use as
+       it is very basic. To learn how to use it, see the 
+       example in adodb/tests/testpaging.php.
+       
+       "Pablo Costa" <pablo@cbsp.com.br> implemented Render_PageLinks().
+       
+       Please note, this class is entirely unsupported, 
+       and no free support requests except for bug reports
+       will be entertained by the author.
+
+*/
+class ADODB_Pager {
+       var $id;        // unique id for pager (defaults to 'adodb')
+       var $db;        // ADODB connection object
+       var $sql;       // sql used
+       var $rs;        // recordset generated
+       var $curr_page; // current page number before Render() called, calculated in constructor
+       var $rows;              // number of rows per page
+    var $linksPerPage=10; // number of links per page in navigation bar
+    var $showPageLinks; 
+
+       var $gridAttributes = 'width=100% border=1 bgcolor=white';
+       
+       // Localize text strings here
+       var $first = '<code>|&lt;</code>';
+       var $prev = '<code>&lt;&lt;</code>';
+       var $next = '<code>>></code>';
+       var $last = '<code>>|</code>';
+       var $moreLinks = '...';
+       var $startLinks = '...';
+       var $gridHeader = false;
+       var $htmlSpecialChars = true;
+       var $page = 'Page';
+       var $linkSelectedColor = 'red';
+       var $cache = 0;  #secs to cache with CachePageExecute()
+       
+       //----------------------------------------------
+       // constructor
+       //
+       // $db  adodb connection object
+       // $sql sql statement
+       // $id  optional id to identify which pager, 
+       //              if you have multiple on 1 page. 
+       //              $id should be only be [a-z0-9]*
+       //
+       function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)
+       {
+       global $HTTP_SERVER_VARS,$PHP_SELF,$HTTP_SESSION_VARS,$HTTP_GET_VARS;
+       
+               $curr_page = $id.'_curr_page';
+               if (empty($PHP_SELF)) $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
+               
+               $this->sql = $sql;
+               $this->id = $id;
+               $this->db = $db;
+               $this->showPageLinks = $showPageLinks;
+               
+               $next_page = $id.'_next_page';  
+               
+               if (isset($HTTP_GET_VARS[$next_page])) {
+                       $HTTP_SESSION_VARS[$curr_page] = $HTTP_GET_VARS[$next_page];
+               }
+               if (empty($HTTP_SESSION_VARS[$curr_page])) $HTTP_SESSION_VARS[$curr_page] = 1; ## at first page
+               
+               $this->curr_page = $HTTP_SESSION_VARS[$curr_page];
+               
+       }
+       
+       //---------------------------
+       // Display link to first page
+       function Render_First($anchor=true)
+       {
+       global $PHP_SELF;
+               if ($anchor) {
+       ?>
+               <a href="<?php echo $PHP_SELF,'?',$this->id;?>_next_page=1"><?php echo $this->first;?></a> &nbsp; 
+       <?php
+               } else {
+                       print "$this->first &nbsp; ";
+               }
+       }
+       
+       //--------------------------
+       // Display link to next page
+       function render_next($anchor=true)
+       {
+       global $PHP_SELF;
+       
+               if ($anchor) {
+               ?>
+               <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() + 1 ?>"><?php echo $this->next;?></a> &nbsp; 
+               <?php
+               } else {
+                       print "$this->next &nbsp; ";
+               }
+       }
+       
+       //------------------
+       // Link to last page
+       // 
+       // for better performance with large recordsets, you can set
+       // $this->db->pageExecuteCountRows = false, which disables
+       // last page counting.
+       function render_last($anchor=true)
+       {
+       global $PHP_SELF;
+       
+               if (!$this->db->pageExecuteCountRows) return;
+               
+               if ($anchor) {
+               ?>
+                       <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->LastPageNo() ?>"><?php echo $this->last;?></a> &nbsp; 
+               <?php
+               } else {
+                       print "$this->last &nbsp; ";
+               }
+       }
+       
+       //---------------------------------------------------
+       // original code by "Pablo Costa" <pablo@cbsp.com.br> 
+        function render_pagelinks()
+        {
+        global $PHP_SELF;
+            $pages        = $this->rs->LastPageNo();
+            $linksperpage = $this->linksPerPage ? $this->linksPerPage : $pages;
+            for($i=1; $i <= $pages; $i+=$linksperpage)
+            {
+                if($this->rs->AbsolutePage() >= $i)
+                {
+                    $start = $i;
+                }
+            }
+                       $numbers = '';
+            $end = $start+$linksperpage-1;
+                       $link = $this->id . "_next_page";
+            if($end > $pages) $end = $pages;
+                       
+                       
+                       if ($this->startLinks && $start > 1) {
+                               $pos = $start - 1;
+                               $numbers .= "<a href=$PHP_SELF?$link=$pos>$this->startLinks</a>  ";
+            } 
+                       
+                       for($i=$start; $i <= $end; $i++) {
+                if ($this->rs->AbsolutePage() == $i)
+                    $numbers .= "<font color=$this->linkSelectedColor><b>$i</b></font>  ";
+                else 
+                     $numbers .= "<a href=$PHP_SELF?$link=$i>$i</a>  ";
+            
+            }
+                       if ($this->moreLinks && $end < $pages) 
+                               $numbers .= "<a href=$PHP_SELF?$link=$i>$this->moreLinks</a>  ";
+            print $numbers . ' &nbsp; ';
+        }
+       // Link to previous page
+       function render_prev($anchor=true)
+       {
+       global $PHP_SELF;
+               if ($anchor) {
+       ?>
+               <a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() - 1 ?>"><?php echo $this->prev;?></a> &nbsp; 
+       <?php 
+               } else {
+                       print "$this->prev &nbsp; ";
+               }
+       }
+       
+       //--------------------------------------------------------
+       // Simply rendering of grid. You should override this for
+       // better control over the format of the grid
+       //
+       // We use output buffering to keep code clean and readable.
+       function RenderGrid()
+       {
+       global $gSQLBlockRows; // used by rs2html to indicate how many rows to display
+               include_once(ADODB_DIR.'/tohtml.inc.php');
+               ob_start();
+               $gSQLBlockRows = $this->rows;
+               rs2html($this->rs,$this->gridAttributes,$this->gridHeader,$this->htmlSpecialChars);
+               $s = ob_get_contents();
+               ob_end_clean();
+               return $s;
+       }
+       
+       //-------------------------------------------------------
+       // Navigation bar
+       //
+       // we use output buffering to keep the code easy to read.
+       function RenderNav()
+       {
+               ob_start();
+               if (!$this->rs->AtFirstPage()) {
+                       $this->Render_First();
+                       $this->Render_Prev();
+               } else {
+                       $this->Render_First(false);
+                       $this->Render_Prev(false);
+               }
+        if ($this->showPageLinks){
+            $this->Render_PageLinks();
+        }
+               if (!$this->rs->AtLastPage()) {
+                       $this->Render_Next();
+                       $this->Render_Last();
+               } else {
+                       $this->Render_Next(false);
+                       $this->Render_Last(false);
+               }
+               $s = ob_get_contents();
+               ob_end_clean();
+               return $s;
+       }
+       
+       //-------------------
+       // This is the footer
+       function RenderPageCount()
+       {
+               if (!$this->db->pageExecuteCountRows) return '';
+               $lastPage = $this->rs->LastPageNo();
+               if ($lastPage == -1) $lastPage = 1; // check for empty rs.
+               return "<font size=-1>$this->page ".$this->curr_page."/".$lastPage."</font>";
+       }
+       
+       //-----------------------------------
+       // Call this class to draw everything.
+       function Render($rows=10)
+       {
+       global $ADODB_COUNTRECS;
+       
+               $this->rows = $rows;
+               
+               $savec = $ADODB_COUNTRECS;
+               if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true;
+               if ($this->cache)
+                       $rs = &$this->db->CachePageExecute($this->cache,$this->sql,$rows,$this->curr_page);
+               else
+                       $rs = &$this->db->PageExecute($this->sql,$rows,$this->curr_page);
+               $ADODB_COUNTRECS = $savec;
+               
+               $this->rs = &$rs;
+               if (!$rs) {
+                       print "<h3>Query failed: $this->sql</h3>";
+                       return;
+               }
+               
+               if (!$rs->EOF && (!$rs->AtFirstPage() || !$rs->AtLastPage())) 
+                       $header = $this->RenderNav();
+               else
+                       $header = "&nbsp;";
+               
+               $grid = $this->RenderGrid();
+               $footer = $this->RenderPageCount();
+               $rs->Close();
+               $this->rs = false;
+               
+               $this->RenderLayout($header,$grid,$footer);
+       }
+       
+       //------------------------------------------------------
+       // override this to control overall layout and formating
+       function RenderLayout($header,$grid,$footer,$attributes='border=1 bgcolor=beige')
+       {
+               echo "<table ".$attributes."><tr><td>",
+                               $header,
+                       "</td></tr><tr><td>",
+                               $grid,
+                       "</td></tr><tr><td>",
+                               $footer,
+                       "</td></tr></table>";
+       }
+}
+
+
+?>
\ No newline at end of file
index 3c97dc5c16ef0f486cb9cecc124f9c9f4b21eacc..3894730469cab7d1c0a3755b0d7bc7614e824ac6 100644 (file)
-<?php\r
-/** \r
- * @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license. \r
- * Whenever there is any discrepancy between the two licenses, \r
- * the BSD license will take precedence. \r
- *\r
- * Set tabs to 4 for best viewing.\r
- * \r
- * PEAR DB Emulation Layer for ADODB.\r
- *\r
- * The following code is modelled on PEAR DB code by Stig Bakken <ssb@fast.no>                                                            |\r
- * and Tomas V.V.Cox <cox@idecnet.com>.        Portions (c)1997-2002 The PHP Group.\r
- */\r
-\r
- /*\r
- We support:\r
\r
- DB_Common\r
- ---------\r
-       query - returns PEAR_Error on error\r
-       limitQuery - return PEAR_Error on error\r
-       prepare - does not return PEAR_Error on error\r
-       execute - does not return PEAR_Error on error\r
-       setFetchMode - supports ASSOC and ORDERED\r
-       errorNative\r
-       quote\r
-       nextID\r
-       disconnect\r
-       \r
- DB_Result\r
- ---------\r
-       numRows - returns -1 if not supported\r
-       numCols\r
-       fetchInto - does not support passing of fetchmode\r
-       fetchRows - does not support passing of fetchmode\r
-       free\r
- */\r
\r
-define('ADODB_PEAR',dirname(__FILE__));\r
-include_once "PEAR.php";\r
-include_once ADODB_PEAR."/adodb-errorpear.inc.php";\r
-include_once ADODB_PEAR."/adodb.inc.php";\r
-\r
-if (!defined('DB_OK')) {\r
-define("DB_OK",        1);\r
-define("DB_ERROR",-1);\r
-/**\r
- * This is a special constant that tells DB the user hasn't specified\r
- * any particular get mode, so the default should be used.\r
- */\r
-\r
-define('DB_FETCHMODE_DEFAULT', 0);\r
-\r
-/**\r
- * Column data indexed by numbers, ordered from 0 and up\r
- */\r
-\r
-define('DB_FETCHMODE_ORDERED', 1);\r
-\r
-/**\r
- * Column data indexed by column names\r
- */\r
-\r
-define('DB_FETCHMODE_ASSOC', 2);\r
-\r
-/* for compatibility */\r
-\r
-define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);\r
-define('DB_GETMODE_ASSOC',   DB_FETCHMODE_ASSOC);\r
-\r
-/**\r
- * these are constants for the tableInfo-function\r
- * they are bitwised or'ed. so if there are more constants to be defined\r
- * in the future, adjust DB_TABLEINFO_FULL accordingly\r
- */\r
-\r
-define('DB_TABLEINFO_ORDER', 1);\r
-define('DB_TABLEINFO_ORDERTABLE', 2);\r
-define('DB_TABLEINFO_FULL', 3);\r
-}\r
-\r
-/**\r
- * The main "DB" class is simply a container class with some static\r
- * methods for creating DB objects as well as some utility functions\r
- * common to all parts of DB.\r
- *\r
- */\r
-\r
-class DB\r
-{\r
-       /**\r
-        * Create a new DB object for the specified database type\r
-        *\r
-        * @param $type string database type, for example "mysql"\r
-        *\r
-        * @return object a newly created DB object, or a DB error code on\r
-        * error\r
-        */\r
-\r
-       function &factory($type)\r
-       {\r
-               include_once(ADODB_DIR."/drivers/adodb-$type.inc.php");\r
-               $obj = &NewADOConnection($type);\r
-               if (!is_object($obj)) $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);\r
-               return $obj;\r
-       }\r
-\r
-       /**\r
-        * Create a new DB object and connect to the specified database\r
-        *\r
-        * @param $dsn mixed "data source name", see the DB::parseDSN\r
-        * method for a description of the dsn format.  Can also be\r
-        * specified as an array of the format returned by DB::parseDSN.\r
-        *\r
-        * @param $options mixed if boolean (or scalar), tells whether\r
-        * this connection should be persistent (for backends that support\r
-        * this).  This parameter can also be an array of options, see\r
-        * DB_common::setOption for more information on connection\r
-        * options.\r
-        *\r
-        * @return object a newly created DB connection object, or a DB\r
-        * error object on error\r
-        *\r
-        * @see DB::parseDSN\r
-        * @see DB::isError\r
-        */\r
-       function &connect($dsn, $options = false)\r
-       {\r
-               if (is_array($dsn)) {\r
-                       $dsninfo = $dsn;\r
-               } else {\r
-                       $dsninfo = DB::parseDSN($dsn);\r
-               }\r
-               switch ($dsninfo["phptype"]) {\r
-                       case 'pgsql':   $type = 'postgres7'; break;\r
-                       case 'ifx':             $type = 'informix9'; break;\r
-                       default:                $type = $dsninfo["phptype"]; break;\r
-               }\r
-\r
-               if (is_array($options) && isset($options["debug"]) &&\r
-                       $options["debug"] >= 2) {\r
-                       // expose php errors with sufficient debug level\r
-                        @include_once("adodb-$type.inc.php");\r
-               } else {\r
-                        @include_once("adodb-$type.inc.php");\r
-               }\r
-\r
-               @$obj =& NewADOConnection($type);\r
-               if (!is_object($obj)) {\r
-                       $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);\r
-                       return $obj;\r
-               }\r
-               if (is_array($options)) {\r
-                       foreach($options as $k => $v) {\r
-                               switch(strtolower($k)) {\r
-                               case 'persistent':      $persist = $v; break;\r
-                               #ibase\r
-                               case 'dialect':         $obj->dialect = $v; break;\r
-                               case 'charset':         $obj->charset = $v; break;\r
-                               case 'buffers':         $obj->buffers = $v; break;\r
-                               #ado\r
-                               case 'charpage':        $obj->charPage = $v; break;\r
-                               #mysql\r
-                               case 'clientflags': $obj->clientFlags = $v; break;\r
-                               }\r
-                       }\r
-               } else {\r
-                       $persist = false;\r
-               }\r
-\r
-               if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':'.$dsninfo['socket'];\r
-               else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':'.$dsninfo['port'];\r
-               \r
-               if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);\r
-               else  $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);\r
-               \r
-               if (!$ok) $obj = ADODB_PEAR_Error();\r
-               return $obj;\r
-       }\r
-\r
-       /**\r
-        * Return the DB API version\r
-        *\r
-        * @return int the DB API version number\r
-        */\r
-       function apiVersion()\r
-       {\r
-               return 2;\r
-       }\r
-\r
-       /**\r
-        * Tell whether a result code from a DB method is an error\r
-        *\r
-        * @param $value int result code\r
-        *\r
-        * @return bool whether $value is an error\r
-        */\r
-       function isError($value)\r
-       {\r
-               return (is_object($value) &&\r
-                               (get_class($value) == 'db_error' ||\r
-                                is_subclass_of($value, 'db_error')));\r
-       }\r
-\r
-\r
-       /**\r
-        * Tell whether a result code from a DB method is a warning.\r
-        * Warnings differ from errors in that they are generated by DB,\r
-        * and are not fatal.\r
-        *\r
-        * @param $value mixed result value\r
-        *\r
-        * @return bool whether $value is a warning\r
-        */\r
-       function isWarning($value)\r
-       {\r
-               return is_object($value) &&\r
-                       (get_class( $value ) == "db_warning" ||\r
-                        is_subclass_of($value, "db_warning"));\r
-       }\r
-\r
-       /**\r
-        * Parse a data source name\r
-        *\r
-        * @param $dsn string Data Source Name to be parsed\r
-        *\r
-        * @return array an associative array with the following keys:\r
-        *\r
-        *  phptype: Database backend used in PHP (mysql, odbc etc.)\r
-        *  dbsyntax: Database used with regards to SQL syntax etc.\r
-        *  protocol: Communication protocol to use (tcp, unix etc.)\r
-        *  hostspec: Host specification (hostname[:port])\r
-        *  database: Database to use on the DBMS server\r
-        *  username: User name for login\r
-        *  password: Password for login\r
-        *\r
-        * The format of the supplied DSN is in its fullest form:\r
-        *\r
-        *  phptype(dbsyntax)://username:password@protocol+hostspec/database\r
-        *\r
-        * Most variations are allowed:\r
-        *\r
-        *  phptype://username:password@protocol+hostspec:110//usr/db_file.db\r
-        *  phptype://username:password@hostspec/database_name\r
-        *  phptype://username:password@hostspec\r
-        *  phptype://username@hostspec\r
-        *  phptype://hostspec/database\r
-        *  phptype://hostspec\r
-        *  phptype(dbsyntax)\r
-        *  phptype\r
-        *\r
-        * @author Tomas V.V.Cox <cox@idecnet.com>\r
-        */\r
-       function parseDSN($dsn)\r
-       {\r
-               if (is_array($dsn)) {\r
-                       return $dsn;\r
-               }\r
-\r
-               $parsed = array(\r
-                       'phptype'  => false,\r
-                       'dbsyntax' => false,\r
-                       'protocol' => false,\r
-                       'hostspec' => false,\r
-                       'database' => false,\r
-                       'username' => false,\r
-                       'password' => false\r
-               );\r
-\r
-               // Find phptype and dbsyntax\r
-               if (($pos = strpos($dsn, '://')) !== false) {\r
-                       $str = substr($dsn, 0, $pos);\r
-                       $dsn = substr($dsn, $pos + 3);\r
-               } else {\r
-                       $str = $dsn;\r
-                       $dsn = NULL;\r
-               }\r
-\r
-               // Get phptype and dbsyntax\r
-               // $str => phptype(dbsyntax)\r
-               if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {\r
-                       $parsed['phptype'] = $arr[1];\r
-                       $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];\r
-               } else {\r
-                       $parsed['phptype'] = $str;\r
-                       $parsed['dbsyntax'] = $str;\r
-               }\r
-\r
-               if (empty($dsn)) {\r
-                       return $parsed;\r
-               }\r
-\r
-               // Get (if found): username and password\r
-               // $dsn => username:password@protocol+hostspec/database\r
-               if (($at = strpos($dsn,'@')) !== false) {\r
-                       $str = substr($dsn, 0, $at);\r
-                       $dsn = substr($dsn, $at + 1);\r
-                       if (($pos = strpos($str, ':')) !== false) {\r
-                               $parsed['username'] = urldecode(substr($str, 0, $pos));\r
-                               $parsed['password'] = urldecode(substr($str, $pos + 1));\r
-                       } else {\r
-                               $parsed['username'] = urldecode($str);\r
-                       }\r
-               }\r
-\r
-               // Find protocol and hostspec\r
-               // $dsn => protocol+hostspec/database\r
-               if (($pos=strpos($dsn, '/')) !== false) {\r
-                       $str = substr($dsn, 0, $pos);\r
-                       $dsn = substr($dsn, $pos + 1);\r
-               } else {\r
-                       $str = $dsn;\r
-                       $dsn = NULL;\r
-               }\r
-\r
-               // Get protocol + hostspec\r
-               // $str => protocol+hostspec\r
-               if (($pos=strpos($str, '+')) !== false) {\r
-                       $parsed['protocol'] = substr($str, 0, $pos);\r
-                       $parsed['hostspec'] = urldecode(substr($str, $pos + 1));\r
-               } else {\r
-                       $parsed['hostspec'] = urldecode($str);\r
-               }\r
-\r
-               // Get dabase if any\r
-               // $dsn => database\r
-               if (!empty($dsn)) {\r
-                       $parsed['database'] = $dsn;\r
-               }\r
-\r
-               return $parsed;\r
-       }\r
-\r
-       /**\r
-        * Load a PHP database extension if it is not loaded already.\r
-        *\r
-        * @access public\r
-        *\r
-        * @param $name the base name of the extension (without the .so or\r
-        * .dll suffix)\r
-        *\r
-        * @return bool true if the extension was already or successfully\r
-        * loaded, false if it could not be loaded\r
-        */\r
-       function assertExtension($name)\r
-       {\r
-               if (!extension_loaded($name)) {\r
-                       $dlext = (strncmp(PHP_OS,'WIN',3) === 0) ? '.dll' : '.so';\r
-                       @dl($name . $dlext);\r
-               }\r
-               if (!extension_loaded($name)) {\r
-                       return false;\r
-               }\r
-               return true;\r
-       }\r
-}\r
-\r
+<?php
+/** 
+ * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * PEAR DB Emulation Layer for ADODB.
+ *
+ * The following code is modelled on PEAR DB code by Stig Bakken <ssb@fast.no>                                                            |
+ * and Tomas V.V.Cox <cox@idecnet.com>.        Portions (c)1997-2002 The PHP Group.
+ */
+
+ /*
+ We support:
+ DB_Common
+ ---------
+       query - returns PEAR_Error on error
+       limitQuery - return PEAR_Error on error
+       prepare - does not return PEAR_Error on error
+       execute - does not return PEAR_Error on error
+       setFetchMode - supports ASSOC and ORDERED
+       errorNative
+       quote
+       nextID
+       disconnect
+       
+ DB_Result
+ ---------
+       numRows - returns -1 if not supported
+       numCols
+       fetchInto - does not support passing of fetchmode
+       fetchRows - does not support passing of fetchmode
+       free
+ */
+define('ADODB_PEAR',dirname(__FILE__));
+include_once "PEAR.php";
+include_once ADODB_PEAR."/adodb-errorpear.inc.php";
+include_once ADODB_PEAR."/adodb.inc.php";
+
+if (!defined('DB_OK')) {
+define("DB_OK",        1);
+define("DB_ERROR",-1);
+/**
+ * This is a special constant that tells DB the user hasn't specified
+ * any particular get mode, so the default should be used.
+ */
+
+define('DB_FETCHMODE_DEFAULT', 0);
+
+/**
+ * Column data indexed by numbers, ordered from 0 and up
+ */
+
+define('DB_FETCHMODE_ORDERED', 1);
+
+/**
+ * Column data indexed by column names
+ */
+
+define('DB_FETCHMODE_ASSOC', 2);
+
+/* for compatibility */
+
+define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
+define('DB_GETMODE_ASSOC',   DB_FETCHMODE_ASSOC);
+
+/**
+ * these are constants for the tableInfo-function
+ * they are bitwised or'ed. so if there are more constants to be defined
+ * in the future, adjust DB_TABLEINFO_FULL accordingly
+ */
+
+define('DB_TABLEINFO_ORDER', 1);
+define('DB_TABLEINFO_ORDERTABLE', 2);
+define('DB_TABLEINFO_FULL', 3);
+}
+
+/**
+ * The main "DB" class is simply a container class with some static
+ * methods for creating DB objects as well as some utility functions
+ * common to all parts of DB.
+ *
+ */
+
+class DB
+{
+       /**
+        * Create a new DB object for the specified database type
+        *
+        * @param $type string database type, for example "mysql"
+        *
+        * @return object a newly created DB object, or a DB error code on
+        * error
+        */
+
+       function &factory($type)
+       {
+               include_once(ADODB_DIR."/drivers/adodb-$type.inc.php");
+               $obj = &NewADOConnection($type);
+               if (!is_object($obj)) $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
+               return $obj;
+       }
+
+       /**
+        * Create a new DB object and connect to the specified database
+        *
+        * @param $dsn mixed "data source name", see the DB::parseDSN
+        * method for a description of the dsn format.  Can also be
+        * specified as an array of the format returned by DB::parseDSN.
+        *
+        * @param $options mixed if boolean (or scalar), tells whether
+        * this connection should be persistent (for backends that support
+        * this).  This parameter can also be an array of options, see
+        * DB_common::setOption for more information on connection
+        * options.
+        *
+        * @return object a newly created DB connection object, or a DB
+        * error object on error
+        *
+        * @see DB::parseDSN
+        * @see DB::isError
+        */
+       function &connect($dsn, $options = false)
+       {
+               if (is_array($dsn)) {
+                       $dsninfo = $dsn;
+               } else {
+                       $dsninfo = DB::parseDSN($dsn);
+               }
+               switch ($dsninfo["phptype"]) {
+                       case 'pgsql':   $type = 'postgres7'; break;
+                       case 'ifx':             $type = 'informix9'; break;
+                       default:                $type = $dsninfo["phptype"]; break;
+               }
+
+               if (is_array($options) && isset($options["debug"]) &&
+                       $options["debug"] >= 2) {
+                       // expose php errors with sufficient debug level
+                        @include_once("adodb-$type.inc.php");
+               } else {
+                        @include_once("adodb-$type.inc.php");
+               }
+
+               @$obj =& NewADOConnection($type);
+               if (!is_object($obj)) {
+                       $obj =& new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
+                       return $obj;
+               }
+               if (is_array($options)) {
+                       foreach($options as $k => $v) {
+                               switch(strtolower($k)) {
+                               case 'persistent':      $persist = $v; break;
+                               #ibase
+                               case 'dialect':         $obj->dialect = $v; break;
+                               case 'charset':         $obj->charset = $v; break;
+                               case 'buffers':         $obj->buffers = $v; break;
+                               #ado
+                               case 'charpage':        $obj->charPage = $v; break;
+                               #mysql
+                               case 'clientflags': $obj->clientFlags = $v; break;
+                               }
+                       }
+               } else {
+                       $persist = false;
+               }
+
+               if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':'.$dsninfo['socket'];
+               else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':'.$dsninfo['port'];
+               
+               if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
+               else  $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
+               
+               if (!$ok) $obj = ADODB_PEAR_Error();
+               return $obj;
+       }
+
+       /**
+        * Return the DB API version
+        *
+        * @return int the DB API version number
+        */
+       function apiVersion()
+       {
+               return 2;
+       }
+
+       /**
+        * Tell whether a result code from a DB method is an error
+        *
+        * @param $value int result code
+        *
+        * @return bool whether $value is an error
+        */
+       function isError($value)
+       {
+               return (is_object($value) &&
+                               (get_class($value) == 'db_error' ||
+                                is_subclass_of($value, 'db_error')));
+       }
+
+
+       /**
+        * Tell whether a result code from a DB method is a warning.
+        * Warnings differ from errors in that they are generated by DB,
+        * and are not fatal.
+        *
+        * @param $value mixed result value
+        *
+        * @return bool whether $value is a warning
+        */
+       function isWarning($value)
+       {
+               return is_object($value) &&
+                       (get_class( $value ) == "db_warning" ||
+                        is_subclass_of($value, "db_warning"));
+       }
+
+       /**
+        * Parse a data source name
+        *
+        * @param $dsn string Data Source Name to be parsed
+        *
+        * @return array an associative array with the following keys:
+        *
+        *  phptype: Database backend used in PHP (mysql, odbc etc.)
+        *  dbsyntax: Database used with regards to SQL syntax etc.
+        *  protocol: Communication protocol to use (tcp, unix etc.)
+        *  hostspec: Host specification (hostname[:port])
+        *  database: Database to use on the DBMS server
+        *  username: User name for login
+        *  password: Password for login
+        *
+        * The format of the supplied DSN is in its fullest form:
+        *
+        *  phptype(dbsyntax)://username:password@protocol+hostspec/database
+        *
+        * Most variations are allowed:
+        *
+        *  phptype://username:password@protocol+hostspec:110//usr/db_file.db
+        *  phptype://username:password@hostspec/database_name
+        *  phptype://username:password@hostspec
+        *  phptype://username@hostspec
+        *  phptype://hostspec/database
+        *  phptype://hostspec
+        *  phptype(dbsyntax)
+        *  phptype
+        *
+        * @author Tomas V.V.Cox <cox@idecnet.com>
+        */
+       function parseDSN($dsn)
+       {
+               if (is_array($dsn)) {
+                       return $dsn;
+               }
+
+               $parsed = array(
+                       'phptype'  => false,
+                       'dbsyntax' => false,
+                       'protocol' => false,
+                       'hostspec' => false,
+                       'database' => false,
+                       'username' => false,
+                       'password' => false
+               );
+
+               // Find phptype and dbsyntax
+               if (($pos = strpos($dsn, '://')) !== false) {
+                       $str = substr($dsn, 0, $pos);
+                       $dsn = substr($dsn, $pos + 3);
+               } else {
+                       $str = $dsn;
+                       $dsn = NULL;
+               }
+
+               // Get phptype and dbsyntax
+               // $str => phptype(dbsyntax)
+               if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
+                       $parsed['phptype'] = $arr[1];
+                       $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
+               } else {
+                       $parsed['phptype'] = $str;
+                       $parsed['dbsyntax'] = $str;
+               }
+
+               if (empty($dsn)) {
+                       return $parsed;
+               }
+
+               // Get (if found): username and password
+               // $dsn => username:password@protocol+hostspec/database
+               if (($at = strpos($dsn,'@')) !== false) {
+                       $str = substr($dsn, 0, $at);
+                       $dsn = substr($dsn, $at + 1);
+                       if (($pos = strpos($str, ':')) !== false) {
+                               $parsed['username'] = urldecode(substr($str, 0, $pos));
+                               $parsed['password'] = urldecode(substr($str, $pos + 1));
+                       } else {
+                               $parsed['username'] = urldecode($str);
+                       }
+               }
+
+               // Find protocol and hostspec
+               // $dsn => protocol+hostspec/database
+               if (($pos=strpos($dsn, '/')) !== false) {
+                       $str = substr($dsn, 0, $pos);
+                       $dsn = substr($dsn, $pos + 1);
+               } else {
+                       $str = $dsn;
+                       $dsn = NULL;
+               }
+
+               // Get protocol + hostspec
+               // $str => protocol+hostspec
+               if (($pos=strpos($str, '+')) !== false) {
+                       $parsed['protocol'] = substr($str, 0, $pos);
+                       $parsed['hostspec'] = urldecode(substr($str, $pos + 1));
+               } else {
+                       $parsed['hostspec'] = urldecode($str);
+               }
+
+               // Get dabase if any
+               // $dsn => database
+               if (!empty($dsn)) {
+                       $parsed['database'] = $dsn;
+               }
+
+               return $parsed;
+       }
+
+       /**
+        * Load a PHP database extension if it is not loaded already.
+        *
+        * @access public
+        *
+        * @param $name the base name of the extension (without the .so or
+        * .dll suffix)
+        *
+        * @return bool true if the extension was already or successfully
+        * loaded, false if it could not be loaded
+        */
+       function assertExtension($name)
+       {
+               if (!extension_loaded($name)) {
+                       $dlext = (strncmp(PHP_OS,'WIN',3) === 0) ? '.dll' : '.so';
+                       @dl($name . $dlext);
+               }
+               if (!extension_loaded($name)) {
+                       return false;
+               }
+               return true;
+       }
+}
+
 ?>
\ No newline at end of file
index 9c0efd24d79f83d1f30bf9b7e1c04f5ffe577ea1..7444e1d9d8d7ecb808302b52a74bb53c4183542d 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. See License.txt. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Library for basic performance monitoring and tuning.\r
-  \r
-  My apologies if you see code mixed with presentation. The presentation suits\r
-  my needs. If you want to separate code from presentation, be my guest. Patches\r
-  are welcome.\r
-  \r
-*/\r
-\r
-if (!defined(ADODB_DIR)) include_once(dirname(__FILE__).'/adodb.inc.php');\r
-include_once(ADODB_DIR.'/tohtml.inc.php');\r
-\r
-\r
-/* return microtime value as a float */\r
-function adodb_microtime()\r
-{\r
-       $t = microtime();\r
-       $t = explode(' ',$t);\r
-       return (float)$t[1]+ (float)$t[0];\r
-}\r
-\r
-/* sql code timing */\r
-function& adodb_log_sql(&$conn,$sql,$inputarr)\r
-{\r
-global $HTTP_SERVER_VARS;\r
-       \r
-    $perf_table = adodb_perf::table();\r
-       $conn->fnExecute = false;\r
-       $t0 = microtime();\r
-       $rs =& $conn->Execute($sql,$inputarr);\r
-       $t1 = microtime();\r
-\r
-       if (!empty($conn->_logsql)) {\r
-               $conn->_logsql = false; // disable logsql error simulation\r
-               $dbT = $conn->databaseType;\r
-               \r
-               $a0 = split(' ',$t0);\r
-               $a0 = (float)$a0[1]+(float)$a0[0];\r
-               \r
-               $a1 = split(' ',$t1);\r
-               $a1 = (float)$a1[1]+(float)$a1[0];\r
-               \r
-               $time = $a1 - $a0;\r
-       \r
-               if (!$rs) {\r
-                       $errM = $conn->ErrorMsg();\r
-                       $errN = $conn->ErrorNo();\r
-                       $conn->lastInsID = 0;\r
-                       $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);\r
-               } else {\r
-                       $tracer = '';\r
-                       $errM = '';\r
-                       $errN = 0;\r
-                       $dbg = $conn->debug;\r
-                       $conn->debug = false;\r
-                       if (!is_object($rs) || $rs->dataProvider == 'empty') \r
-                               $conn->_affected = $conn->affected_rows(true);\r
-                       $conn->lastInsID = @$conn->Insert_ID();\r
-                       $conn->debug = $dbg;\r
-               }\r
-               if (isset($HTTP_SERVER_VARS['HTTP_HOST'])) {\r
-                       $tracer .= '<br>'.$HTTP_SERVER_VARS['HTTP_HOST'];\r
-                       if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= $HTTP_SERVER_VARS['PHP_SELF'];\r
-               } else \r
-                       if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= '<br>'.$HTTP_SERVER_VARS['PHP_SELF'];\r
-               //$tracer .= (string) adodb_backtrace(false);\r
-               \r
-               $tracer = substr($tracer,0,500);\r
-               \r
-               if (is_array($inputarr)) {\r
-                       if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);\r
-                       else {\r
-                               $params = '';\r
-                               $params = implode(', ',$inputarr);\r
-                               if (strlen($params) >= 3000) $params = substr($params, 0, 3000);\r
-                       }\r
-               } else {\r
-                       $params = '';\r
-               }\r
-               \r
-               if (is_array($sql)) $sql = $sql[0];\r
-               $arr = array('b'=>trim(substr($sql,0,230)),\r
-                                       'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>round($time,6));\r
-\r
-               $saved = $conn->debug;\r
-               $conn->debug = 0;\r
-               \r
-               if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {\r
-                       $isql = "insert into $perf_table values($conn->sysTimeStamp,:b,:c,:d,:e,:f)";\r
-               } else if ($dbT == 'odbc_mssql' || $dbT == 'informix') {\r
-                       $timer = $arr['f'];\r
-                       if ($dbT == 'informix') $sql2 = substr($sql2,0,230);\r
-\r
-                       $sql1 = $conn->qstr($arr['b']);\r
-                       $sql2 = $conn->qstr($arr['c']);\r
-                       $params = $conn->qstr($arr['d']);\r
-                       $tracer = $conn->qstr($arr['e']);\r
-                       \r
-                       $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($conn->sysTimeStamp,$sql1,$sql2,$params,$tracer,$timer)";\r
-                       if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);\r
-                       $arr = false;\r
-               } else {\r
-                       $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $conn->sysTimeStamp,?,?,?,?,?)";\r
-               }\r
-               $ok = $conn->Execute($isql,$arr);\r
-               $conn->debug = $saved;\r
-               \r
-               if ($ok) {\r
-                       $conn->_logsql = true; \r
-               } else {\r
-                       $err2 = $conn->ErrorMsg();\r
-                       $conn->_logsql = true; // enable logsql error simulation\r
-                       $perf =& NewPerfMonitor($conn);\r
-                       if ($perf) {\r
-                               if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr);\r
-                       } else {\r
-                               $ok = $conn->Execute("create table $perf_table (\r
-                               created varchar(50),\r
-                               sql0 varchar(250), \r
-                               sql1 varchar(4000),\r
-                               params varchar(3000),\r
-                               tracer varchar(500),\r
-                               timer decimal(16,6))");\r
-                       }\r
-                       if (!$ok) {\r
-                               ADOConnection::outp( "<b>LOGSQL Insert Failed</b>: $isql<br>$err2</br>");\r
-                               $conn->_logsql = false;\r
-                       }\r
-               }\r
-               $conn->_errorMsg = $errM;\r
-               $conn->_errorCode = $errN;\r
-       } \r
-       $conn->fnExecute = 'adodb_log_sql';\r
-       return $rs;\r
-}\r
-\r
-       \r
-/*\r
-The settings data structure is an associative array that database parameter per element.\r
-\r
-Each database parameter element in the array is itself an array consisting of:\r
-\r
-0: category code, used to group related db parameters\r
-1: either\r
-       a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'", \r
-       b. array holding sql string and field to look for, e.g. array('show variables','table_cache'),\r
-       c. a string prefixed by =, then a PHP method of the class is invoked, \r
-               e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue',\r
-2: description of the database parameter\r
-*/\r
-\r
-class adodb_perf {\r
-       var $conn;\r
-       var $color = '#F0F0F0';\r
-       var $table = '<table border=1 bgcolor=white>';\r
-       var $titles = '<tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr>';\r
-       var $warnRatio = 90;\r
-       var $tablesSQL = false;\r
-       var $cliFormat = "%32s => %s \r\n";\r
-       var $sql1 = 'sql1';  // used for casting sql1 to text for mssql\r
-       var $explain = true;\r
-       var $helpurl = "<a href=http://phplens.com/adodb/reference.functions.fnexecute.and.fncacheexecute.properties.html#logsql>LogSQL help</a>";\r
-       var $createTableSQL = false;\r
-       var $maxLength = 2000;\r
-       \r
-    // Sets the tablename to be used            \r
-    function table($newtable = false)\r
-    {\r
-        static $_table;\r
-\r
-        if (!empty($newtable))  $_table = $newtable;\r
-               if (empty($_table)) $_table = 'adodb_logsql';\r
-        return $_table;\r
-    }\r
-\r
-       // returns array with info to calculate CPU Load\r
-       function _CPULoad()\r
-       {\r
-/*\r
-\r
-cpu  524152 2662 2515228 336057010\r
-cpu0 264339 1408 1257951 168025827\r
-cpu1 259813 1254 1257277 168031181\r
-page 622307 25475680\r
-swap 24 1891\r
-intr 890153570 868093576 6 0 4 4 0 6 1 2 0 0 0 124 0 8098760 2 13961053 0 0 0 0 0 0 0 0 0 0 0 0 0 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\r
-disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320)\r
-ctxt 66155838\r
-btime 1062315585\r
-processes 69293\r
-\r
-*/\r
-               // Algorithm is taken from\r
-               // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp\r
-               if (strncmp(PHP_OS,'WIN',3)==0) {\r
-                       @$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");\r
-                       if (!$c) return false;\r
-                       \r
-                       $info[0] = $c->PercentProcessorTime;\r
-                       $info[1] = 0;\r
-                       $info[2] = 0;\r
-                       $info[3] = $c->TimeStamp_Sys100NS;\r
-                       //print_r($info);\r
-                       return $info;\r
-               }\r
-               \r
-               // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com)\r
-               $statfile = '/proc/stat';\r
-               if (!file_exists($statfile)) return false;\r
-               \r
-               $fd = fopen($statfile,"r");\r
-               if (!$fd) return false;\r
-               \r
-               $statinfo = explode("\n",fgets($fd, 1024));\r
-               fclose($fd);\r
-               foreach($statinfo as $line) {\r
-                       $info = explode(" ",$line);\r
-                       if($info[0]=="cpu") {\r
-                               array_shift($info);  // pop off "cpu"\r
-                               if(!$info[0]) array_shift($info); // pop off blank space (if any)\r
-                               return $info;\r
-                       }\r
-               }\r
-               \r
-               return false;\r
-               \r
-       }\r
-       \r
-       /* NOT IMPLEMENTED */\r
-       function MemInfo()\r
-       {\r
-               /*\r
-\r
-        total:    used:    free:  shared: buffers:  cached:\r
-Mem:  1055289344 917299200 137990144        0 165437440 599773184\r
-Swap: 2146775040 11055104 2135719936\r
-MemTotal:      1030556 kB\r
-MemFree:        134756 kB\r
-MemShared:           0 kB\r
-Buffers:        161560 kB\r
-Cached:         581384 kB\r
-SwapCached:       4332 kB\r
-Active:         494468 kB\r
-Inact_dirty:    322856 kB\r
-Inact_clean:     24256 kB\r
-Inact_target:   168316 kB\r
-HighTotal:      131064 kB\r
-HighFree:         1024 kB\r
-LowTotal:       899492 kB\r
-LowFree:        133732 kB\r
-SwapTotal:     2096460 kB\r
-SwapFree:      2085664 kB\r
-Committed_AS:   348732 kB\r
-               */\r
-       }\r
-       \r
-       \r
-       /*\r
-               Remember that this is client load, not db server load!\r
-       */\r
-       var $_lastLoad;\r
-       function CPULoad()\r
-       {\r
-               $info = $this->_CPULoad();\r
-               if (!$info) return false;\r
-                       \r
-               if (empty($this->_lastLoad)) {\r
-                       sleep(1);\r
-                       $this->_lastLoad = $info;\r
-                       $info = $this->_CPULoad();\r
-               }\r
-               \r
-               $last = $this->_lastLoad;\r
-               $this->_lastLoad = $info;\r
-               \r
-               $d_user = $info[0] - $last[0];\r
-               $d_nice = $info[1] - $last[1];\r
-               $d_system = $info[2] - $last[2];\r
-               $d_idle = $info[3] - $last[3];\r
-               \r
-               //printf("Delta - User: %f  Nice: %f  System: %f  Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);\r
-\r
-               if (strncmp(PHP_OS,'WIN',3)==0) {\r
-                       if ($d_idle < 1) $d_idle = 1;\r
-                       return 100*(1-$d_user/$d_idle);\r
-               }else {\r
-                       $total=$d_user+$d_nice+$d_system+$d_idle;\r
-                       if ($total<1) $total=1;\r
-                       return 100*($d_user+$d_nice+$d_system)/$total; \r
-               }\r
-       }\r
-       \r
-       function Tracer($sql)\r
-       {\r
-        $perf_table = adodb_perf::table();\r
-               $saveE = $this->conn->fnExecute;\r
-               $this->conn->fnExecute = false;\r
-                       \r
-               $sqlq = $this->conn->qstr($sql);\r
-               $arr = $this->conn->GetArray(\r
-"select count(*),tracer \r
-       from $perf_table where sql1=$sqlq \r
-       group by tracer\r
-       order by 1 desc");\r
-               $s = '';\r
-               if ($arr) {\r
-                       $s .= '<h3>Scripts Affected</h3>';\r
-                       foreach($arr as $k) {\r
-                               $s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';\r
-                       }\r
-               }\r
-               $this->conn->fnExecute = $saveE;\r
-               return $s;\r
-       }\r
-\r
-       /* \r
-               Explain Plan for $sql.\r
-               If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the \r
-                       actual sql.\r
-       */\r
-       function Explain($sql,$partial=false)\r
-       {       \r
-               return false;\r
-       }\r
-       \r
-       function InvalidSQL($numsql = 10)\r
-       {\r
-       global $HTTP_GET_VARS;\r
-       \r
-               if (isset($HTTP_GET_VARS['sql'])) return;\r
-               $s = '<h3>Invalid SQL</h3>';\r
-               $saveE = $this->conn->fnExecute;\r
-               $this->conn->fnExecute = false;\r
-        $perf_table = adodb_perf::table();\r
-               $rs =& $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from $perf_table where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql);\r
-               $this->conn->fnExecute = $saveE;\r
-               if ($rs) {\r
-                       $s .= rs2html($rs,false,false,false,false);\r
-               } else\r
-                       return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";\r
-               \r
-               return $s;\r
-       }\r
-\r
-       \r
-       /*\r
-               This script identifies the longest running SQL\r
-       */      \r
-       function _SuspiciousSQL($numsql = 10)\r
-       {\r
-               global $ADODB_FETCH_MODE,$HTTP_GET_VARS;\r
-               \r
-            $perf_table = adodb_perf::table();\r
-                       $saveE = $this->conn->fnExecute;\r
-                       $this->conn->fnExecute = false;\r
-                       \r
-                       if (isset($HTTP_GET_VARS['exps']) && isset($HTTP_GET_VARS['sql'])) {\r
-                               $partial = !empty($HTTP_GET_VARS['part']);\r
-                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";\r
-                       }\r
-                       \r
-                       if (isset($HTTP_GET_VARS['sql'])) return;\r
-                       $sql1 = $this->sql1;\r
-                       \r
-                       $save = $ADODB_FETCH_MODE;\r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-                       //$this->conn->debug=1;\r
-                       $rs =& $this->conn->SelectLimit(\r
-                       "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer\r
-                               from $perf_table\r
-                               where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')\r
-                               and (tracer is null or tracer not like 'ERROR:%')\r
-                               group by sql1\r
-                               order by 1 desc",$numsql);\r
-                       $ADODB_FETCH_MODE = $save;\r
-                       $this->conn->fnExecute = $saveE;\r
-                       \r
-                       if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";\r
-                       $s = "<h3>Suspicious SQL</h3>\r
-<font size=1>The following SQL have high average execution times</font><br>\r
-<table border=1 bgcolor=white><tr><td><b>Avg Time</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";\r
-                       $max = $this->maxLength;\r
-                       while (!$rs->EOF) {\r
-                               $sql = $rs->fields[1];\r
-                               $raw = urlencode($sql);\r
-                               if (strlen($raw)>$max-100) {\r
-                                       $sql2 = substr($sql,0,$max-500);\r
-                                       $raw = urlencode($sql2).'&part='.crc32($sql);\r
-                               }\r
-                               $prefix = "<a target=sql".rand()." href=\"?hidem=1&exps=1&sql=".$raw."&x#explain\">";\r
-                               $suffix = "</a>";\r
-                               if ($this->explain == false || strlen($prefix)>$max) {\r
-                                       $suffix = ' ... <i>String too long for GET parameter: '.strlen($prefix).'</i>';\r
-                                       $prefix = '';\r
-                               }\r
-                               $s .= "<tr><td>".round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".\r
-                                       "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";\r
-                               $rs->MoveNext();\r
-                       }\r
-                       return $s."</table>";\r
-               \r
-       }\r
-       \r
-       function CheckMemory()\r
-       {\r
-               return '';\r
-       }\r
-       \r
-       \r
-       function SuspiciousSQL($numsql=10)\r
-       {\r
-               return adodb_perf::_SuspiciousSQL($numsql);\r
-       }\r
-\r
-       function ExpensiveSQL($numsql=10)\r
-       {\r
-               return adodb_perf::_ExpensiveSQL($numsql);\r
-       }\r
-\r
-       \r
-       /*\r
-               This reports the percentage of load on the instance due to the most \r
-               expensive few SQL statements. Tuning these statements can often \r
-               make huge improvements in overall system performance. \r
-       */\r
-       function _ExpensiveSQL($numsql = 10)\r
-       {\r
-               global $HTTP_GET_VARS,$ADODB_FETCH_MODE;\r
-               \r
-            $perf_table = adodb_perf::table();\r
-                       $saveE = $this->conn->fnExecute;\r
-                       $this->conn->fnExecute = false;\r
-                       \r
-                       if (isset($HTTP_GET_VARS['expe']) && isset($HTTP_GET_VARS['sql'])) {\r
-                               $partial = !empty($HTTP_GET_VARS['part']);\r
-                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";\r
-                       }\r
-                       \r
-                       if (isset($HTTP_GET_VARS['sql'])) return;\r
-                       \r
-                       $sql1 = $this->sql1;\r
-                       $save = $ADODB_FETCH_MODE;\r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-                       $rs =& $this->conn->SelectLimit(\r
-                       "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer\r
-                               from $perf_table\r
-                               where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5))  not in ('DROP ','INSER','COMMI','CREAT')\r
-                               and (tracer is null or tracer not like 'ERROR:%')\r
-                               group by sql1\r
-                               order by 1 desc",$numsql);\r
-                       \r
-                       $this->conn->fnExecute = $saveE;\r
-                       $ADODB_FETCH_MODE = $save;\r
-                       if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";\r
-                       $s = "<h3>Expensive SQL</h3>\r
-<font size=1>Tuning the following SQL will reduce the server load substantially</font><br>\r
-<table border=1 bgcolor=white><tr><td><b>Load</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";\r
-                       $max = $this->maxLength;\r
-                       while (!$rs->EOF) {\r
-                               $sql = $rs->fields[1];\r
-                               $raw = urlencode($sql);\r
-                               if (strlen($raw)>$max-100) {\r
-                                       $sql2 = substr($sql,0,$max-500);\r
-                                       $raw = urlencode($sql2).'&part='.crc32($sql);\r
-                               }\r
-                               $prefix = "<a target=sqle".rand()." href=\"?hidem=1&expe=1&sql=".$raw."&x#explain\">";\r
-                               $suffix = "</a>";\r
-                               if($this->explain == false || strlen($prefix>$max)) {\r
-                                       $prefix = '';\r
-                                       $suffix = '';\r
-                               }\r
-                               $s .= "<tr><td>".round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".\r
-                                       "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";\r
-                               $rs->MoveNext();\r
-                       }\r
-                       return $s."</table>";\r
-       }\r
-       \r
-       /*\r
-               Raw function to return parameter value from $settings.\r
-       */\r
-       function DBParameter($param)\r
-       {\r
-               if (empty($this->settings[$param])) return false;\r
-               $sql = $this->settings[$param][1];\r
-               return $this->_DBParameter($sql);\r
-       }\r
-       \r
-       /*\r
-               Raw function returning array of poll paramters\r
-       */\r
-       function &PollParameters()\r
-       {\r
-               $arr[0] = (float)$this->DBParameter('data cache hit ratio');\r
-               $arr[1] = (float)$this->DBParameter('data reads');\r
-               $arr[2] = (float)$this->DBParameter('data writes');\r
-               $arr[3] = (integer) $this->DBParameter('current connections');\r
-               return $arr;\r
-       }\r
-       \r
-       /*\r
-               Low-level Get Database Parameter\r
-       */\r
-       function _DBParameter($sql)\r
-       {\r
-               $savelog = $this->conn->LogSQL(false);\r
-               if (is_array($sql)) {\r
-               global $ADODB_FETCH_MODE;\r
-               \r
-                       $sql1 = $sql[0];\r
-                       $key = $sql[1];\r
-                       if (sizeof($sql)>2) $pos = $sql[2];\r
-                       else $pos = 1;\r
-                       if (sizeof($sql)>3) $coef = $sql[3];\r
-                       else $coef = false;\r
-                       $ret = false;\r
-                       $save = $ADODB_FETCH_MODE;\r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-                       $rs = $this->conn->Execute($sql1);\r
-                       $ADODB_FETCH_MODE = $save;\r
-                       if ($rs) {\r
-                               while (!$rs->EOF) {\r
-                                       $keyf = reset($rs->fields);\r
-                                       if (trim($keyf) == $key) {\r
-                                               $ret = $rs->fields[$pos];\r
-                                               if ($coef) $ret *= $coef;\r
-                                               break;\r
-                                       }\r
-                                       $rs->MoveNext();\r
-                               }\r
-                               $rs->Close();\r
-                       }\r
-                       $this->conn->LogSQL($savelog);\r
-                       return $ret;\r
-               } else {\r
-                       if (strncmp($sql,'=',1) == 0) {\r
-                               $fn = substr($sql,1);\r
-                               return $this->$fn();\r
-                       }\r
-                       $sql = str_replace('$DATABASE',$this->conn->database,$sql);\r
-                       $ret = $this->conn->GetOne($sql);\r
-                       $this->conn->LogSQL($savelog);\r
-                       \r
-                       return $ret;\r
-               }\r
-       }\r
-       \r
-       /*\r
-               Warn if cache ratio falls below threshold. Displayed in "Description" column.\r
-       */\r
-       function WarnCacheRatio($val)\r
-       {\r
-               if ($val < $this->warnRatio) \r
-                        return '<font color=red><b>Cache ratio should be at least '.$this->warnRatio.'%</b></font>';\r
-               else return '';\r
-       }\r
-       \r
-       /***********************************************************************************************/\r
-       //                                    HIGH LEVEL UI FUNCTIONS\r
-       /***********************************************************************************************/\r
-\r
-       \r
-       function UI($pollsecs=5)\r
-       {\r
-       global $HTTP_GET_VARS,$HTTP_SERVER_VARS,$HTTP_POST_VARS;\r
-       \r
-    $perf_table = adodb_perf::table();\r
-       $conn = $this->conn;\r
-       \r
-       $app = $conn->host;\r
-       if ($conn->host && $conn->database) $app .= ', db=';\r
-       $app .= $conn->database;\r
-       \r
-       if ($app) $app .= ', ';\r
-       $savelog = $this->conn->LogSQL(false);  \r
-       $info = $conn->ServerInfo();\r
-       if (isset($HTTP_GET_VARS['clearsql'])) {\r
-               $this->conn->Execute('delete from $perf_table');\r
-       }\r
-       $this->conn->LogSQL($savelog);\r
-       \r
-       // magic quotes\r
-       \r
-       if (isset($HTTP_GET_VARS['sql']) && get_magic_quotes_gpc()) {\r
-               $_GET['sql'] = $HTTP_GET_VARS['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$HTTP_GET_VARS['sql']);\r
-       }\r
-       \r
-       if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;\r
-       else  $nsql = $_SESSION['ADODB_PERF_SQL'];\r
-       \r
-       $app .= '<font size=-1>'.$info['description'].'</font>';\r
-       \r
-       \r
-       if (isset($HTTP_GET_VARS['do'])) $do = $HTTP_GET_VARS['do'];\r
-       else if (isset($HTTP_POST_VARS['do'])) $do = $HTTP_POST_VARS['do'];\r
-        else if (isset($HTTP_GET_VARS['sql'])) $do = 'viewsql';\r
-        else $do = 'stats';\r
-        \r
-       if (isset($HTTP_GET_VARS['nsql'])) {\r
-               if ($HTTP_GET_VARS['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $HTTP_GET_VARS['nsql'];\r
-       }\r
-       echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";\r
-       if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";\r
-       else $form = "<td>&nbsp;</td>";\r
-       \r
-       $allowsql = !defined('ADODB_PERF_NO_RUN_SQL');\r
-       \r
-       if  (empty($HTTP_GET_VARS['hidem']))\r
-       echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>\r
-       <b><a href=http://php.weblogs.com/adodb?perf=1>ADOdb</a> Performance Monitor</b> for $app</tr><tr><td>\r
-       <a href=?do=stats>Performance Stats</a> &nbsp; <a href=?do=viewsql>View SQL</a>\r
-        &nbsp; <a href=?do=tables>View Tables</a> &nbsp; <a href=?do=poll>Poll Stats</a>",\r
-        $allowsql ? ' &nbsp; <a href=?do=dosql>Run SQL</a>' : '',\r
-        "$form",\r
-        "</tr></table>";\r
-\r
-        \r
-               switch ($do) {\r
-               default:\r
-               case 'stats':\r
-                       echo $this->HealthCheck();\r
-                       $this->conn->debug=1;\r
-                       echo $this->CheckMemory();\r
-                       break;\r
-               case 'poll':\r
-                       echo "<iframe width=720 height=80% \r
-                               src=\"{$HTTP_SERVER_VARS['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";\r
-                       break;\r
-               case 'poll2':\r
-                       echo "<pre>";\r
-                       $this->Poll($pollsecs);\r
-                       break;\r
-               \r
-               case 'dosql':\r
-                       if (!$allowsql) break;\r
-                       \r
-                       $this->DoSQLForm();\r
-                       break;\r
-               case 'viewsql':\r
-                       if (empty($HTTP_GET_VARS['hidem']))\r
-                               echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";\r
-                       echo($this->SuspiciousSQL($nsql));\r
-                       echo($this->ExpensiveSQL($nsql));\r
-                       echo($this->InvalidSQL($nsql));\r
-                       break;\r
-               case 'tables': \r
-                       echo $this->Tables(); break;\r
-               }\r
-               global $ADODB_vers;\r
-               echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";\r
-       }\r
-       \r
-       /*\r
-               Runs in infinite loop, returning real-time statistics\r
-       */\r
-       function Poll($secs=5)\r
-       {\r
-               $this->conn->fnExecute = false;\r
-               //$this->conn->debug=1;\r
-               if ($secs <= 1) $secs = 1;\r
-               echo "Accumulating statistics, every $secs seconds...\n";flush();\r
-               $arro =& $this->PollParameters();\r
-               $cnt = 0;\r
-               set_time_limit(0);\r
-               sleep($secs);\r
-               while (1) {\r
-                       $arr =& $this->PollParameters();\r
-                       \r
-                       $hits   = sprintf('%2.2f',$arr[0]);\r
-                       $reads  = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);\r
-                       $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);\r
-                       $sess = sprintf('%5d',$arr[3]);\r
-                       \r
-                       $load = $this->CPULoad();\r
-                       if ($load !== false) {\r
-                               $oslabel = 'WS-CPU%';\r
-                               $osval = sprintf(" %2.1f  ",(float) $load);\r
-                       }else {\r
-                               $oslabel = '';\r
-                               $osval = '';\r
-                       }\r
-                       if ($cnt % 10 == 0) echo " Time   ".$oslabel."   Hit%   Sess           Reads/s          Writes/s\n"; \r
-                       $cnt += 1;\r
-                       echo date('H:i:s').'  '.$osval."$hits  $sess $reads $writes\n";\r
-                       flush();\r
-                       \r
-                       sleep($secs);\r
-                       $arro = $arr;\r
-               }\r
-       }\r
-       \r
-       /*\r
-               Returns basic health check in a command line interface\r
-       */\r
-       function HealthCheckCLI()\r
-       {\r
-               return $this->HealthCheck(true);\r
-       }\r
-       \r
-               \r
-       /*\r
-               Returns basic health check as HTML\r
-       */\r
-       function HealthCheck($cli=false)\r
-       {\r
-               $saveE = $this->conn->fnExecute;\r
-               $this->conn->fnExecute = false; \r
-               if ($cli) $html = '';\r
-               else $html = $this->table.'<tr><td colspan=3><h3>'.$this->conn->databaseType.'</h3></td></tr>'.$this->titles;\r
-               \r
-               $oldc = false;\r
-               $bgc = '';\r
-               foreach($this->settings as $name => $arr) {\r
-                       if ($arr === false) break;\r
-                       \r
-                       if (!is_string($name)) {\r
-                               if ($cli) $html .= " -- $arr -- \n";\r
-                               else $html .= "<tr bgcolor=$this->color><td colspan=3><i>$arr</i> &nbsp;</td></tr>";\r
-                               continue;\r
-                       }\r
-                       \r
-                       if (!is_array($arr)) break;\r
-                       $category = $arr[0];\r
-                       $how = $arr[1];\r
-                       if (sizeof($arr)>2) $desc = $arr[2];\r
-                       else $desc = ' &nbsp; ';\r
-                       \r
-                       \r
-                       if ($category == 'HIDE') continue;\r
-                       \r
-                       $val = $this->_DBParameter($how);\r
-                       \r
-                       if ($desc && strncmp($desc,"=",1) === 0) {\r
-                               $fn = substr($desc,1);\r
-                               $desc = $this->$fn($val);\r
-                       }\r
-                       \r
-                       if ($val === false) {\r
-                               $m = $this->conn->ErrorMsg();\r
-                               $val = "Error: $m"; \r
-                       } else {\r
-                               if (is_numeric($val) && $val >= 256*1024) {\r
-                                       if ($val % (1024*1024) == 0) {\r
-                                               $val /= (1024*1024);\r
-                                               $val .= 'M';\r
-                                       } else if ($val % 1024 == 0) {\r
-                                               $val /= 1024;\r
-                                               $val .= 'K';\r
-                                       }\r
-                                       //$val = htmlspecialchars($val);\r
-                               }\r
-                       }\r
-                       if ($category != $oldc) {\r
-                               $oldc = $category;\r
-                               //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color;\r
-                       }\r
-                       if (strlen($desc)==0) $desc = '&nbsp;';\r
-                       if (strlen($val)==0) $val = '&nbsp;';\r
-                       if ($cli) {\r
-                               $html  .= str_replace('&nbsp;','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc)));\r
-                               \r
-                       }else {\r
-                               $html .= "<tr$bgc><td>".$name.'</td><td>'.$val.'</td><td>'.$desc."</td></tr>\n";\r
-                       }\r
-               }\r
-               \r
-               if (!$cli) $html .= "</table>\n";\r
-               $this->conn->fnExecute = $saveE;\r
-                       \r
-               return $html;   \r
-       }\r
-       \r
-       function Tables($orderby='1')\r
-       {\r
-               if (!$this->tablesSQL) return false;\r
-               \r
-               $savelog = $this->conn->LogSQL(false);\r
-               $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby);\r
-               $this->conn->LogSQL($savelog);\r
-               $html = rs2html($rs,false,false,false,false);\r
-               return $html;\r
-       }\r
-       \r
-\r
-       function CreateLogTable()\r
-       {\r
-               if (!$this->createTableSQL) return false;\r
-               \r
-               $savelog = $this->conn->LogSQL(false);\r
-               $ok = $this->conn->Execute($this->createTableSQL);\r
-               $this->conn->LogSQL($savelog);\r
-               return ($ok) ? true : false;\r
-       }\r
-       \r
-       function DoSQLForm()\r
-       {\r
-       global $HTTP_SERVER_VARS,$HTTP_GET_VARS,$HTTP_POST_VARS,$HTTP_SESSION_VARS;\r
-       \r
-               $HTTP_VARS = array_merge($HTTP_GET_VARS,$HTTP_POST_VARS);\r
-               \r
-               $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];\r
-               $sql = isset($HTTP_VARS['sql']) ? $HTTP_VARS['sql'] : '';\r
-\r
-               if (isset($HTTP_SESSION_VARS['phplens_sqlrows'])) $rows = $HTTP_SESSION_VARS['phplens_sqlrows'];\r
-               else $rows = 3;\r
-               \r
-               if (isset($HTTP_VARS['SMALLER'])) {\r
-                       $rows /= 2;\r
-                       if ($rows < 3) $rows = 3;\r
-                       $HTTP_SESSION_VARS['phplens_sqlrows'] = $rows;\r
-               }\r
-               if (isset($HTTP_VARS['BIGGER'])) {\r
-                       $rows *= 2;\r
-                       $HTTP_SESSION_VARS['phplens_sqlrows'] = $rows;\r
-               }\r
-               \r
-?>\r
-\r
-<form method="POST" action="<?php echo $PHP_SELF ?>">\r
-<table><tr>\r
-<td> Form size: <input type="submit" value=" &lt; " name="SMALLER"><input type="submit" value=" &gt; &gt; " name="BIGGER">\r
-</td>\r
-<td align=right>\r
-<input type="submit" value=" Run SQL Below " name="RUN"><input type=hidden name=do value=dosql>\r
-</td></tr>\r
-  <tr>\r
-  <td colspan=2><textarea rows=<?php print $rows; ?> name="sql" cols="80"><?php print htmlspecialchars($sql) ?></textarea>\r
-  </td>\r
-  </tr>\r
- </table>\r
-</form>\r
-\r
-<?php\r
-               if (!isset($HTTP_VARS['sql'])) return;\r
-               \r
-               $sql = $this->undomq(trim($sql));\r
-               if (substr($sql,strlen($sql)-1) === ';') {\r
-                       $print = true;\r
-                       $sqla = $this->SplitSQL($sql);\r
-               } else  {\r
-                       $print = false;\r
-                       $sqla = array($sql);\r
-               }\r
-               foreach($sqla as $sqls) {\r
-\r
-                       if (!$sqls) continue;\r
-                       \r
-                       if ($print) {\r
-                               print "<p>".htmlspecialchars($sqls)."</p>";\r
-                               flush();\r
-                       }\r
-                       $savelog = $this->conn->LogSQL(false);\r
-                       $rs = $this->conn->Execute($sqls);\r
-                       $this->conn->LogSQL($savelog);\r
-                       if ($rs && is_object($rs) && !$rs->EOF) {\r
-                               rs2html($rs);\r
-                               while ($rs->NextRecordSet()) {\r
-                                       print "<table width=98% bgcolor=#C0C0FF><tr><td>&nbsp;</td></tr></table>";\r
-                                       rs2html($rs);\r
-                               }\r
-                       } else {\r
-                               $e1 = (integer) $this->conn->ErrorNo();\r
-                               $e2 = $this->conn->ErrorMsg();\r
-                               if (($e1) || ($e2)) {\r
-                                       if (empty($e1)) $e1 = '-1'; // postgresql fix\r
-                                       print ' &nbsp; '.$e1.': '.$e2;\r
-                               } else {\r
-                                       print "<p>No Recordset returned<br></p>";\r
-                               }\r
-                       }\r
-               } // foreach\r
-       }\r
-       \r
-       function SplitSQL($sql)\r
-       {\r
-               $arr = explode(';',$sql);\r
-               return $arr;\r
-       }\r
-       \r
-       function undomq(&$m) \r
-       {\r
-       if (get_magic_quotes_gpc()) {\r
-               // undo the damage\r
-               $m = str_replace('\\\\','\\',$m);\r
-               $m = str_replace('\"','"',$m);\r
-               $m = str_replace('\\\'','\'',$m);\r
-       }\r
-       return $m;\r
-}\r
-}\r
-\r
-\r
-\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Library for basic performance monitoring and tuning.
+  
+  My apologies if you see code mixed with presentation. The presentation suits
+  my needs. If you want to separate code from presentation, be my guest. Patches
+  are welcome.
+  
+*/
+
+if (!defined(ADODB_DIR)) include_once(dirname(__FILE__).'/adodb.inc.php');
+include_once(ADODB_DIR.'/tohtml.inc.php');
+
+
+/* return microtime value as a float */
+function adodb_microtime()
+{
+       $t = microtime();
+       $t = explode(' ',$t);
+       return (float)$t[1]+ (float)$t[0];
+}
+
+/* sql code timing */
+function& adodb_log_sql(&$conn,$sql,$inputarr)
+{
+global $HTTP_SERVER_VARS;
+       
+    $perf_table = adodb_perf::table();
+       $conn->fnExecute = false;
+       $t0 = microtime();
+       $rs =& $conn->Execute($sql,$inputarr);
+       $t1 = microtime();
+
+       if (!empty($conn->_logsql)) {
+               $conn->_logsql = false; // disable logsql error simulation
+               $dbT = $conn->databaseType;
+               
+               $a0 = split(' ',$t0);
+               $a0 = (float)$a0[1]+(float)$a0[0];
+               
+               $a1 = split(' ',$t1);
+               $a1 = (float)$a1[1]+(float)$a1[0];
+               
+               $time = $a1 - $a0;
+       
+               if (!$rs) {
+                       $errM = $conn->ErrorMsg();
+                       $errN = $conn->ErrorNo();
+                       $conn->lastInsID = 0;
+                       $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);
+               } else {
+                       $tracer = '';
+                       $errM = '';
+                       $errN = 0;
+                       $dbg = $conn->debug;
+                       $conn->debug = false;
+                       if (!is_object($rs) || $rs->dataProvider == 'empty') 
+                               $conn->_affected = $conn->affected_rows(true);
+                       $conn->lastInsID = @$conn->Insert_ID();
+                       $conn->debug = $dbg;
+               }
+               if (isset($HTTP_SERVER_VARS['HTTP_HOST'])) {
+                       $tracer .= '<br>'.$HTTP_SERVER_VARS['HTTP_HOST'];
+                       if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= $HTTP_SERVER_VARS['PHP_SELF'];
+               } else 
+                       if (isset($HTTP_SERVER_VARS['PHP_SELF'])) $tracer .= '<br>'.$HTTP_SERVER_VARS['PHP_SELF'];
+               //$tracer .= (string) adodb_backtrace(false);
+               
+               $tracer = substr($tracer,0,500);
+               
+               if (is_array($inputarr)) {
+                       if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);
+                       else {
+                               $params = '';
+                               $params = implode(', ',$inputarr);
+                               if (strlen($params) >= 3000) $params = substr($params, 0, 3000);
+                       }
+               } else {
+                       $params = '';
+               }
+               
+               if (is_array($sql)) $sql = $sql[0];
+               $arr = array('b'=>trim(substr($sql,0,230)),
+                                       'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>round($time,6));
+
+               $saved = $conn->debug;
+               $conn->debug = 0;
+               
+               if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {
+                       $isql = "insert into $perf_table values($conn->sysTimeStamp,:b,:c,:d,:e,:f)";
+               } else if ($dbT == 'odbc_mssql' || $dbT == 'informix') {
+                       $timer = $arr['f'];
+                       if ($dbT == 'informix') $sql2 = substr($sql2,0,230);
+
+                       $sql1 = $conn->qstr($arr['b']);
+                       $sql2 = $conn->qstr($arr['c']);
+                       $params = $conn->qstr($arr['d']);
+                       $tracer = $conn->qstr($arr['e']);
+                       
+                       $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($conn->sysTimeStamp,$sql1,$sql2,$params,$tracer,$timer)";
+                       if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);
+                       $arr = false;
+               } else {
+                       $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $conn->sysTimeStamp,?,?,?,?,?)";
+               }
+               $ok = $conn->Execute($isql,$arr);
+               $conn->debug = $saved;
+               
+               if ($ok) {
+                       $conn->_logsql = true; 
+               } else {
+                       $err2 = $conn->ErrorMsg();
+                       $conn->_logsql = true; // enable logsql error simulation
+                       $perf =& NewPerfMonitor($conn);
+                       if ($perf) {
+                               if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr);
+                       } else {
+                               $ok = $conn->Execute("create table $perf_table (
+                               created varchar(50),
+                               sql0 varchar(250), 
+                               sql1 varchar(4000),
+                               params varchar(3000),
+                               tracer varchar(500),
+                               timer decimal(16,6))");
+                       }
+                       if (!$ok) {
+                               ADOConnection::outp( "<b>LOGSQL Insert Failed</b>: $isql<br>$err2</br>");
+                               $conn->_logsql = false;
+                       }
+               }
+               $conn->_errorMsg = $errM;
+               $conn->_errorCode = $errN;
+       } 
+       $conn->fnExecute = 'adodb_log_sql';
+       return $rs;
+}
+
+       
+/*
+The settings data structure is an associative array that database parameter per element.
+
+Each database parameter element in the array is itself an array consisting of:
+
+0: category code, used to group related db parameters
+1: either
+       a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'", 
+       b. array holding sql string and field to look for, e.g. array('show variables','table_cache'),
+       c. a string prefixed by =, then a PHP method of the class is invoked, 
+               e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue',
+2: description of the database parameter
+*/
+
+class adodb_perf {
+       var $conn;
+       var $color = '#F0F0F0';
+       var $table = '<table border=1 bgcolor=white>';
+       var $titles = '<tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr>';
+       var $warnRatio = 90;
+       var $tablesSQL = false;
+       var $cliFormat = "%32s => %s \r\n";
+       var $sql1 = 'sql1';  // used for casting sql1 to text for mssql
+       var $explain = true;
+       var $helpurl = "<a href=http://phplens.com/adodb/reference.functions.fnexecute.and.fncacheexecute.properties.html#logsql>LogSQL help</a>";
+       var $createTableSQL = false;
+       var $maxLength = 2000;
+       
+    // Sets the tablename to be used            
+    function table($newtable = false)
+    {
+        static $_table;
+
+        if (!empty($newtable))  $_table = $newtable;
+               if (empty($_table)) $_table = 'adodb_logsql';
+        return $_table;
+    }
+
+       // returns array with info to calculate CPU Load
+       function _CPULoad()
+       {
+/*
+
+cpu  524152 2662 2515228 336057010
+cpu0 264339 1408 1257951 168025827
+cpu1 259813 1254 1257277 168031181
+page 622307 25475680
+swap 24 1891
+intr 890153570 868093576 6 0 4 4 0 6 1 2 0 0 0 124 0 8098760 2 13961053 0 0 0 0 0 0 0 0 0 0 0 0 0 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320)
+ctxt 66155838
+btime 1062315585
+processes 69293
+
+*/
+               // Algorithm is taken from
+               // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp
+               if (strncmp(PHP_OS,'WIN',3)==0) {
+                       @$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");
+                       if (!$c) return false;
+                       
+                       $info[0] = $c->PercentProcessorTime;
+                       $info[1] = 0;
+                       $info[2] = 0;
+                       $info[3] = $c->TimeStamp_Sys100NS;
+                       //print_r($info);
+                       return $info;
+               }
+               
+               // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com)
+               $statfile = '/proc/stat';
+               if (!file_exists($statfile)) return false;
+               
+               $fd = fopen($statfile,"r");
+               if (!$fd) return false;
+               
+               $statinfo = explode("\n",fgets($fd, 1024));
+               fclose($fd);
+               foreach($statinfo as $line) {
+                       $info = explode(" ",$line);
+                       if($info[0]=="cpu") {
+                               array_shift($info);  // pop off "cpu"
+                               if(!$info[0]) array_shift($info); // pop off blank space (if any)
+                               return $info;
+                       }
+               }
+               
+               return false;
+               
+       }
+       
+       /* NOT IMPLEMENTED */
+       function MemInfo()
+       {
+               /*
+
+        total:    used:    free:  shared: buffers:  cached:
+Mem:  1055289344 917299200 137990144        0 165437440 599773184
+Swap: 2146775040 11055104 2135719936
+MemTotal:      1030556 kB
+MemFree:        134756 kB
+MemShared:           0 kB
+Buffers:        161560 kB
+Cached:         581384 kB
+SwapCached:       4332 kB
+Active:         494468 kB
+Inact_dirty:    322856 kB
+Inact_clean:     24256 kB
+Inact_target:   168316 kB
+HighTotal:      131064 kB
+HighFree:         1024 kB
+LowTotal:       899492 kB
+LowFree:        133732 kB
+SwapTotal:     2096460 kB
+SwapFree:      2085664 kB
+Committed_AS:   348732 kB
+               */
+       }
+       
+       
+       /*
+               Remember that this is client load, not db server load!
+       */
+       var $_lastLoad;
+       function CPULoad()
+       {
+               $info = $this->_CPULoad();
+               if (!$info) return false;
+                       
+               if (empty($this->_lastLoad)) {
+                       sleep(1);
+                       $this->_lastLoad = $info;
+                       $info = $this->_CPULoad();
+               }
+               
+               $last = $this->_lastLoad;
+               $this->_lastLoad = $info;
+               
+               $d_user = $info[0] - $last[0];
+               $d_nice = $info[1] - $last[1];
+               $d_system = $info[2] - $last[2];
+               $d_idle = $info[3] - $last[3];
+               
+               //printf("Delta - User: %f  Nice: %f  System: %f  Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
+
+               if (strncmp(PHP_OS,'WIN',3)==0) {
+                       if ($d_idle < 1) $d_idle = 1;
+                       return 100*(1-$d_user/$d_idle);
+               }else {
+                       $total=$d_user+$d_nice+$d_system+$d_idle;
+                       if ($total<1) $total=1;
+                       return 100*($d_user+$d_nice+$d_system)/$total; 
+               }
+       }
+       
+       function Tracer($sql)
+       {
+        $perf_table = adodb_perf::table();
+               $saveE = $this->conn->fnExecute;
+               $this->conn->fnExecute = false;
+                       
+               $sqlq = $this->conn->qstr($sql);
+               $arr = $this->conn->GetArray(
+"select count(*),tracer 
+       from $perf_table where sql1=$sqlq 
+       group by tracer
+       order by 1 desc");
+               $s = '';
+               if ($arr) {
+                       $s .= '<h3>Scripts Affected</h3>';
+                       foreach($arr as $k) {
+                               $s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';
+                       }
+               }
+               $this->conn->fnExecute = $saveE;
+               return $s;
+       }
+
+       /* 
+               Explain Plan for $sql.
+               If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the 
+                       actual sql.
+       */
+       function Explain($sql,$partial=false)
+       {       
+               return false;
+       }
+       
+       function InvalidSQL($numsql = 10)
+       {
+       global $HTTP_GET_VARS;
+       
+               if (isset($HTTP_GET_VARS['sql'])) return;
+               $s = '<h3>Invalid SQL</h3>';
+               $saveE = $this->conn->fnExecute;
+               $this->conn->fnExecute = false;
+        $perf_table = adodb_perf::table();
+               $rs =& $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from $perf_table where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql);
+               $this->conn->fnExecute = $saveE;
+               if ($rs) {
+                       $s .= rs2html($rs,false,false,false,false);
+               } else
+                       return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
+               
+               return $s;
+       }
+
+       
+       /*
+               This script identifies the longest running SQL
+       */      
+       function _SuspiciousSQL($numsql = 10)
+       {
+               global $ADODB_FETCH_MODE,$HTTP_GET_VARS;
+               
+            $perf_table = adodb_perf::table();
+                       $saveE = $this->conn->fnExecute;
+                       $this->conn->fnExecute = false;
+                       
+                       if (isset($HTTP_GET_VARS['exps']) && isset($HTTP_GET_VARS['sql'])) {
+                               $partial = !empty($HTTP_GET_VARS['part']);
+                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
+                       }
+                       
+                       if (isset($HTTP_GET_VARS['sql'])) return;
+                       $sql1 = $this->sql1;
+                       
+                       $save = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                       //$this->conn->debug=1;
+                       $rs =& $this->conn->SelectLimit(
+                       "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
+                               from $perf_table
+                               where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
+                               and (tracer is null or tracer not like 'ERROR:%')
+                               group by sql1
+                               order by 1 desc",$numsql);
+                       $ADODB_FETCH_MODE = $save;
+                       $this->conn->fnExecute = $saveE;
+                       
+                       if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
+                       $s = "<h3>Suspicious SQL</h3>
+<font size=1>The following SQL have high average execution times</font><br>
+<table border=1 bgcolor=white><tr><td><b>Avg Time</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
+                       $max = $this->maxLength;
+                       while (!$rs->EOF) {
+                               $sql = $rs->fields[1];
+                               $raw = urlencode($sql);
+                               if (strlen($raw)>$max-100) {
+                                       $sql2 = substr($sql,0,$max-500);
+                                       $raw = urlencode($sql2).'&part='.crc32($sql);
+                               }
+                               $prefix = "<a target=sql".rand()." href=\"?hidem=1&exps=1&sql=".$raw."&x#explain\">";
+                               $suffix = "</a>";
+                               if ($this->explain == false || strlen($prefix)>$max) {
+                                       $suffix = ' ... <i>String too long for GET parameter: '.strlen($prefix).'</i>';
+                                       $prefix = '';
+                               }
+                               $s .= "<tr><td>".round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
+                                       "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
+                               $rs->MoveNext();
+                       }
+                       return $s."</table>";
+               
+       }
+       
+       function CheckMemory()
+       {
+               return '';
+       }
+       
+       
+       function SuspiciousSQL($numsql=10)
+       {
+               return adodb_perf::_SuspiciousSQL($numsql);
+       }
+
+       function ExpensiveSQL($numsql=10)
+       {
+               return adodb_perf::_ExpensiveSQL($numsql);
+       }
+
+       
+       /*
+               This reports the percentage of load on the instance due to the most 
+               expensive few SQL statements. Tuning these statements can often 
+               make huge improvements in overall system performance. 
+       */
+       function _ExpensiveSQL($numsql = 10)
+       {
+               global $HTTP_GET_VARS,$ADODB_FETCH_MODE;
+               
+            $perf_table = adodb_perf::table();
+                       $saveE = $this->conn->fnExecute;
+                       $this->conn->fnExecute = false;
+                       
+                       if (isset($HTTP_GET_VARS['expe']) && isset($HTTP_GET_VARS['sql'])) {
+                               $partial = !empty($HTTP_GET_VARS['part']);
+                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
+                       }
+                       
+                       if (isset($HTTP_GET_VARS['sql'])) return;
+                       
+                       $sql1 = $this->sql1;
+                       $save = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                       $rs =& $this->conn->SelectLimit(
+                       "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
+                               from $perf_table
+                               where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5))  not in ('DROP ','INSER','COMMI','CREAT')
+                               and (tracer is null or tracer not like 'ERROR:%')
+                               group by sql1
+                               order by 1 desc",$numsql);
+                       
+                       $this->conn->fnExecute = $saveE;
+                       $ADODB_FETCH_MODE = $save;
+                       if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
+                       $s = "<h3>Expensive SQL</h3>
+<font size=1>Tuning the following SQL will reduce the server load substantially</font><br>
+<table border=1 bgcolor=white><tr><td><b>Load</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
+                       $max = $this->maxLength;
+                       while (!$rs->EOF) {
+                               $sql = $rs->fields[1];
+                               $raw = urlencode($sql);
+                               if (strlen($raw)>$max-100) {
+                                       $sql2 = substr($sql,0,$max-500);
+                                       $raw = urlencode($sql2).'&part='.crc32($sql);
+                               }
+                               $prefix = "<a target=sqle".rand()." href=\"?hidem=1&expe=1&sql=".$raw."&x#explain\">";
+                               $suffix = "</a>";
+                               if($this->explain == false || strlen($prefix>$max)) {
+                                       $prefix = '';
+                                       $suffix = '';
+                               }
+                               $s .= "<tr><td>".round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
+                                       "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
+                               $rs->MoveNext();
+                       }
+                       return $s."</table>";
+       }
+       
+       /*
+               Raw function to return parameter value from $settings.
+       */
+       function DBParameter($param)
+       {
+               if (empty($this->settings[$param])) return false;
+               $sql = $this->settings[$param][1];
+               return $this->_DBParameter($sql);
+       }
+       
+       /*
+               Raw function returning array of poll paramters
+       */
+       function &PollParameters()
+       {
+               $arr[0] = (float)$this->DBParameter('data cache hit ratio');
+               $arr[1] = (float)$this->DBParameter('data reads');
+               $arr[2] = (float)$this->DBParameter('data writes');
+               $arr[3] = (integer) $this->DBParameter('current connections');
+               return $arr;
+       }
+       
+       /*
+               Low-level Get Database Parameter
+       */
+       function _DBParameter($sql)
+       {
+               $savelog = $this->conn->LogSQL(false);
+               if (is_array($sql)) {
+               global $ADODB_FETCH_MODE;
+               
+                       $sql1 = $sql[0];
+                       $key = $sql[1];
+                       if (sizeof($sql)>2) $pos = $sql[2];
+                       else $pos = 1;
+                       if (sizeof($sql)>3) $coef = $sql[3];
+                       else $coef = false;
+                       $ret = false;
+                       $save = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                       $rs = $this->conn->Execute($sql1);
+                       $ADODB_FETCH_MODE = $save;
+                       if ($rs) {
+                               while (!$rs->EOF) {
+                                       $keyf = reset($rs->fields);
+                                       if (trim($keyf) == $key) {
+                                               $ret = $rs->fields[$pos];
+                                               if ($coef) $ret *= $coef;
+                                               break;
+                                       }
+                                       $rs->MoveNext();
+                               }
+                               $rs->Close();
+                       }
+                       $this->conn->LogSQL($savelog);
+                       return $ret;
+               } else {
+                       if (strncmp($sql,'=',1) == 0) {
+                               $fn = substr($sql,1);
+                               return $this->$fn();
+                       }
+                       $sql = str_replace('$DATABASE',$this->conn->database,$sql);
+                       $ret = $this->conn->GetOne($sql);
+                       $this->conn->LogSQL($savelog);
+                       
+                       return $ret;
+               }
+       }
+       
+       /*
+               Warn if cache ratio falls below threshold. Displayed in "Description" column.
+       */
+       function WarnCacheRatio($val)
+       {
+               if ($val < $this->warnRatio) 
+                        return '<font color=red><b>Cache ratio should be at least '.$this->warnRatio.'%</b></font>';
+               else return '';
+       }
+       
+       /***********************************************************************************************/
+       //                                    HIGH LEVEL UI FUNCTIONS
+       /***********************************************************************************************/
+
+       
+       function UI($pollsecs=5)
+       {
+       global $HTTP_GET_VARS,$HTTP_SERVER_VARS,$HTTP_POST_VARS;
+       
+    $perf_table = adodb_perf::table();
+       $conn = $this->conn;
+       
+       $app = $conn->host;
+       if ($conn->host && $conn->database) $app .= ', db=';
+       $app .= $conn->database;
+       
+       if ($app) $app .= ', ';
+       $savelog = $this->conn->LogSQL(false);  
+       $info = $conn->ServerInfo();
+       if (isset($HTTP_GET_VARS['clearsql'])) {
+               $this->conn->Execute("delete from $perf_table");
+       }
+       $this->conn->LogSQL($savelog);
+       
+       // magic quotes
+       
+       if (isset($HTTP_GET_VARS['sql']) && get_magic_quotes_gpc()) {
+               $_GET['sql'] = $HTTP_GET_VARS['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$HTTP_GET_VARS['sql']);
+       }
+       
+       if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;
+       else  $nsql = $_SESSION['ADODB_PERF_SQL'];
+       
+       $app .= '<font size=-1>'.$info['description'].'</font>';
+       
+       
+       if (isset($HTTP_GET_VARS['do'])) $do = $HTTP_GET_VARS['do'];
+       else if (isset($HTTP_POST_VARS['do'])) $do = $HTTP_POST_VARS['do'];
+        else if (isset($HTTP_GET_VARS['sql'])) $do = 'viewsql';
+        else $do = 'stats';
+        
+       if (isset($HTTP_GET_VARS['nsql'])) {
+               if ($HTTP_GET_VARS['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $HTTP_GET_VARS['nsql'];
+       }
+       echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";
+       if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";
+       else $form = "<td>&nbsp;</td>";
+       
+       $allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
+       
+       if  (empty($HTTP_GET_VARS['hidem']))
+       echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
+       <b><a href=http://php.weblogs.com/adodb?perf=1>ADOdb</a> Performance Monitor</b> for $app</tr><tr><td>
+       <a href=?do=stats>Performance Stats</a> &nbsp; <a href=?do=viewsql>View SQL</a>
+        &nbsp; <a href=?do=tables>View Tables</a> &nbsp; <a href=?do=poll>Poll Stats</a>",
+        $allowsql ? ' &nbsp; <a href=?do=dosql>Run SQL</a>' : '',
+        "$form",
+        "</tr></table>";
+
+        
+               switch ($do) {
+               default:
+               case 'stats':
+                       echo $this->HealthCheck();
+                       $this->conn->debug=1;
+                       echo $this->CheckMemory();
+                       break;
+               case 'poll':
+                       echo "<iframe width=720 height=80% 
+                               src=\"{$HTTP_SERVER_VARS['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";
+                       break;
+               case 'poll2':
+                       echo "<pre>";
+                       $this->Poll($pollsecs);
+                       break;
+               
+               case 'dosql':
+                       if (!$allowsql) break;
+                       
+                       $this->DoSQLForm();
+                       break;
+               case 'viewsql':
+                       if (empty($HTTP_GET_VARS['hidem']))
+                               echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
+                       echo($this->SuspiciousSQL($nsql));
+                       echo($this->ExpensiveSQL($nsql));
+                       echo($this->InvalidSQL($nsql));
+                       break;
+               case 'tables': 
+                       echo $this->Tables(); break;
+               }
+               global $ADODB_vers;
+               echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
+       }
+       
+       /*
+               Runs in infinite loop, returning real-time statistics
+       */
+       function Poll($secs=5)
+       {
+               $this->conn->fnExecute = false;
+               //$this->conn->debug=1;
+               if ($secs <= 1) $secs = 1;
+               echo "Accumulating statistics, every $secs seconds...\n";flush();
+               $arro =& $this->PollParameters();
+               $cnt = 0;
+               set_time_limit(0);
+               sleep($secs);
+               while (1) {
+                       $arr =& $this->PollParameters();
+                       
+                       $hits   = sprintf('%2.2f',$arr[0]);
+                       $reads  = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);
+                       $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);
+                       $sess = sprintf('%5d',$arr[3]);
+                       
+                       $load = $this->CPULoad();
+                       if ($load !== false) {
+                               $oslabel = 'WS-CPU%';
+                               $osval = sprintf(" %2.1f  ",(float) $load);
+                       }else {
+                               $oslabel = '';
+                               $osval = '';
+                       }
+                       if ($cnt % 10 == 0) echo " Time   ".$oslabel."   Hit%   Sess           Reads/s          Writes/s\n"; 
+                       $cnt += 1;
+                       echo date('H:i:s').'  '.$osval."$hits  $sess $reads $writes\n";
+                       flush();
+                       
+                       sleep($secs);
+                       $arro = $arr;
+               }
+       }
+       
+       /*
+               Returns basic health check in a command line interface
+       */
+       function HealthCheckCLI()
+       {
+               return $this->HealthCheck(true);
+       }
+       
+               
+       /*
+               Returns basic health check as HTML
+       */
+       function HealthCheck($cli=false)
+       {
+               $saveE = $this->conn->fnExecute;
+               $this->conn->fnExecute = false; 
+               if ($cli) $html = '';
+               else $html = $this->table.'<tr><td colspan=3><h3>'.$this->conn->databaseType.'</h3></td></tr>'.$this->titles;
+               
+               $oldc = false;
+               $bgc = '';
+               foreach($this->settings as $name => $arr) {
+                       if ($arr === false) break;
+                       
+                       if (!is_string($name)) {
+                               if ($cli) $html .= " -- $arr -- \n";
+                               else $html .= "<tr bgcolor=$this->color><td colspan=3><i>$arr</i> &nbsp;</td></tr>";
+                               continue;
+                       }
+                       
+                       if (!is_array($arr)) break;
+                       $category = $arr[0];
+                       $how = $arr[1];
+                       if (sizeof($arr)>2) $desc = $arr[2];
+                       else $desc = ' &nbsp; ';
+                       
+                       
+                       if ($category == 'HIDE') continue;
+                       
+                       $val = $this->_DBParameter($how);
+                       
+                       if ($desc && strncmp($desc,"=",1) === 0) {
+                               $fn = substr($desc,1);
+                               $desc = $this->$fn($val);
+                       }
+                       
+                       if ($val === false) {
+                               $m = $this->conn->ErrorMsg();
+                               $val = "Error: $m"; 
+                       } else {
+                               if (is_numeric($val) && $val >= 256*1024) {
+                                       if ($val % (1024*1024) == 0) {
+                                               $val /= (1024*1024);
+                                               $val .= 'M';
+                                       } else if ($val % 1024 == 0) {
+                                               $val /= 1024;
+                                               $val .= 'K';
+                                       }
+                                       //$val = htmlspecialchars($val);
+                               }
+                       }
+                       if ($category != $oldc) {
+                               $oldc = $category;
+                               //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color;
+                       }
+                       if (strlen($desc)==0) $desc = '&nbsp;';
+                       if (strlen($val)==0) $val = '&nbsp;';
+                       if ($cli) {
+                               $html  .= str_replace('&nbsp;','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc)));
+                               
+                       }else {
+                               $html .= "<tr$bgc><td>".$name.'</td><td>'.$val.'</td><td>'.$desc."</td></tr>\n";
+                       }
+               }
+               
+               if (!$cli) $html .= "</table>\n";
+               $this->conn->fnExecute = $saveE;
+                       
+               return $html;   
+       }
+       
+       function Tables($orderby='1')
+       {
+               if (!$this->tablesSQL) return false;
+               
+               $savelog = $this->conn->LogSQL(false);
+               $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby);
+               $this->conn->LogSQL($savelog);
+               $html = rs2html($rs,false,false,false,false);
+               return $html;
+       }
+       
+
+       function CreateLogTable()
+       {
+               if (!$this->createTableSQL) return false;
+               
+               $savelog = $this->conn->LogSQL(false);
+               $ok = $this->conn->Execute($this->createTableSQL);
+               $this->conn->LogSQL($savelog);
+               return ($ok) ? true : false;
+       }
+       
+       function DoSQLForm()
+       {
+       global $HTTP_SERVER_VARS,$HTTP_GET_VARS,$HTTP_POST_VARS,$HTTP_SESSION_VARS;
+       
+               $HTTP_VARS = array_merge($HTTP_GET_VARS,$HTTP_POST_VARS);
+               
+               $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
+               $sql = isset($HTTP_VARS['sql']) ? $HTTP_VARS['sql'] : '';
+
+               if (isset($HTTP_SESSION_VARS['phplens_sqlrows'])) $rows = $HTTP_SESSION_VARS['phplens_sqlrows'];
+               else $rows = 3;
+               
+               if (isset($HTTP_VARS['SMALLER'])) {
+                       $rows /= 2;
+                       if ($rows < 3) $rows = 3;
+                       $HTTP_SESSION_VARS['phplens_sqlrows'] = $rows;
+               }
+               if (isset($HTTP_VARS['BIGGER'])) {
+                       $rows *= 2;
+                       $HTTP_SESSION_VARS['phplens_sqlrows'] = $rows;
+               }
+               
+?>
+
+<form method="POST" action="<?php echo $PHP_SELF ?>">
+<table><tr>
+<td> Form size: <input type="submit" value=" &lt; " name="SMALLER"><input type="submit" value=" &gt; &gt; " name="BIGGER">
+</td>
+<td align=right>
+<input type="submit" value=" Run SQL Below " name="RUN"><input type=hidden name=do value=dosql>
+</td></tr>
+  <tr>
+  <td colspan=2><textarea rows=<?php print $rows; ?> name="sql" cols="80"><?php print htmlspecialchars($sql) ?></textarea>
+  </td>
+  </tr>
+ </table>
+</form>
+
+<?php
+               if (!isset($HTTP_VARS['sql'])) return;
+               
+               $sql = $this->undomq(trim($sql));
+               if (substr($sql,strlen($sql)-1) === ';') {
+                       $print = true;
+                       $sqla = $this->SplitSQL($sql);
+               } else  {
+                       $print = false;
+                       $sqla = array($sql);
+               }
+               foreach($sqla as $sqls) {
+
+                       if (!$sqls) continue;
+                       
+                       if ($print) {
+                               print "<p>".htmlspecialchars($sqls)."</p>";
+                               flush();
+                       }
+                       $savelog = $this->conn->LogSQL(false);
+                       $rs = $this->conn->Execute($sqls);
+                       $this->conn->LogSQL($savelog);
+                       if ($rs && is_object($rs) && !$rs->EOF) {
+                               rs2html($rs);
+                               while ($rs->NextRecordSet()) {
+                                       print "<table width=98% bgcolor=#C0C0FF><tr><td>&nbsp;</td></tr></table>";
+                                       rs2html($rs);
+                               }
+                       } else {
+                               $e1 = (integer) $this->conn->ErrorNo();
+                               $e2 = $this->conn->ErrorMsg();
+                               if (($e1) || ($e2)) {
+                                       if (empty($e1)) $e1 = '-1'; // postgresql fix
+                                       print ' &nbsp; '.$e1.': '.$e2;
+                               } else {
+                                       print "<p>No Recordset returned<br></p>";
+                               }
+                       }
+               } // foreach
+       }
+       
+       function SplitSQL($sql)
+       {
+               $arr = explode(';',$sql);
+               return $arr;
+       }
+       
+       function undomq(&$m) 
+       {
+       if (get_magic_quotes_gpc()) {
+               // undo the damage
+               $m = str_replace('\\\\','\\',$m);
+               $m = str_replace('\"','"',$m);
+               $m = str_replace('\\\'','\'',$m);
+       }
+       return $m;
+}
+}
+
+
+
 ?>
\ No newline at end of file
index ef2f55e393fd855e741afc371a4270a5f1d84631..766f00683e914bda03ba0d9a0f6cea9f04e93cf3 100644 (file)
@@ -1,16 +1,16 @@
-<?php\r
-\r
-/*\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  \r
-  Set tabs to 4.\r
-*/\r
-\r
-\r
-class ADODB_BASE_RS {\r
-}\r
-\r
+<?php
+
+/*
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  
+  Set tabs to 4.
+*/
+
+
+class ADODB_BASE_RS {
+}
+
 ?>
\ No newline at end of file
index e86b62b23f455e82ae12a3fa910eb6385d148370..9c9932afa796cad8a607e21577c8367773a81292 100644 (file)
-<?PHP\r
-// Copyright (c) 2003 ars Cognita Inc., all rights reserved\r
+<?php\r
+// Copyright (c) 2004 ars Cognita Inc., all rights reserved\r
 /* ******************************************************************************\r
     Released under both BSD license and Lesser GPL library license. \r
        Whenever there is any discrepancy between the two licenses, \r
        the BSD license will take precedence. \r
+       \r
+Redistribution and use in source and binary forms, with or without modification,\r
+are permitted provided that the following conditions are met:\r
+\r
+Redistributions of source code must retain the above copyright notice, this list\r
+ of conditions and the following disclaimer.\r
+Redistributions in binary form must reproduce the above copyright notice, this l\r
+ist of conditions and the following disclaimer in the documentation and/or other\r
+ materials provided with the distribution.\r
+Neither the name of the ars Cognita, Inc.,  nor the names of its contributors may be used \r
+to endorse or promote products derived from this software without specific prior\r
+written permission.\r
+\r
+DISCLAIMER:\r
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND\r
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WA\r
+RRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\r
+ IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIREC\r
+T, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR P\r
+ROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\r
+ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWI\r
+SE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE P\r
+OSSIBILITY OF SUCH DAMAGE.\r
+\r
 *******************************************************************************/\r
 /**\r
  * xmlschema is a class that allows the user to quickly and easily\r
  * build a database on any ADOdb-supported platform using a simple\r
  * XML schema.\r
  *\r
- * @author Richard Tango-Lowy\r
+ * Last Editor: $Author$\r
+ * @author Richard Tango-Lowy & Dan Cech\r
  * @version $Revision$\r
+ *\r
+ * @package axmls\r
+ * @tutorial getting_started.pkg\r
  */\r
\r
+\r
 /**\r
 * Debug on or off\r
 */\r
- if (!defined('XMLS_DEBUG')) define( 'XMLS_DEBUG', FALSE );\r
\r
+if( !defined( 'XMLS_DEBUG' ) ) {\r
+       define( 'XMLS_DEBUG', FALSE );\r
+}\r
+\r
 /**\r
-* Include the main ADODB library\r
+* Default prefix key\r
 */\r
-if (!defined( '_ADODB_LAYER' ) ) {\r
-       require( dirname(__FILE__) . '/adodb.inc.php' );\r
+if( !defined( 'XMLS_PREFIX' ) ) {\r
+       define( 'XMLS_PREFIX', '%%P' );\r
 }\r
 \r
 /**\r
 * Maximum length allowed for object prefix\r
-*\r
-* @access private\r
 */\r
-define( 'XMLS_PREFIX_MAXLEN', 10 );\r
+if( !defined( 'XMLS_PREFIX_MAXLEN' ) ) {\r
+       define( 'XMLS_PREFIX_MAXLEN', 10 );\r
+}\r
 \r
+/**\r
+* Execute SQL inline as it is generated\r
+*/\r
+if( !defined( 'XMLS_EXECUTE_INLINE' ) ) {\r
+       define( 'XMLS_EXECUTE_INLINE', FALSE );\r
+}\r
 \r
 /**\r
- * Creates a table object in ADOdb's datadict format\r
- *\r
- * This class stores information about a database table. As charactaristics\r
- * of the table are loaded from the external source, methods and properties\r
- * of this class are used to build up the table description in ADOdb's\r
-*  datadict format.\r
- *\r
- * @access private\r
- */\r
-class dbTable {\r
+* Continue SQL Execution if an error occurs?\r
+*/\r
+if( !defined( 'XMLS_CONTINUE_ON_ERROR' ) ) {\r
+       define( 'XMLS_CONTINUE_ON_ERROR', FALSE );\r
+}\r
+\r
+/**\r
+* Current Schema Version\r
+*/\r
+if( !defined( 'XMLS_SCHEMA_VERSION' ) ) {\r
+       define( 'XMLS_SCHEMA_VERSION', '0.2' );\r
+}\r
+\r
+/**\r
+* Default Schema Version.  Used for Schemas without an explicit version set.\r
+*/\r
+if( !defined( 'XMLS_DEFAULT_SCHEMA_VERSION' ) ) {\r
+       define( 'XMLS_DEFAULT_SCHEMA_VERSION', '0.1' );\r
+}\r
+\r
+/**\r
+* Default Schema Version.  Used for Schemas without an explicit version set.\r
+*/\r
+if( !defined( 'XMLS_DEFAULT_UPGRADE_METHOD' ) ) {\r
+       define( 'XMLS_DEFAULT_UPGRADE_METHOD', 'ALTER' );\r
+}\r
+\r
+/**\r
+* Include the main ADODB library\r
+*/\r
+if( !defined( '_ADODB_LAYER' ) ) {\r
+       require( 'adodb.inc.php' );\r
+}\r
+\r
+/**\r
+* Abstract DB Object. This class provides basic methods for database objects, such\r
+* as tables and indexes.\r
+*\r
+* @package axmls\r
+* @access private\r
+*/\r
+class dbObject {\r
        \r
        /**\r
-       * @var string   Table name\r
+       * var object Parent\r
        */\r
-       var $tableName;\r
+       var $parent;\r
        \r
        /**\r
-       * @var array    Field specifier: Meta-information about each field\r
+       * var string current element\r
        */\r
-       var $fieldSpec;\r
+       var $currentElement;\r
        \r
        /**\r
-       * @var array    Table options: Table-level options\r
+       * NOP\r
        */\r
-       var $tableOpts;\r
+       function dbObject( &$parent, $attributes = NULL ) {\r
+               $this->parent =& $parent;\r
+       }\r
        \r
        /**\r
-       * @var string   Field index: Keeps track of which field is currently being processed\r
+       * XML Callback to process start elements\r
+       *\r
+       * @access private\r
        */\r
-       var $currentField;\r
+       function _tag_open( &$parser, $tag, $attributes ) {\r
+               \r
+       }\r
        \r
        /**\r
-       * @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database\r
+       * XML Callback to process CDATA elements\r
+       *\r
        * @access private\r
        */\r
-       var $upgrade;\r
+       function _tag_cdata( &$parser, $cdata ) {\r
+               \r
+       }\r
        \r
        /**\r
-       * @var array Array of legacy metadata. Used for REPLACE upgrades.\r
+       * XML Callback to process end elements\r
+       *\r
        * @access private\r
        */\r
-       var $legacyFieldMetadata;\r
+       function _tag_close( &$parser, $tag ) {\r
+               \r
+       }\r
+       \r
+       function create() {\r
+               return array();\r
+       }\r
+       \r
+       /**\r
+       * Destroys the object\r
+       */\r
+       function destroy() {\r
+               unset( $this );\r
+       }\r
+       \r
+       /**\r
+       * Checks whether the specified RDBMS is supported by the current\r
+       * database object or its ranking ancestor.\r
+       *\r
+       * @param string $platform RDBMS platform name (from ADODB platform list).\r
+       * @return boolean TRUE if RDBMS is supported; otherwise returns FALSE.\r
+       */\r
+       function supportedPlatform( $platform = NULL ) {\r
+               return is_object( $this->parent ) ? $this->parent->supportedPlatform( $platform ) : TRUE;\r
+       }\r
+       \r
+       /**\r
+       * Returns the prefix set by the ranking ancestor of the database object.\r
+       *\r
+       * @param string $name Prefix string.\r
+       * @return string Prefix.\r
+       */\r
+       function prefix( $name = '' ) {\r
+               return is_object( $this->parent ) ? $this->parent->prefix( $name ) : $name;\r
+       }\r
+       \r
+       /**\r
+       * Extracts a field ID from the specified field.\r
+       *\r
+       * @param string $field Field.\r
+       * @return string Field ID.\r
+       */\r
+       function FieldID( $field ) {\r
+               return strtoupper( preg_replace( '/^`(.+)`$/', '$1', $field ) );\r
+       }\r
+}\r
+\r
+/**\r
+* Creates a table object in ADOdb's datadict format\r
+*\r
+* This class stores information about a database table. As charactaristics\r
+* of the table are loaded from the external source, methods and properties\r
+* of this class are used to build up the table description in ADOdb's\r
+* datadict format.\r
+*\r
+* @package axmls\r
+* @access private\r
+*/\r
+class dbTable extends dbObject {\r
+       \r
+       /**\r
+       * @var string Table name\r
+       */\r
+       var $name;\r
+       \r
+       /**\r
+       * @var array Field specifier: Meta-information about each field\r
+       */\r
+       var $fields = array();\r
+       \r
+       /**\r
+       * @var array List of table indexes.\r
+       */\r
+       var $indexes = array();\r
+       \r
+       /**\r
+       * @var array Table options: Table-level options\r
+       */\r
+       var $opts = array();\r
+       \r
+       /**\r
+       * @var string Field index: Keeps track of which field is currently being processed\r
+       */\r
+       var $current_field;\r
        \r
        /**\r
        * @var boolean Mark table for destruction\r
        * @access private\r
        */\r
-       var $dropTable;\r
+       var $drop_table;\r
        \r
        /**\r
        * @var boolean Mark field for destruction (not yet implemented)\r
        * @access private\r
        */\r
-       var $dropField;\r
+       var $drop_field = array();\r
        \r
        /**\r
-       * Constructor. Iniitializes a new table object.\r
+       * Iniitializes a new table object.\r
        *\r
-       * If the table already exists, there are two methods available to upgrade it.\r
-       * To upgrade an existing table the new schema by ALTERing the table, set the upgradeTable\r
-       * argument to "ALTER."  To force the new table to replace the current table, set the upgradeTable\r
-       * argument to "REPLACE."\r
+       * @param string $prefix DB Object prefix\r
+       * @param array $attributes Array of table attributes.\r
+       */\r
+       function dbTable( &$parent, $attributes = NULL ) {\r
+               $this->parent =& $parent;\r
+               $this->name = $this->prefix($attributes['NAME']);\r
+       }\r
+       \r
+       /**\r
+       * XML Callback to process start elements. Elements currently \r
+       * processed are: INDEX, DROP, FIELD, KEY, NOTNULL, AUTOINCREMENT & DEFAULT. \r
        *\r
-       * @param string $name           Table name\r
-       * @param string $upgradeTable           Upgrade method (NULL, ALTER, or REPLACE)\r
+       * @access private\r
        */\r
-       function dbTable( $name, $upgrade = NULL ) {\r
-               logMsg( "+++dbTable( $name, $upgrade )" );\r
+       function _tag_open( &$parser, $tag, $attributes ) {\r
+               $this->currentElement = strtoupper( $tag );\r
                \r
-               $dbconn = $GLOBALS['AXMLS_DBCONN'];\r
-               $dbdict = $GLOBALS['AXMLS_DBDICT'];\r
-               \r
-               $this->tableName = $name;\r
-\r
-               // If upgrading, set and handle the upgrade method\r
-               if( isset( $upgrade ) ) {\r
-                       $upgrade = strtoupper( $upgrade );\r
-                       \r
-                       switch( $upgrade ) {\r
+               switch( $this->currentElement ) {\r
+                       case 'INDEX':\r
+                               xml_set_object( $parser, $this->addIndex( $attributes ) );\r
+                               break;\r
+                       case 'DROP':\r
+                               $this->drop();\r
+                               break;\r
+                       case 'FIELD':\r
+                               // Add a field\r
+                               $fieldName = $attributes['NAME'];\r
+                               $fieldType = $attributes['TYPE'];\r
+                               $fieldSize = isset( $attributes['SIZE'] ) ? $attributes['SIZE'] : NULL;\r
+                               $fieldOpts = isset( $attributes['OPTS'] ) ? $attributes['OPTS'] : NULL;\r
                                \r
-                               case "ALTER":\r
-                                       $this->upgrade = strtoupper( $upgrade );\r
-                                       logMsg( "Upgrading table '$name' using {$this->upgrade}" );\r
-                                       break;\r
-                                       \r
-                               case "REPLACE":\r
-                                       $this->upgrade = strtoupper( $upgrade );\r
-                                       logMsg( "Upgrading table '$name' using {$this->upgrade}" );\r
-                                       \r
-                                       // Need to fetch column names, run them through the case handler (for MySQL),\r
-                                       // create the new column, migrate the data, then drop the old column.\r
-                                       $this->legacyFieldMetadata = $dbconn->MetaColumns( $name );\r
-                                       logMsg( $this->legacyFieldMetadata, "Legacy Metadata" );\r
-                                       break;\r
-                                       \r
-                               default:\r
-                                       unset( $this->upgrade );\r
-                                       break;\r
-                       }\r
-                       \r
-               } else {\r
-                       logMsg( "Creating table '$name'" );\r
+                               $this->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );\r
+                               break;\r
+                       case 'KEY':     \r
+                       case 'NOTNULL':\r
+                       case 'AUTOINCREMENT':\r
+                               // Add a field option\r
+                               $this->addFieldOpt( $this->current_field, $this->currentElement );\r
+                               break;\r
+                       case 'DEFAULT':\r
+                               // Add a field option to the table object\r
+                               \r
+                               // Work around ADOdb datadict issue that misinterprets empty strings.\r
+                               if( $attributes['VALUE'] == '' ) {\r
+                                       $attributes['VALUE'] = " '' ";\r
+                               }\r
+                               \r
+                               $this->addFieldOpt( $this->current_field, $this->currentElement, $attributes['VALUE'] );\r
+                               break;\r
+                       default:\r
+                               // print_r( array( $tag, $attributes ) );\r
+               }\r
+       }\r
+       \r
+       /**\r
+       * XML Callback to process CDATA elements\r
+       *\r
+       * @access private\r
+       */\r
+       function _tag_cdata( &$parser, $cdata ) {\r
+               switch( $this->currentElement ) {\r
+                       // Table constraint\r
+                       case 'CONSTRAINT':\r
+                       // Table option\r
+                       case 'OPT':\r
+                               $this->addTableOpt( $cdata );\r
+                               break;\r
+                       default:\r
+                               \r
+               }\r
+       }\r
+       \r
+       /**\r
+       * XML Callback to process end elements\r
+       *\r
+       * @access private\r
+       */\r
+       function _tag_close( &$parser, $tag ) {\r
+               $this->currentElement = '';\r
+               \r
+               switch( strtoupper( $tag ) ) {\r
+                       case 'TABLE':\r
+                               $this->parent->addSQL( $this->create( $this->parent ) );\r
+                               xml_set_object( $parser, $this->parent );\r
+                               $this->destroy();\r
+                               break;\r
                }\r
-               logMsg( "   ---dbTable" );\r
+       }\r
+       \r
+       /**\r
+       * Adds an index to a table object\r
+       *\r
+       * @param array $attributes Index attributes\r
+       * @return object dbIndex object\r
+       */\r
+       function &addIndex( $attributes ) {\r
+               $name = strtoupper( $attributes['NAME'] );\r
+               $this->indexes[$name] =& new dbIndex( $this, $attributes );\r
+               return $this->indexes[$name];\r
        }\r
        \r
        /**\r
@@ -164,31 +379,33 @@ class dbTable {
        *       - F:  Floating point number\r
        *       - N:  Numeric or decimal number\r
        *\r
-       * @param string $name   Name of the table to which the field will be added.\r
-       * @param string $type           ADODB datadict field type.\r
-       * @param string $size           Field size\r
-       * @param array $opts            Field options array\r
-       * @return array Field specifier array\r
+       * @param string $name Name of the table to which the field will be added.\r
+       * @param string $type   ADODB datadict field type.\r
+       * @param string $size   Field size\r
+       * @param array $opts    Field options array\r
+       * @return array Field specifier array\r
        */\r
        function addField( $name, $type, $size = NULL, $opts = NULL ) {\r
-               logMsg( "   +++addField( $name, $type, $size, $opts )" );\r
+               $field_id = $this->FieldID( $name );\r
+               \r
                // Set the field index so we know where we are\r
-               $this->currentField = $name;\r
+               $this->current_field = $field_id;\r
+               \r
+               // Set the field name (required)\r
+               $this->fields[$field_id]['NAME'] = $name;\r
                \r
                // Set the field type (required)\r
-               $this->fieldSpec[$name]['TYPE'] = $type;\r
+               $this->fields[$field_id]['TYPE'] = $type;\r
                \r
                // Set the field size (optional)\r
                if( isset( $size ) ) {\r
-                       $this->fieldSpec[$name]['SIZE'] = $size;\r
+                       $this->fields[$field_id]['SIZE'] = $size;\r
                }\r
                \r
                // Set the field options\r
-               if( isset( $opts ) ) $this->fieldSpec[$name]['OPTS'] = $opts;\r
-               \r
-               // Return array containing field specifier\r
-               logMsg( "   ---addField" );\r
-               return $this->fieldSpec;\r
+               if( isset( $opts ) ) {\r
+                       $this->fields[$field_id]['OPTS'] = $opts;\r
+               }\r
        }\r
        \r
        /**\r
@@ -197,181 +414,158 @@ class dbTable {
        * This method adds a field option allowed by the ADOdb datadict \r
        * and appends it to the given field.\r
        *\r
-       * @param string $field          Field name\r
-       * @param string $opt            ADOdb field option\r
-       * @param mixed $value   Field option value\r
-       * @return array Field specifier array\r
+       * @param string $field  Field name\r
+       * @param string $opt ADOdb field option\r
+       * @param mixed $value Field option value\r
+       * @return array Field specifier array\r
        */\r
        function addFieldOpt( $field, $opt, $value = NULL ) {\r
-               logMsg( "   +++addFieldOpt( $field, $opt, $value )" );\r
-               \r
-               // Add the option to the field specifier\r
-               if(  $value === NULL ) { // No value, so add only the option\r
-                       $this->fieldSpec[$field]['OPTS'][] = $opt;\r
-               } else { // Add the option and value\r
-                       $this->fieldSpec[$field]['OPTS'][] = array( "$opt" => "$value" );\r
+               if( !isset( $value ) ) {\r
+                       $this->fields[$this->FieldID( $field )]['OPTS'][] = $opt;\r
+               // Add the option and value\r
+               } else {\r
+                       $this->fields[$this->FieldID( $field )]['OPTS'][] = array( $opt => $value );\r
                }\r
-       \r
-               // Return array containing field specifier\r
-               logMsg( "   ---addFieldOpt( $field )" );\r
-               return $this->fieldSpec;\r
        }\r
        \r
        /**\r
        * Adds an option to the table\r
        *\r
-       *This method takes a comma-separated list of table-level options\r
+       * This method takes a comma-separated list of table-level options\r
        * and appends them to the table object.\r
        *\r
-       * @param string $opt            Table option\r
-       * @return string        Option list\r
+       * @param string $opt Table option\r
+       * @return array Options\r
        */\r
        function addTableOpt( $opt ) {\r
-               logMsg( "   +++addTableOpt( $opt )" );\r
+               $this->opts[] = $opt;\r
                \r
-               $optlist = &$this->tableOpts;\r
-               $optlist ? ( $optlist .= ", $opt" ) : ($optlist = $opt );\r
-               \r
-               // Return the options list\r
-               logMsg( "   ---addTableOpt( $opt )" );\r
-               return $optlist;\r
+               return $this->opts;\r
        }\r
        \r
        /**\r
        * Generates the SQL that will create the table in the database\r
        *\r
-       * Returns SQL that will create the table represented by the object.\r
-       *\r
-       * @param object $dict           ADOdb data dictionary\r
-       * @return array Array containing table creation SQL\r
+       * @param object $xmls adoSchema object\r
+       * @return array Array containing table creation SQL\r
        */\r
-       function create( $dict ) {\r
-               logMsg( "   +++<b>create</b>( $dict )" );\r
-       \r
-               // Drop the table\r
-               if( $this->dropTable ) {\r
-                       $sqlArray[] = "DROP TABLE {$this->tableName}";\r
-                       return $sqlArray;\r
+       function create( &$xmls ) {\r
+               $sql = array();\r
+               \r
+               // drop any existing indexes\r
+               if( is_array( $legacy_indexes = $xmls->dict->MetaIndexes( $this->name ) ) ) {\r
+                       foreach( $legacy_indexes as $index => $index_details ) {\r
+                               $sql[] = $xmls->dict->DropIndexSQL( $index, $this->name );\r
+                       }\r
+               }\r
+               \r
+               // remove fields to be dropped from table object\r
+               foreach( $this->drop_field as $field ) {\r
+                       unset( $this->fields[$field] );\r
+               }\r
+               \r
+               // if table exists\r
+               if( is_array( $legacy_fields = $xmls->dict->MetaColumns( $this->name ) ) ) {\r
+                       // drop table\r
+                       if( $this->drop_table ) {\r
+                               $sql[] = $xmls->dict->DropTableSQL( $this->name );\r
+                               \r
+                               return $sql;\r
+                       }\r
+                       \r
+                       // drop any existing fields not in schema\r
+                       foreach( $legacy_fields as $field_id => $field ) {\r
+                               if( !isset( $this->fields[$field_id] ) ) {\r
+                                       $sql[] = $xmls->dict->DropColumnSQL( $this->name, '`'.$field->name.'`' );\r
+                               }\r
+                       }\r
+               // if table doesn't exist\r
+               } else {\r
+                       if( $this->drop_table ) {\r
+                               return $sql;\r
+                       }\r
+                       \r
+                       $legacy_fields = array();\r
                }\r
                \r
                // Loop through the field specifier array, building the associative array for the field options\r
                $fldarray = array();\r
-               $i = 0;\r
                \r
-               foreach( $this->fieldSpec as $field => $finfo ) {\r
-                       $i++;\r
-                       \r
+               foreach( $this->fields as $field_id => $finfo ) {\r
                        // Set an empty size if it isn't supplied\r
-                       if( !isset( $finfo['SIZE'] ) ) $finfo['SIZE'] = '';\r
+                       if( !isset( $finfo['SIZE'] ) ) {\r
+                               $finfo['SIZE'] = '';\r
+                       }\r
                        \r
                        // Initialize the field array with the type and size\r
-                       $fldarray[$i] = array( $field, $finfo['TYPE'], $finfo['SIZE'] );\r
+                       $fldarray[$field_id] = array(\r
+                               'NAME' => $finfo['NAME'],\r
+                               'TYPE' => $finfo['TYPE'],\r
+                               'SIZE' => $finfo['SIZE']\r
+                       );\r
                        \r
                        // Loop through the options array and add the field options. \r
                        if( isset( $finfo['OPTS'] ) ) {\r
                                foreach( $finfo['OPTS'] as $opt ) {\r
-                                       \r
-                                       if( is_array( $opt ) ) { // Option has an argument.\r
+                                       // Option has an argument.\r
+                                       if( is_array( $opt ) ) {\r
                                                $key = key( $opt );\r
-                                               $value = $opt[key( $opt ) ];\r
-                                               $fldarray[$i][$key] = $value;\r
-                                               \r
-                                       } else { // Option doesn't have arguments\r
-                                               array_push( $fldarray[$i], $opt );\r
+                                               $value = $opt[key( $opt )];\r
+                                               $fldarray[$field_id][$key] = $value;\r
+                                       // Option doesn't have arguments\r
+                                       } else {\r
+                                               $fldarray[$field_id][$opt] = $opt;\r
                                        }\r
                                }\r
                        }\r
                }\r
                \r
-               // Check for existing table\r
-               $legacyTables = $dict->MetaTables();\r
-               if( is_array( $legacyTables ) and count( $legacyTables > 0 ) ) {\r
-                       foreach( $dict->MetaTables() as $table ) {\r
-                               $this->legacyTables[ strtoupper( $table ) ] = $table;\r
-                       }\r
-                       if( isset( $this->legacyTables ) and is_array( $this->legacyTables ) and count( $this->legacyTables > 0 ) ) {\r
-                               if( array_key_exists( strtoupper( $this->tableName ), $this->legacyTables ) ) {\r
-                                       $existingTableName = $this->legacyTables[strtoupper( $this->tableName )];\r
-                                       logMsg( "Upgrading $existingTableName using '{$this->upgrade}'" );\r
-                               }\r
-                       }\r
-               }       \r
-               \r
-               // Build table array\r
-               if( !isset( $this->upgrade ) or !isset( $existingTableName ) ) {\r
-                       \r
+               if( empty( $legacy_fields ) ) {\r
                        // Create the new table\r
-                       $sqlArray = $dict->CreateTableSQL( $this->tableName, $fldarray, $this->tableOpts );\r
-                       logMsg( $sqlArray, "Generated CreateTableSQL" );\r
-                       \r
+                       $sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );\r
+                       logMsg( end( $sql ), 'Generated CreateTableSQL' );\r
                } else {\r
-                       \r
                        // Upgrade an existing table\r
-                       switch( $this->upgrade ) {\r
-                               \r
+                       logMsg( "Upgrading {$this->name} using '{$xmls->upgrade}'" );\r
+                       switch( $xmls->upgrade ) {\r
+                               // Use ChangeTableSQL\r
                                case 'ALTER':\r
-                                       // Use ChangeTableSQL\r
-                                       $sqlArray = $dict->ChangeTableSQL( $this->tableName, $fldarray, $this->tableOpts );\r
-                                       logMsg( $sqlArray, "Generated ChangeTableSQL (ALTERing table)" );\r
+                                       logMsg( 'Generated ChangeTableSQL (ALTERing table)' );\r
+                                       $sql[] = $xmls->dict->ChangeTableSQL( $this->name, $fldarray, $this->opts );\r
                                        break;\r
-                                       \r
                                case 'REPLACE':\r
-                                       logMsg( "Doing upgrade REPLACE (testing)" );\r
-                                       $sqlArray = $dict->ChangeTableSQL( $this->tableName, $fldarray, $this->tableOpts );\r
-                                       $this->replace( $dict );\r
+                                       logMsg( 'Doing upgrade REPLACE (testing)' );\r
+                                       $sql[] = $xmls->dict->DropTableSQL( $this->name );\r
+                                       $sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts );\r
                                        break;\r
-                                       \r
+                               // ignore table\r
                                default:\r
+                                       return array();\r
                        }\r
                }\r
                \r
-               // Return the array containing the SQL to create the table\r
-               logMsg( "   ---create" );\r
-               return $sqlArray;\r
+               foreach( $this->indexes as $index ) {\r
+                       $sql[] = $index->create( $xmls );\r
+               }\r
+               \r
+               return $sql;\r
        }\r
        \r
        /**\r
-       * Generates the SQL that will drop the table or field from the database\r
-       *\r
-       * @param object $dict           ADOdb data dictionary\r
-       * @return array Array containing table creation SQL\r
+       * Marks a field or table for destruction\r
        */\r
-       function drop( $dict ) {\r
-               if( isset( $this->currentField ) ) {\r
+       function drop() {\r
+               if( isset( $this->current_field ) ) {\r
                        // Drop the current field\r
-                       logMsg( "Dropping field '{$this->currentField}' from table '{$this->tableName}'" );\r
-                       $this->dropField = TRUE;\r
-                       $sqlArray = $dict->DropColumnSQL( $this->tableName, $this->currentField );\r
+                       logMsg( "Dropping field '{$this->current_field}' from table '{$this->name}'" );\r
+                       // $this->drop_field[$this->current_field] = $xmls->dict->DropColumnSQL( $this->name, $this->current_field );\r
+                       $this->drop_field[$this->current_field] = $this->current_field;\r
                } else {\r
                        // Drop the current table\r
-                       logMsg( "Dropping table '{$this->tableName}'" );\r
-                       $this->dropTable = TRUE;\r
-                       $sqlArray = false;\r
+                       logMsg( "Dropping table '{$this->name}'" );\r
+                       // $this->drop_table = $xmls->dict->DropTableSQL( $this->name );\r
+                       $this->drop_table = TRUE;\r
                }\r
-               return $sqlArray; \r
-       }\r
-       \r
-       /**\r
-       * Generates the SQL that will replace an existing table in the database\r
-       *\r
-       * Returns SQL that will replace the table represented by the object.\r
-       *\r
-       * @return array Array containing table replacement SQL\r
-       */\r
-       function replace( $dict ) {\r
-               logMsg( "   +++replace( $dict )" );\r
-               \r
-               // Identify new columns\r
-               \r
-               logMsg( "   ---replace)" );\r
-       }\r
-       \r
-       /**\r
-       * Destructor\r
-       */\r
-       function destroy() {\r
-               logMsg( "===destroy" );\r
-               unset( $this );\r
        }\r
 }\r
 \r
@@ -383,180 +577,174 @@ class dbTable {
 * of this class are used to build up the index description in ADOdb's\r
 * datadict format.\r
 *\r
+* @package axmls\r
 * @access private\r
 */\r
-class dbIndex {\r
+class dbIndex extends dbObject {\r
        \r
        /**\r
        * @var string   Index name\r
        */\r
-       var $indexName;\r
+       var $name;\r
        \r
        /**\r
        * @var array    Index options: Index-level options\r
        */\r
-       var $indexOpts;\r
-\r
-       /**\r
-       * @var string   Name of the table this index is attached to\r
-       */\r
-       var $tableName;\r
+       var $opts = array();\r
        \r
        /**\r
        * @var array    Indexed fields: Table columns included in this index\r
        */\r
-       var $fields;\r
+       var $columns = array();\r
        \r
        /**\r
-       * @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database\r
+       * @var boolean Mark index for destruction\r
        * @access private\r
        */\r
-       var $upgrade;\r
+       var $drop = FALSE;\r
        \r
        /**\r
-       * @var boolean Mark index for destruction\r
+       * Initializes the new dbIndex object.\r
+       *\r
+       * @param object $parent Parent object\r
+       * @param array $attributes Attributes\r
+       *\r
+       * @internal\r
+       */\r
+       function dbIndex( &$parent, $attributes = NULL ) {\r
+               $this->parent =& $parent;\r
+               \r
+               $this->name = $this->prefix ($attributes['NAME']);\r
+       }\r
+       \r
+       /**\r
+       * XML Callback to process start elements\r
+       *\r
+       * Processes XML opening tags. \r
+       * Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH. \r
+       *\r
        * @access private\r
        */\r
-       var $dropIndex;\r
+       function _tag_open( &$parser, $tag, $attributes ) {\r
+               $this->currentElement = strtoupper( $tag );\r
+               \r
+               switch( $this->currentElement ) {\r
+                       case 'DROP':\r
+                               $this->drop();\r
+                               break;\r
+                       case 'CLUSTERED':\r
+                       case 'BITMAP':\r
+                       case 'UNIQUE':\r
+                       case 'FULLTEXT':\r
+                       case 'HASH':\r
+                               // Add index Option\r
+                               $this->addIndexOpt( $this->currentElement );\r
+                               break;\r
+                       default:\r
+                               // print_r( array( $tag, $attributes ) );\r
+               }\r
+       }\r
        \r
        /**\r
-       * Constructor. Initialize the index and table names.\r
+       * XML Callback to process CDATA elements\r
+       *\r
+       * Processes XML cdata.\r
        *\r
-       * If the upgrade argument is set to ALTER or REPLACE, axmls will attempt to drop the index\r
-       * before and replace it with the new one.\r
+       * @access private\r
+       */\r
+       function _tag_cdata( &$parser, $cdata ) {\r
+               switch( $this->currentElement ) {\r
+                       // Index field name\r
+                       case 'COL':\r
+                               $this->addField( $cdata );\r
+                               break;\r
+                       default:\r
+                               \r
+               }\r
+       }\r
+       \r
+       /**\r
+       * XML Callback to process end elements\r
        *\r
-       * @param string $name   Index name\r
-       * @param string $table          Name of indexed table\r
-       * @param string $upgrade                Upgrade method (NULL, ALTER, or REPLACE)\r
+       * @access private\r
        */\r
-       function dbIndex( $name, $table, $upgrade = NULL ) {\r
-               logMsg( "===dbIndex( $name, $table )" );\r
-               $this->indexName = $name;\r
-               $this->tableName = $table;\r
-               $this->dropIndex = FALSE;\r
+       function _tag_close( &$parser, $tag ) {\r
+               $this->currentElement = '';\r
                \r
-               // If upgrading, set the upgrade method\r
-               if( isset( $upgrade ) ) {\r
-                       $upgrade = strtoupper( $upgrade );\r
-                       if( $upgrade == 'ALTER' or $upgrade == 'REPLACE' ) {\r
-                               $this->upgrade = strtoupper( $upgrade );\r
-                               // Drop the old index\r
-                               logMsg( "Dropping old index '$name' using {$this->upgrade}" );\r
-                       } else {\r
-                               unset( $this->upgrade );\r
-                       }\r
-                       \r
-               } else {\r
-                       logMsg( "Creating index '$name'" );\r
+               switch( strtoupper( $tag ) ) {\r
+                       case 'INDEX':\r
+                               xml_set_object( $parser, $this->parent );\r
+                               break;\r
                }\r
        }\r
        \r
        /**\r
        * Adds a field to the index\r
-       * \r
-       * This method adds the specified column to an index.\r
        *\r
-       * @param string $name           Field name\r
-       * @return string        Field list\r
+       * @param string $name Field name\r
+       * @return string Field list\r
        */\r
        function addField( $name ) {\r
-               logMsg( "   +++addField( $name )" );\r
-               \r
-               $fieldlist = &$this->fields;\r
-               $fieldlist ? ( $fieldlist .=" , $name" ) : ( $fieldlist = $name );\r
+               $this->columns[$this->FieldID( $name )] = $name;\r
                \r
                // Return the field list\r
-               logMsg( "   ---addField" );\r
-               return $fieldlist;\r
+               return $this->columns;\r
        }\r
        \r
        /**\r
-       * Adds an option to the index\r
+       * Adds options to the index\r
        *\r
-       *This method takes a comma-separated list of index-level options\r
-       * and appends them to the index object.\r
-       *\r
-       * @param string $opt            Index option\r
-       * @return string        Option list\r
+       * @param string $opt Comma-separated list of index options.\r
+       * @return string Option list\r
        */\r
        function addIndexOpt( $opt ) {\r
-               logMsg( "   +++addIndexOpt( $opt )" );\r
-               $optlist = &$this->indexOpts;\r
-               $optlist ? ( $optlist .= ", $opt" ) : ( $optlist = $opt );\r
-\r
+               $this->opts[] = $opt;\r
+               \r
                // Return the options list\r
-               logMsg( "   ---addIndexOpt" );\r
-               return $optlist;\r
+               return $this->opts;\r
        }\r
-\r
+       \r
        /**\r
        * Generates the SQL that will create the index in the database\r
        *\r
-       * Returns SQL that will create the index represented by the object.\r
-       *\r
-       * @param object $dict   ADOdb data dictionary object\r
-       * @return array Array containing index creation SQL\r
+       * @param object $xmls adoSchema object\r
+       * @return array Array containing index creation SQL\r
        */\r
-       function create( $dict ) {\r
-               logMsg( "   +++create( $dict )" );\r
-               \r
-               // Drop the index\r
-               if( $this->dropIndex == TRUE ) {\r
-                       $sqlArray = array( "DROP INDEX {$this->indexName}" );\r
-                       return $sqlArray; \r
+       function create( &$xmls ) {\r
+               if( $this->drop ) {\r
+                       return NULL;\r
                }\r
                \r
-               if (isset($this->indexOpts) ) {\r
-                       // CreateIndexSQL requires an array of options.\r
-                       $indexOpts_arr = explode(",",$this->indexOpts);\r
-               } else {\r
-                       $indexOpts_arr = NULL;\r
-               }\r
-        \r
-               // Build index SQL array\r
-               $sqlArray = $dict->CreateIndexSQL( $this->indexName, $this->tableName, $this->fields, $indexOpts_arr );\r
-               \r
-               // If upgrading, prepend SQL to drop the old index\r
-               if( isset( $this->upgrade ) ) {\r
-                       $dropSql = "DROP INDEX {$this->indexName} ON {$this->tableName}";\r
-                       array_unshift( $sqlArray, $dropSql );\r
+               // eliminate any columns that aren't in the table\r
+               foreach( $this->columns as $id => $col ) {\r
+                       if( !isset( $this->parent->fields[$id] ) ) {\r
+                               unset( $this->columns[$id] );\r
+                       }\r
                }\r
                \r
-               // Return the array containing the SQL to create the table\r
-               logMsg( "   ---create" );\r
-               return $sqlArray;\r
+               return $xmls->dict->CreateIndexSQL( $this->name, $this->parent->name, $this->columns, $this->opts );\r
        }\r
        \r
        /**\r
        * Marks an index for destruction\r
        */\r
        function drop() {\r
-               logMsg( "Marking index '{$this->indexName}' from '{$this->tableName}' for drop" );\r
-               $this->dropIndex = TRUE;\r
-       }\r
-       \r
-       /**\r
-       * Destructor\r
-       */\r
-       function destroy() {\r
-               logMsg( "===destroy" );\r
-               unset( $this );\r
+               $this->drop = TRUE;\r
        }\r
 }\r
 \r
 /**\r
 * Creates the SQL to execute a list of provided SQL queries\r
 *\r
-* This class compiles a list of SQL queries specified in the external file.\r
-*\r
+* @package axmls\r
 * @access private\r
 */\r
-class dbQuerySet {\r
+class dbQuerySet extends dbObject {\r
        \r
        /**\r
        * @var array    List of SQL queries\r
        */\r
-       var $querySet;\r
+       var $queries = array();\r
        \r
        /**\r
        * @var string   String used to build of a query line by line\r
@@ -564,23 +752,153 @@ class dbQuerySet {
        var $query;\r
        \r
        /**\r
-       * Constructor. Initializes the queries array\r
+       * @var string   Query prefix key\r
+       */\r
+       var $prefixKey = '';\r
+       \r
+       /**\r
+       * @var boolean  Auto prefix enable (TRUE)\r
+       */\r
+       var $prefixMethod = 'AUTO';\r
+       \r
+       /**\r
+       * Initializes the query set.\r
+       *\r
+       * @param object $parent Parent object\r
+       * @param array $attributes Attributes\r
+       */\r
+       function dbQuerySet( &$parent, $attributes = NULL ) {\r
+               $this->parent =& $parent;\r
+                       \r
+               // Overrides the manual prefix key\r
+               if( isset( $attributes['KEY'] ) ) {\r
+                       $this->prefixKey = $attributes['KEY'];\r
+               }\r
+               \r
+               $prefixMethod = isset( $attributes['PREFIXMETHOD'] ) ? strtoupper( trim( $attributes['PREFIXMETHOD'] ) ) : '';\r
+               \r
+               // Enables or disables automatic prefix prepending\r
+               switch( $prefixMethod ) {\r
+                       case 'AUTO':\r
+                               $this->prefixMethod = 'AUTO';\r
+                               break;\r
+                       case 'MANUAL':\r
+                               $this->prefixMethod = 'MANUAL';\r
+                               break;\r
+                       case 'NONE':\r
+                               $this->prefixMethod = 'NONE';\r
+                               break;\r
+                       default:\r
+                               $this->prefixMethod = 'AUTO';\r
+               }\r
+       }\r
+       \r
+       /**\r
+       * XML Callback to process start elements. Elements currently \r
+       * processed are: QUERY. \r
+       *\r
+       * @access private\r
+       */\r
+       function _tag_open( &$parser, $tag, $attributes ) {\r
+               $this->currentElement = strtoupper( $tag );\r
+               \r
+               switch( $this->currentElement ) {\r
+                       case 'QUERY':\r
+                               // Create a new query in a SQL queryset.\r
+                               // Ignore this query set if a platform is specified and it's different than the \r
+                               // current connection platform.\r
+                               if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {\r
+                                       $this->newQuery();\r
+                               } else {\r
+                                       $this->discardQuery();\r
+                               }\r
+                               break;\r
+                       default:\r
+                               // print_r( array( $tag, $attributes ) );\r
+               }\r
+       }\r
+       \r
+       /**\r
+       * XML Callback to process CDATA elements\r
+       */\r
+       function _tag_cdata( &$parser, $cdata ) {\r
+               switch( $this->currentElement ) {\r
+                       // Line of queryset SQL data\r
+                       case 'QUERY':\r
+                               $this->buildQuery( $cdata );\r
+                               break;\r
+                       default:\r
+                               \r
+               }\r
+       }\r
+       \r
+       /**\r
+       * XML Callback to process end elements\r
+       *\r
+       * @access private\r
+       */\r
+       function _tag_close( &$parser, $tag ) {\r
+               $this->currentElement = '';\r
+               \r
+               switch( strtoupper( $tag ) ) {\r
+                       case 'QUERY':\r
+                               // Add the finished query to the open query set.\r
+                               $this->addQuery();\r
+                               break;\r
+                       case 'SQL':\r
+                               $this->parent->addSQL( $this->create( $this->parent ) );\r
+                               xml_set_object( $parser, $this->parent );\r
+                               $this->destroy();\r
+                               break;\r
+                       default:\r
+                               \r
+               }\r
+       }\r
+       \r
+       /**\r
+       * Re-initializes the query.\r
+       *\r
+       * @return boolean TRUE\r
        */\r
-       function dbQuerySet() {\r
-               logMsg( "===dbQuerySet" );\r
-               $this->querySet = array();\r
+       function newQuery() {\r
                $this->query = '';\r
+               \r
+               return TRUE;\r
+       }\r
+       \r
+       /**\r
+       * Discards the existing query.\r
+       *\r
+       * @return boolean TRUE\r
+       */\r
+       function discardQuery() {\r
+               unset( $this->query );\r
+               \r
+               return TRUE;\r
        }\r
        \r
        /** \r
        * Appends a line to a query that is being built line by line\r
        *\r
-       * $param string $data   Line of SQL data or NULL to initialize a new query\r
+       * @param string $data Line of SQL data or NULL to initialize a new query\r
+       * @return string SQL query string.\r
        */\r
-       function buildQuery( $data = NULL ) {\r
-               logMsg( "   +++buildQuery( $data )" );\r
-               isset( $data ) ? ( $this->query .= " " . trim( $data ) ) : ( $this->query = '' );\r
-               logMsg( "   ---buildQuery" );\r
+       function buildQuery( $sql = NULL ) {\r
+               if( !isset( $this->query ) ) {\r
+                       return FALSE;\r
+               }\r
+               \r
+               if( empty( $sql ) ) {\r
+                       return FALSE;\r
+               }\r
+               \r
+               if( !empty( $this->query ) ) {\r
+                       $this->query .= ' ';\r
+               }\r
+               \r
+               $this->query .= trim( $sql );\r
+               \r
+               return $this->query;\r
        }\r
        \r
        /**\r
@@ -589,572 +907,926 @@ class dbQuerySet {
        * @return string        SQL of added query\r
        */\r
        function addQuery() {\r
-               logMsg( "   +++addQuery" );\r
+               if( !isset( $this->query ) ) {\r
+                       return FALSE;\r
+               }\r
                \r
-               // Push the query onto the query set array\r
-               $finishedQuery = $this->query;\r
-               array_push( $this->querySet, $finishedQuery );\r
+               $this->queries[] = $this->query;\r
+               $return = $this->query;\r
                \r
-               // Return the query set array\r
-               logMsg( "   ---addQuery" );\r
-               return $finishedQuery;\r
+               unset( $this->query );\r
+               \r
+               return $return;\r
        }\r
        \r
        /**\r
        * Creates and returns the current query set\r
        *\r
+       * @param object $xmls adoSchema object\r
        * @return array Query set\r
        */\r
-       function create() {\r
-               logMsg( "   ===create" );\r
-               return $this->querySet;\r
+       function create( &$xmls ) {\r
+               foreach( $this->queries as $id => $query ) {\r
+                       switch( $this->prefixMethod ) {\r
+                               case 'AUTO':\r
+                                       // Enable auto prefix replacement\r
+                                       \r
+                                       // Process object prefix.\r
+                                       // Evaluate SQL statements to prepend prefix to objects\r
+                                       $query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query );\r
+                                       $query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query );\r
+                                       $query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query );\r
+                                       \r
+                                       // SELECT statements aren't working yet\r
+                                       #$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data );\r
+                                       \r
+                               case 'MANUAL':\r
+                                       // If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX.\r
+                                       // If prefixKey is not set, we use the default constant XMLS_PREFIX\r
+                                       if( isset( $this->prefixKey ) AND( $this->prefixKey !== '' ) ) {\r
+                                               // Enable prefix override\r
+                                               $query = str_replace( $this->prefixKey, $xmls->objectPrefix, $query );\r
+                                       } else {\r
+                                               // Use default replacement\r
+                                               $query = str_replace( XMLS_PREFIX , $xmls->objectPrefix, $query );\r
+                                       }\r
+                       }\r
+                       \r
+                       $this->queries[$id] = trim( $query );\r
+               }\r
+               \r
+               // Return the query set array\r
+               return $this->queries;\r
        }\r
        \r
        /**\r
-       * Destructor\r
+       * Rebuilds the query with the prefix attached to any objects\r
+       *\r
+       * @param string $regex Regex used to add prefix\r
+       * @param string $query SQL query string\r
+       * @param string $prefix Prefix to be appended to tables, indices, etc.\r
+       * @return string Prefixed SQL query string.\r
        */\r
-       function destroy() {\r
-               logMsg( "===destroy" );\r
-               unset( $this );\r
+       function prefixQuery( $regex, $query, $prefix = NULL ) {\r
+               if( !isset( $prefix ) ) {\r
+                       return $query;\r
+               }\r
+               \r
+               if( preg_match( $regex, $query, $match ) ) {\r
+                       $preamble = $match[1];\r
+                       $postamble = $match[5];\r
+                       $objectList = explode( ',', $match[3] );\r
+                       // $prefix = $prefix . '_';\r
+                       \r
+                       $prefixedList = '';\r
+                       \r
+                       foreach( $objectList as $object ) {\r
+                               if( $prefixedList !== '' ) {\r
+                                       $prefixedList .= ', ';\r
+                               }\r
+                               \r
+                               $prefixedList .= $prefix . trim( $object );\r
+                       }\r
+                       \r
+                       $query = $preamble . ' ' . $prefixedList . ' ' . $postamble;\r
+               }\r
+               \r
+               return $query;\r
        }\r
 }\r
 \r
-\r
 /**\r
 * Loads and parses an XML file, creating an array of "ready-to-run" SQL statements\r
 * \r
 * This class is used to load and parse the XML file, to create an array of SQL statements\r
 * that can be used to build a database, and to build the database using the SQL array.\r
 *\r
-* @author Richard Tango-Lowy\r
+* @tutorial getting_started.pkg\r
+*\r
+* @author Richard Tango-Lowy & Dan Cech\r
 * @version $Revision$\r
-* @copyright (c) 2003 ars Cognita, Inc., all rights reserved\r
+*\r
+* @package axmls\r
 */\r
 class adoSchema {\r
        \r
        /**\r
        * @var array    Array containing SQL queries to generate all objects\r
-       */\r
-       var $sqlArray;\r
-       \r
-       /**\r
-       * @var object   XML Parser object\r
        * @access private\r
        */\r
-       var $xmlParser;\r
+       var $sqlArray;\r
        \r
        /**\r
        * @var object   ADOdb connection object\r
        * @access private\r
        */\r
-       var $dbconn;\r
+       var $db;\r
        \r
        /**\r
-       * @var string   Database type (platform)\r
+       * @var object   ADOdb Data Dictionary\r
        * @access private\r
        */\r
-       var $dbType;\r
+       var $dict;\r
        \r
        /**\r
-       * @var object   ADOdb Data Dictionary\r
+       * @var string Current XML element\r
        * @access private\r
        */\r
-       var $dict;\r
+       var $currentElement = '';\r
        \r
        /**\r
-       * @var object   Temporary dbTable object\r
+       * @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database\r
        * @access private\r
        */\r
-       var $table;\r
+       var $upgrade = '';\r
        \r
        /**\r
-       * @var object   Temporary dbIndex object\r
+       * @var string Optional object prefix\r
        * @access private\r
        */\r
-       var $index;\r
+       var $objectPrefix = '';\r
        \r
        /**\r
-       * @var object   Temporary dbQuerySet object\r
+       * @var long     Original Magic Quotes Runtime value\r
        * @access private\r
        */\r
-       var $querySet;\r
+       var $mgq;\r
        \r
        /**\r
-       * @var string Current XML element\r
+       * @var long     System debug\r
        * @access private\r
        */\r
-       var $currentElement;\r
+       var $debug;\r
        \r
        /**\r
-       * @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database\r
+       * @var string Regular expression to find schema version\r
        * @access private\r
        */\r
-       var $upgradeMethod;\r
+       var $versionRegex = '/<schema.*?( version="([^"]*)")?.*?>/';\r
        \r
        /**\r
-       * @var mixed Existing tables before upgrade\r
+       * @var string Current schema version\r
        * @access private\r
        */\r
-       var $legacyTables;\r
+       var $schemaVersion;\r
        \r
        /**\r
-       * @var string Optional object prefix\r
-       * @access private\r
+       * @var int      Success of last Schema execution\r
        */\r
-       var $objectPrefix;\r
+       var $success;\r
        \r
        /**\r
-       * @var long     Original Magic Quotes Runtime value\r
-       * @access private\r
+       * @var bool     Execute SQL inline as it is generated\r
        */\r
-       var $mgq;\r
+       var $executeInline;\r
        \r
        /**\r
-       * @var long     System debug\r
-       * @access private\r
+       * @var bool     Continue SQL execution if errors occur\r
        */\r
-       var $debug;\r
+       var $continueOnError;\r
        \r
        /**\r
-       * Constructor. Initializes the xmlschema object.\r
+       * Creates an adoSchema object\r
        *\r
-       * adoSchema provides methods to parse and process the XML schema file. The dbconn argument \r
-       * is a database connection object created by ADONewConnection. To upgrade an existing database to\r
-       * the provided schema, set the upgradeSchema flag to TRUE. By default, adoSchema will attempt to\r
-       * upgrade tables by ALTERing them on the fly. If your RDBMS doesn't support direct alteration\r
-       * (e.g., PostgreSQL), setting the forceReplace flag to TRUE will replace existing tables rather than\r
-       * altering them, copying data from each column in the old table to the like-named column in the\r
-       * new table.\r
+       * Creating an adoSchema object is the first step in processing an XML schema.\r
+       * The only parameter is an ADOdb database connection object, which must already\r
+       * have been created.\r
        *\r
-       * @param object $dbconn         ADOdb connection object\r
-       * @param object $upgradeSchema  Upgrade the database (deprecated)\r
-       * @param object $forceReplace   If upgrading, REPLACE tables (deprecated)\r
+       * @param object $db ADOdb database connection object.\r
        */\r
-       function adoSchema( $dbconn, $upgradeSchema = FALSE, $forceReplace = FALSE ) {\r
-               logMsg( "+++<b>adoSchema</b>( $dbconn, $upgradeSchema, $forceReplace )" );\r
-               \r
+       function adoSchema( &$db ) {\r
                // Initialize the environment\r
                $this->mgq = get_magic_quotes_runtime();\r
-               set_magic_quotes_runtime(0);    \r
+               set_magic_quotes_runtime(0);\r
                \r
-               $this->dbconn   =  &$dbconn;\r
-               $this->dbType = $dbconn->databaseType;\r
+               $this->debug = $this->db->debug;\r
+               $this->db =& $db;\r
+               $this->dict = NewDataDictionary( $this->db );\r
                $this->sqlArray = array();\r
-               $this->debug = $this->dbconn->debug;\r
-               \r
-               // Create an ADOdb dictionary object\r
-               $this->dict = NewDataDictionary( $dbconn );\r
-       \r
-               $GLOBALS['AXMLS_DBCONN'] = $this->dbconn;\r
-               $GLOBALS['AXMLS_DBDICT'] = $this->dict;\r
-               \r
-               // If upgradeSchema is set, we will be upgrading an existing database to match\r
-               // the provided schema. If forceReplace is set, objects are marked for replacement\r
-               // rather than alteration. Both these options are deprecated in favor of the \r
-               // upgradeSchema method.\r
-               if( $upgradeSchema == TRUE ) {\r
-                       \r
-                       if( $forceReplace == TRUE ) {\r
-                               logMsg( "upgradeSchema option deprecated. Use adoSchema->upgradeSchema('REPLACE') method instead" );\r
-                               $method = 'REPLACE';\r
-                       } else {\r
-                               logMsg( "upgradeSchema option deprecated. Use adoSchema->upgradeSchema() method instead" );\r
-                               $method = 'BEST';\r
-                       }\r
-                       $method = $this->upgradeSchema( $method );\r
-                       logMsg( "Upgrading database using '$method'" );\r
-                       \r
-               } else {\r
-                       logMsg( "Creating new database schema" );\r
-                       unset( $this->upgradeMethod );\r
-               }\r
-               logMsg( "---<b>adoSchema</b>" );\r
+               $this->schemaVersion = XMLS_SCHEMA_VERSION;\r
+               $this->executeInline( XMLS_EXECUTE_INLINE );\r
+               $this->continueOnError( XMLS_CONTINUE_ON_ERROR );\r
+               $this->setUpgradeMethod();\r
        }\r
        \r
        /**\r
-       * Upgrades an existing schema rather than creating a new one\r
+       * Sets the method to be used for upgrading an existing database\r
        *\r
-       * Upgrades an exsiting database to match the provided schema. The method\r
-       * option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to\r
+       * Use this method to specify how existing database objects should be upgraded.\r
+       * The method option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to\r
        * alter each database object directly, REPLACE attempts to rebuild each object\r
        * from scratch, BEST attempts to determine the best upgrade method for each\r
        * object, and NONE disables upgrading.\r
        *\r
+       * This method is not yet used by AXMLS, but exists for backward compatibility.\r
+       * The ALTER method is automatically assumed when the adoSchema object is\r
+       * instantiated; other upgrade methods are not currently supported.\r
+       *\r
        * @param string $method Upgrade method (ALTER|REPLACE|BEST|NONE)\r
        * @returns string Upgrade method used\r
        */\r
-       function upgradeSchema( $method = 'BEST' ) {\r
+       function SetUpgradeMethod( $method = '' ) {\r
+               if( !is_string( $method ) ) {\r
+                       return FALSE;\r
+               }\r
                \r
-               // Get the metadata from existing tables, then map the names back to case-insensitive\r
-               // names (for RDBMS' like MySQL,. that are case specific.)\r
-               $legacyTables = $this->dict->MetaTables();\r
-\r
-               if( is_array( $legacyTables ) and count( $legacyTables > 0 ) ) {\r
-                       foreach( $this->dict->MetaTables() as $table ) {\r
-                               $this->legacyTables[ strtoupper( $table ) ] = $table;\r
-                       }\r
-                       logMsg( $this->legacyTables, "Legacy Tables Map" );\r
-               } \r
+               $method = strtoupper( $method );\r
                \r
                // Handle the upgrade methods\r
-               switch( strtoupper( $method ) ) {\r
-                       \r
+               switch( $method ) {\r
                        case 'ALTER':\r
-                               $this->upgradeMethod = 'ALTER';\r
+                               $this->upgrade = $method;\r
                                break;\r
-                               \r
                        case 'REPLACE':\r
-                               $this->upgradeMethod = 'REPLACE';\r
+                               $this->upgrade = $method;\r
                                break;\r
-                               \r
                        case 'BEST':\r
-                               $this->upgradeMethod = 'ALTER';\r
+                               $this->upgrade = 'ALTER';\r
                                break;\r
-                               \r
                        case 'NONE':\r
-                               $this->upgradeMethod = '';\r
+                               $this->upgrade = 'NONE';\r
                                break;\r
-                               \r
                        default:\r
-                               // Fail out if no legitimate method is passed.\r
-                               return FALSE;\r
+                               // Use default if no legitimate method is passed.\r
+                               $this->upgrade = XMLS_DEFAULT_UPGRADE_METHOD;\r
                }\r
-               return $method;\r
-       }\r
                \r
+               return $this->upgrade;\r
+       }\r
+       \r
        /**\r
-       * Loads and parses an XML file\r
+       * Enables/disables inline SQL execution.\r
+       *\r
+       * Call this method to enable or disable inline execution of the schema. If the mode is set to TRUE (inline execution),\r
+       * AXMLS applies the SQL to the database immediately as each schema entity is parsed. If the mode\r
+       * is set to FALSE (post execution), AXMLS parses the entire schema and you will need to call adoSchema::ExecuteSchema()\r
+       * to apply the schema to the database.\r
        *\r
-       * This method accepts a path to an xmlschema-compliant XML file,\r
-       * loads it, parses it, and uses it to create the SQL to generate the objects\r
-       * described by the XML file.\r
+       * @param bool $mode execute\r
+       * @return bool current execution mode\r
        *\r
-       * @param string $file           XML file\r
-       * @return array Array of SQL queries, ready to execute\r
+       * @see ParseSchema(), ExecuteSchema()\r
        */\r
-       function ParseSchema( $file ) {\r
-               logMsg( "+++ParseSchema( $file )" );\r
-               \r
-               // Create the parser\r
-               $this->xmlParser = &$xmlParser;\r
-               $xmlParser = xml_parser_create();\r
-               xml_set_object( $xmlParser, $this );\r
+       function ExecuteInline( $mode = NULL ) {\r
+               if( is_bool( $mode ) ) {\r
+                       $this->executeInline = $mode;\r
+               }\r
                \r
-               // Initialize the XML callback functions\r
-               xml_set_element_handler( $xmlParser, "_xmlcb_startElement", "_xmlcb_endElement" );\r
-               xml_set_character_data_handler( $xmlParser, "_xmlcb_cData" );\r
+               return $this->executeInline;\r
+       }\r
+       \r
+       /**\r
+       * Enables/disables SQL continue on error.\r
+       *\r
+       * Call this method to enable or disable continuation of SQL execution if an error occurs.\r
+       * If the mode is set to TRUE (continue), AXMLS will continue to apply SQL to the database, even if an error occurs.\r
+       * If the mode is set to FALSE (halt), AXMLS will halt execution of generated sql if an error occurs, though parsing\r
+       * of the schema will continue.\r
+       *\r
+       * @param bool $mode execute\r
+       * @return bool current continueOnError mode\r
+       *\r
+       * @see addSQL(), ExecuteSchema()\r
+       */\r
+       function ContinueOnError( $mode = NULL ) {\r
+               if( is_bool( $mode ) ) {\r
+                       $this->continueOnError = $mode;\r
+               }\r
                \r
+               return $this->continueOnError;\r
+       }\r
+       \r
+       /**\r
+       * Loads an XML schema from a file and converts it to SQL.\r
+       *\r
+       * Call this method to load the specified schema (see the DTD for the proper format) from\r
+       * the filesystem and generate the SQL necessary to create the database described. \r
+       * @see ParseSchemaString()\r
+       *\r
+       * @param string $file Name of XML schema file.\r
+       * @return array Array of SQL queries, ready to execute\r
+       */\r
+       function ParseSchema( $filename ) {\r
+               return $this->ParseSchemaString( $this->ConvertSchemaFile ( $filename ) );\r
+       }\r
+       \r
+       /**\r
+       * Loads an XML schema from a file and converts it to SQL.\r
+       *\r
+       * Call this method to load the specified schema from a file (see the DTD for the proper format) \r
+       * and generate the SQL necessary to create the database described by the schema.\r
+       *\r
+       * @param string $file Name of XML schema file.\r
+       * @return array Array of SQL queries, ready to execute.\r
+       *\r
+       * @deprecated Replaced by adoSchema::ParseSchema() and adoSchema::ParseSchemaString()\r
+       * @see ParseSchema(), ParseSchemaString()\r
+       */\r
+       function ParseSchemaFile( $filename ) {\r
                // Open the file\r
-               if( !( $fp = fopen( $file, "r" ) ) ) {\r
-                       die( "Unable to open file" );\r
+               if( !($fp = fopen( $filename, 'r' )) ) {\r
+                       // die( 'Unable to open file' );\r
+                       return FALSE;\r
                }\r
                \r
+               // do version detection here\r
+               if( $this->SchemaFileVersion( $filename ) != $this->schemaVersion ) {\r
+                       return FALSE;\r
+               }\r
+               \r
+               $xmlParser = $this->create_parser();\r
+               \r
                // Process the file\r
                while( $data = fread( $fp, 4096 ) ) {\r
                        if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) {\r
-                               die( sprintf( "XML error: %s at line %d",\r
-                                       xml_error_string( xml_get_error_code( $xmlParser ) ),\r
-                                       xml_get_current_line_number( $xmlParser ) ) );\r
+                               die( sprintf(\r
+                                       "XML error: %s at line %d",\r
+                                       xml_error_string( xml_get_error_code( $xmlParser) ),\r
+                                       xml_get_current_line_number( $xmlParser)\r
+                               ) );\r
                        }\r
                }\r
                \r
-               // Return the array of queries\r
-               logMsg( "---ParseSchema" );\r
+               xml_parser_free( $xmlParser );\r
+               \r
                return $this->sqlArray;\r
        }\r
        \r
        /**\r
-       * Loads a schema into the database\r
+       * Converts an XML schema string to SQL.\r
        *\r
-       * Accepts an array of SQL queries generated by the parser \r
-       * and executes them.\r
+       * Call this method to parse a string containing an XML schema (see the DTD for the proper format)\r
+       * and generate the SQL necessary to create the database described by the schema. \r
+       * @see ParseSchema()\r
        *\r
-       * @param array $sqlArray        Array of SQL statements\r
-       * @param boolean $continueOnErr Don't fail out if an error is encountered\r
-       * @returns integer      0 if failed, 1 if errors, 2 if successful\r
+       * @param string $xmlstring XML schema string.\r
+       * @return array Array of SQL queries, ready to execute.\r
        */\r
-       function ExecuteSchema( $sqlArray, $continueOnErr =  TRUE ) {\r
-               logMsg( "+++ExecuteSchema( $sqlArray, $continueOnErr )" );\r
+       function ParseSchemaString( $xmlstring ) {\r
+               if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {\r
+                       return FALSE;\r
+               }\r
+               \r
+               // do version detection here\r
+               if( $this->SchemaStringVersion( $xmlstring ) != $this->schemaVersion ) {\r
+                       return FALSE;\r
+               }\r
+               \r
+               $xmlParser = $this->create_parser();\r
+               \r
+               $this->success = 2;\r
                \r
-               $err = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr );\r
+               if( !xml_parse( $xmlParser, $xmlstring, TRUE ) ) {\r
+                       die( sprintf(\r
+                               "XML error: %s at line %d",\r
+                               xml_error_string( xml_get_error_code( $xmlParser) ),\r
+                               xml_get_current_line_number( $xmlParser)\r
+                       ) );\r
+               }\r
                \r
-               // Return the success code\r
-               logMsg( "---ExecuteSchema" );\r
-               return $err;\r
+               xml_parser_free( $xmlParser );\r
+               return $this->sqlArray;\r
        }\r
        \r
        /**\r
-       * XML Callback to process start elements\r
+       * Applies the current XML schema to the database (post execution).\r
        *\r
-       * @access private\r
+       * Call this method to apply the current schema (generally created by calling \r
+       * ParseSchema() or ParseSchemaString() ) to the database (creating the tables, indexes, \r
+       * and executing other SQL specified in the schema) after parsing.\r
+       * @see ParseSchema(), ParseSchemaString(), ExecuteInline()\r
+       *\r
+       * @param array $sqlArray Array of SQL statements that will be applied rather than\r
+       *               the current schema.\r
+       * @param boolean $continueOnErr Continue to apply the schema even if an error occurs.\r
+       * @returns integer 0 if failure, 1 if errors, 2 if successful.\r
        */\r
-       function _xmlcb_startElement( $parser, $name, $attrs ) {\r
+       function ExecuteSchema( $sqlArray = NULL, $continueOnErr =  NULL ) {\r
+               if( !is_bool( $continueOnErr ) ) {\r
+                       $continueOnErr = $this->ContinueOnError();\r
+               }\r
+               \r
+               if( !isset( $sqlArray ) ) {\r
+                       $sqlArray = $this->sqlArray;\r
+               }\r
                \r
-               isset( $this->upgradeMethod ) ? ( $upgradeMethod = $this->upgradeMethod ) : ( $upgradeMethod = '' );\r
+               if( !is_array( $sqlArray ) ) {\r
+                       $this->success = 0;\r
+               } else {\r
+                       $this->success = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr );\r
+               }\r
                \r
-               $dbType = $this->dbType;\r
-               if( isset( $this->table ) ) $table = &$this->table;\r
-               if( isset( $this->index ) ) $index = &$this->index;\r
-               if( isset( $this->querySet ) ) $querySet = &$this->querySet;\r
-               $this->currentElement = $name;\r
+               return $this->success;\r
+       }\r
+       \r
+       /**\r
+       * Returns the current SQL array. \r
+       *\r
+       * Call this method to fetch the array of SQL queries resulting from \r
+       * ParseSchema() or ParseSchemaString(). \r
+       *\r
+       * @param string $format Format: HTML, TEXT, or NONE (PHP array)\r
+       * @return array Array of SQL statements or FALSE if an error occurs\r
+       */\r
+       function PrintSQL( $format = 'NONE' ) {\r
+               return $this->getSQL( $format, $sqlArray );\r
+       }\r
+       \r
+       /**\r
+       * Saves the current SQL array to the local filesystem as a list of SQL queries.\r
+       *\r
+       * Call this method to save the array of SQL queries (generally resulting from a\r
+       * parsed XML schema) to the filesystem.\r
+       *\r
+       * @param string $filename Path and name where the file should be saved.\r
+       * @return boolean TRUE if save is successful, else FALSE. \r
+       */\r
+       function SaveSQL( $filename = './schema.sql' ) {\r
                \r
-               // Process the element. Ignore unimportant elements.\r
-               if( in_array( trim( $name ),  array( "SCHEMA", "DESCR", "COL", "CONSTRAINT" ) ) ) {\r
+               if( !isset( $sqlArray ) ) {\r
+                       $sqlArray = $this->sqlArray;\r
+               }\r
+               if( !isset( $sqlArray ) ) {\r
                        return FALSE;\r
                }\r
                \r
-               switch( $name ) {\r
-                               \r
-                       case "CLUSTERED":       // IndexOpt\r
-                       case "BITMAP":          // IndexOpt\r
-                       case "UNIQUE":          // IndexOpt\r
-                       case "FULLTEXT":        // IndexOpt\r
-                       case "HASH":            // IndexOpt\r
-                               if( isset( $this->index ) ) $this->index->addIndexOpt( $name );\r
-                               break;\r
-\r
-                       case "TABLE":   // Table element\r
-                               if( !isset( $attrs['PLATFORM'] ) or $this->supportedPlatform( $attrs['PLATFORM'] ) ) {\r
-                                       isset( $this->objectPrefix ) ? ( $tableName = $this->objectPrefix . $attrs['NAME'] ) : ( $tableName =  $attrs['NAME'] );\r
-                                       $this->table = new dbTable( $tableName, $upgradeMethod );\r
-                               } else {\r
-                                       unset( $this->table );\r
-                               }\r
-                               break;\r
-                               \r
-                       case "FIELD":   // Table field\r
-                               if( isset( $this->table ) ) {\r
-                                       $fieldName = $attrs['NAME'];\r
-                                       $fieldType = $attrs['TYPE'];\r
-                                       isset( $attrs['SIZE'] ) ? ( $fieldSize = $attrs['SIZE'] ) : ( $fieldSize = NULL );\r
-                                       isset( $attrs['OPTS'] ) ? ( $fieldOpts = $attrs['OPTS'] ) : ( $fieldOpts = NULL );\r
-                                       $this->table->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );\r
-                               }\r
-                               break;\r
-                               \r
-                       case "KEY":     // Table field option\r
-                               if( isset( $this->table ) ) {\r
-                                       $this->table->addFieldOpt( $this->table->currentField, 'KEY' );\r
-                               }\r
-                               break;\r
-                               \r
-                       case "NOTNULL": // Table field option\r
-                               if( isset( $this->table ) ) {\r
-                                       $this->table->addFieldOpt( $this->table->currentField, 'NOTNULL' );\r
-                               }\r
-                               break;\r
-                               \r
-                       case "AUTOINCREMENT":   // Table field option\r
-                               if( isset( $this->table ) ) {\r
-                                       $this->table->addFieldOpt( $this->table->currentField, 'AUTOINCREMENT' );\r
-                               }\r
-                               break;\r
-                               \r
-                       case "DEFAULT": // Table field option\r
-                               if( isset( $this->table ) ) {\r
-                                       $this->table->addFieldOpt( $this->table->currentField, 'DEFAULT', $attrs['VALUE'] );\r
-                               }\r
-                               break;\r
-                               \r
-                       case "INDEX":   // Table index\r
-                       \r
-                               if( !isset( $attrs['PLATFORM'] ) or $this->supportedPlatform( $attrs['PLATFORM'] ) ) {\r
-                                       if (isset($attrs['TABLE']))\r
-                                               isset( $this->objectPrefix) ? ( $tableName = $this->objectPrefix . $attrs['TABLE'] ) : ( $tableName =  $attrs['TABLE'] );\r
-                                       else\r
-                                               $tableName = '';\r
-                                       $this->index = new dbIndex( $attrs['NAME'], $tableName, $upgradeMethod );\r
-                               } else {\r
-                                       if( isset( $this->index ) ) unset( $this->index );\r
-                               }\r
-                               break;\r
-                               \r
-                       case "SQL":     // Freeform SQL queryset\r
-                               if( !isset( $attrs['PLATFORM'] ) or $this->supportedPlatform( $attrs['PLATFORM'] ) ) {\r
-                                       $this->querySet = new dbQuerySet( $attrs );\r
-                               } else {\r
-                                       if( isset( $this->querySet ) ) unset( $this->querySet );\r
-                               }\r
+               $fp = fopen( $filename, "w" );\r
+               \r
+               foreach( $sqlArray as $key => $query ) {\r
+                       fwrite( $fp, $query . ";\n" );\r
+               }\r
+               fclose( $fp );\r
+       }\r
+       \r
+       /**\r
+       * Create an xml parser\r
+       *\r
+       * @return object PHP XML parser object\r
+       *\r
+       * @access private\r
+       */\r
+       function &create_parser() {\r
+               // Create the parser\r
+               $xmlParser = xml_parser_create();\r
+               xml_set_object( $xmlParser, $this );\r
+               \r
+               // Initialize the XML callback functions\r
+               xml_set_element_handler( $xmlParser, '_tag_open', '_tag_close' );\r
+               xml_set_character_data_handler( $xmlParser, '_tag_cdata' );\r
+               \r
+               return $xmlParser;\r
+       }\r
+       \r
+       /**\r
+       * XML Callback to process start elements\r
+       *\r
+       * @access private\r
+       */\r
+       function _tag_open( &$parser, $tag, $attributes ) {\r
+               switch( strtoupper( $tag ) ) {\r
+                       case 'TABLE':\r
+                               $this->obj = new dbTable( $this, $attributes );\r
+                               xml_set_object( $parser, $this->obj );\r
                                break;\r
-                               \r
-                       case "QUERY":   // Queryset SQL query\r
-                               if( isset( $this->querySet ) ) {\r
-                                       // Ignore this query set if a platform is specified and it's different than the \r
-                                       // current connection platform.\r
-                                       if( !isset( $attrs['PLATFORM'] ) or $this->supportedPlatform( $attrs['PLATFORM'] ) ) {\r
-                                               $this->querySet->buildQuery();\r
-                                       } else {\r
-                                               if( isset( $this->querySet->query ) ) unset( $this->querySet->query );\r
-                                       }\r
+                       case 'SQL':\r
+                               if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) {\r
+                                       $this->obj = new dbQuerySet( $this, $attributes );\r
+                                       xml_set_object( $parser, $this->obj );\r
                                }\r
                                break;\r
-                               \r
                        default:\r
-                               if( $this->debug ) print "OPENING ELEMENT '$name'<BR/>\n";\r
-               }       \r
+                               // print_r( array( $tag, $attributes ) );\r
+               }\r
+               \r
        }\r
-\r
+       \r
+       /**\r
+       * XML Callback to process CDATA elements\r
+       *\r
+       * @access private\r
+       */\r
+       function _tag_cdata( &$parser, $cdata ) {\r
+       }\r
+       \r
        /**\r
-       * XML Callback to process cDATA elements\r
+       * XML Callback to process end elements\r
        *\r
        * @access private\r
+       * @internal\r
        */\r
-       function _xmlcb_cData( $parser, $data ) {\r
+       function _tag_close( &$parser, $tag ) {\r
                \r
-               $element = &$this->currentElement;\r
+       }\r
+       \r
+       /**\r
+       * Converts an XML schema string to the specified DTD version.\r
+       *\r
+       * Call this method to convert a string containing an XML schema to a different AXMLS\r
+       * DTD version. For instance, to convert a schema created for an pre-1.0 version for \r
+       * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version \r
+       * parameter is specified, the schema will be converted to the current DTD version. \r
+       * If the newFile parameter is provided, the converted schema will be written to the specified\r
+       * file.\r
+       * @see ConvertSchemaFile()\r
+       *\r
+       * @param string $schema String containing XML schema that will be converted.\r
+       * @param string $newVersion DTD version to convert to.\r
+       * @param string $newFile File name of (converted) output file.\r
+       * @return string Converted XML schema or FALSE if an error occurs.\r
+       */\r
+       function ConvertSchemaString( $schema, $newVersion = NULL, $newFile = NULL ) {\r
                \r
-               if( trim( $data ) == "" ) return;\r
+               // grab current version\r
+               if( !( $version = $this->SchemaStringVersion( $schema ) ) ) {\r
+                       return FALSE;\r
+               }\r
                \r
-               // Process the data depending on the element\r
-               switch( $element ) {\r
+               if( !isset ($newVersion) ) {\r
+                       $newVersion = $this->schemaVersion;\r
+               }\r
                \r
-                       case "COL":     // Index column\r
-                               if( isset( $this->index ) ) $this->index->addField( $data );\r
-                               break;\r
-                               \r
-                       case "DESCR":   // Description element\r
-                               // Display the description information\r
-                               if( isset( $this->table ) ) {\r
-                                       $name = "({$this->table->tableName}):  ";\r
-                               } elseif( isset( $this->index ) ) {\r
-                                       $name = "({$this->index->indexName}):  ";\r
-                               } else {\r
-                                       $name = "";\r
-                               }\r
-                               if( $this->debug ) print "<LI> $name $data\n";\r
-                               break;\r
+               if( $version == $newVersion ) {\r
+                       $result = $schema;\r
+               } else {\r
+                       // Fail if XSLT extension is not available\r
+                       if( ! function_exists( 'xslt_create' ) ) {\r
+                               return FALSE;\r
+                       }\r
                        \r
-                       case "QUERY":   // Query SQL data\r
-                               if( isset( $this->querySet ) and isset( $this->querySet->query ) ) $this->querySet->buildQuery( $data );\r
-                               break;\r
+                       $xsl_file = dirname( __FILE__ ) . '/xsl/convert-' . $version . '-' . $newVersion . '.xsl';\r
                        \r
-                       case "CONSTRAINT":      // Table constraint\r
-                               if( isset( $this->table ) ) $this->table->addTableOpt( $data );\r
-                               break;\r
-                               \r
-                       default:\r
-                               if( $this->debug ) print "<UL><LI>CDATA ($element) $data</UL>\n";\r
+                       // look for xsl\r
+                       if( !is_readable( $xsl_file ) ) {\r
+                               return FALSE;\r
+                       }\r
+                       \r
+                       $arguments = array (\r
+                               '/_xml' => $schema,\r
+                               '/_xsl' => file_get_contents ($xsl_file)\r
+                       );\r
+                       \r
+                       // create an XSLT processor\r
+                       $xh = xslt_create ();\r
+                       \r
+                       // set error handler\r
+                       xslt_set_error_handler ($xh, array (&$this, 'xslt_error_handler'));\r
+                       \r
+                       // process the schema\r
+                       $result = xslt_process ($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments); \r
+                       \r
+                       xslt_free ($xh);\r
+               }\r
+               \r
+               if( is_string ($newFile) AND ( $fp = fopen( $newFile, 'w' ) ) ) {\r
+                       fwrite ($fp, $result);\r
+                       fclose ($fp);\r
                }\r
+               \r
+               return $result;\r
        }\r
-\r
+       \r
        /**\r
-       * XML Callback to process end elements\r
+       * Converts an XML schema file to the specified DTD version.\r
        *\r
-       * @access private\r
+       * Call this method to convert the specified XML schema file to a different AXMLS\r
+       * DTD version. For instance, to convert a schema created for an pre-1.0 version for \r
+       * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version \r
+       * parameter is specified, the schema will be converted to the current DTD version. \r
+       * If the newFile parameter is provided, the converted schema will be written to the specified\r
+       * file.\r
+       * @see ConvertSchemaString()\r
+       *\r
+       * @param string $filename Name of XML schema file that will be converted.\r
+       * @param string $newVersion DTD version to convert to.\r
+       * @param string $newFile File name of (converted) output file.\r
+       * @return string Converted XML schema or FALSE if an error occurs.\r
        */\r
-       function _xmlcb_endElement( $parser, $name ) {\r
+       function ConvertSchemaFile( $filename, $newVersion = NULL, $newFile = NULL ) {\r
                \r
-               // Process the element. Ignore unimportant elements.\r
-               if( in_array( trim( $name ), \r
-                       array(  "SCHEMA", "DESCR", "KEY", "AUTOINCREMENT", "FIELD",\r
-                                               "DEFAULT", "NOTNULL", "CONSTRAINT", "COL" ) ) ) {\r
+               // grab current version\r
+               if( !( $version = $this->SchemaFileVersion( $filename ) ) ) {\r
                        return FALSE;\r
                }\r
                \r
-               switch( trim( $name ) ) {\r
+               if( !isset ($newVersion) ) {\r
+                       $newVersion = $this->schemaVersion;\r
+               }\r
+               \r
+               if( $version == $newVersion ) {\r
+                       $result = file_get_contents( $filename );\r
                        \r
-                       case "TABLE":   // Table element\r
-                               if( isset( $this->table ) ) {\r
-                                       $tableSQL = $this->table->create( $this->dict );\r
-                                       \r
-                                       // Handle case changes in MySQL\r
-                                       // Get the metadata from the database, convert old and new table names to the\r
-                                       // same case and compare. If they're the same, pop a RENAME onto the query stack.\r
-                                       $tableName = $this->table->tableName;\r
-                                       if( $this->dict->upperName == 'MYSQL' \r
-                                               and is_array( $this->legacyTables )\r
-                                               and array_key_exists( strtoupper( $tableName ), $this->legacyTables )\r
-                                               and $oldTableName = $this->legacyTables[ strtoupper( $tableName ) ] ) {\r
-                                               if( $oldTableName != $tableName ) {\r
-                                               logMsg( "RENAMING table $oldTableName to $tableName" );\r
-                                               array_push( $this->sqlArray, "RENAME TABLE $oldTableName TO $tableName" );\r
+                       // remove unicode BOM if present\r
+                       if( substr( $result, 0, 3 ) == sprintf( '%c%c%c', 239, 187, 191 ) ) {\r
+                               $result = substr( $result, 3 );\r
+                       }\r
+               } else {\r
+                       // Fail if XSLT extension is not available\r
+                       if( ! function_exists( 'xslt_create' ) ) {\r
+                               return FALSE;\r
+                       }\r
+                       \r
+                       $xsl_file = dirname( __FILE__ ) . '/xsl/convert-' . $version . '-' . $newVersion . '.xsl';\r
+                       \r
+                       // look for xsl\r
+                       if( !is_readable( $xsl_file ) ) {\r
+                               return FALSE;\r
+                       }\r
+                       \r
+                       $arguments = array (\r
+                               '/_xml' => file_get_contents ($filename),\r
+                               '/_xsl' => file_get_contents ($xsl_file)\r
+                       );\r
+                       \r
+                       // create an XSLT processor\r
+                       $xh = xslt_create ();\r
+                       \r
+                       // set error handler\r
+                       xslt_set_error_handler ($xh, array (&$this, 'xslt_error_handler'));\r
+                       \r
+                       // process the schema\r
+                       $result = xslt_process ($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments); \r
+                       \r
+                       xslt_free ($xh);\r
+               }\r
+               \r
+               if( is_string ($newFile) AND ( $fp = fopen( $newFile, 'w' ) ) ) {\r
+                       fwrite ($fp, $result);\r
+                       fclose ($fp);\r
+               }\r
+               \r
+               return $result;\r
+       }\r
+       \r
+       /**\r
+       * Processes XSLT transformation errors\r
+       *\r
+       * @param object $parser XML parser object\r
+       * @param integer $errno Error number\r
+       * @param integer $level Error level\r
+       * @param array $fields Error information fields\r
+       *\r
+       * @access private\r
+       */\r
+       function xslt_error_handler( $parser, $errno, $level, $fields ) {\r
+               if( is_array( $fields ) ) {\r
+                       $msg = array(\r
+                               'Message Type' => ucfirst( $fields['msgtype'] ),\r
+                               'Message Code' => $fields['code'],\r
+                               'Message' => $fields['msg'],\r
+                               'Error Number' => $errno,\r
+                               'Level' => $level\r
+                       );\r
+                       \r
+                       switch( $fields['URI'] ) {\r
+                               case 'arg:/_xml':\r
+                                       $msg['Input'] = 'XML';\r
+                                       break;\r
+                               case 'arg:/_xsl':\r
+                                       $msg['Input'] = 'XSL';\r
+                                       break;\r
+                               default:\r
+                                       $msg['Input'] = $fields['URI'];\r
+                       }\r
+                       \r
+                       $msg['Line'] = $fields['line'];\r
+               } else {\r
+                       $msg = array(\r
+                               'Message Type' => 'Error',\r
+                               'Error Number' => $errno,\r
+                               'Level' => $level,\r
+                               'Fields' => var_export( $fields, TRUE )\r
+                       );\r
+               }\r
+               \r
+               $error_details = $msg['Message Type'] . ' in XSLT Transformation' . "\n"\r
+                                          . '<table>' . "\n";\r
+               \r
+               foreach( $msg as $label => $details ) {\r
+                       $error_details .= '<tr><td><b>' . $label . ': </b></td><td>' . htmlentities( $details ) . '</td></tr>' . "\n";\r
+               }\r
+               \r
+               $error_details .= '</table>';\r
+               \r
+               trigger_error( $error_details, E_USER_ERROR );\r
+       }\r
+       \r
+       /**\r
+       * Returns the AXMLS Schema Version of the requested XML schema file.\r
+       *\r
+       * Call this method to obtain the AXMLS DTD version of the requested XML schema file.\r
+       * @see SchemaStringVersion()\r
+       *\r
+       * @param string $filename AXMLS schema file\r
+       * @return string Schema version number or FALSE on error\r
+       */\r
+       function SchemaFileVersion( $filename ) {\r
+               // Open the file\r
+               if( !($fp = fopen( $filename, 'r' )) ) {\r
+                       // die( 'Unable to open file' );\r
+                       return FALSE;\r
+               }\r
+               \r
+               // Process the file\r
+               while( $data = fread( $fp, 4096 ) ) {\r
+                       if( preg_match( $this->versionRegex, $data, $matches ) ) {\r
+                               return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;\r
+                       }\r
+               }\r
+               \r
+               return FALSE;\r
+       }\r
+       \r
+       /**\r
+       * Returns the AXMLS Schema Version of the provided XML schema string.\r
+       *\r
+       * Call this method to obtain the AXMLS DTD version of the provided XML schema string.\r
+       * @see SchemaFileVersion()\r
+       *\r
+       * @param string $xmlstring XML schema string\r
+       * @return string Schema version number or FALSE on error\r
+       */\r
+       function SchemaStringVersion( $xmlstring ) {\r
+               if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) {\r
+                       return FALSE;\r
+               }\r
+               \r
+               if( preg_match( $this->versionRegex, $xmlstring, $matches ) ) {\r
+                       return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION;\r
+               }\r
+               \r
+               return FALSE;\r
+       }\r
+       \r
+       /**\r
+       * Extracts an XML schema from an existing database.\r
+       *\r
+       * Call this method to create an XML schema string from an existing database.\r
+       * If the data parameter is set to TRUE, AXMLS will include the data from the database\r
+       * in the schema. \r
+       *\r
+       * @param boolean $data Include data in schema dump\r
+       * @return string Generated XML schema\r
+       */\r
+       function ExtractSchema( $data = FALSE ) {\r
+               $old_mode = $this->db->SetFetchMode( ADODB_FETCH_NUM );\r
+               \r
+               $schema = '<?xml version="1.0"?>' . "\n"\r
+                               . '<schema version="' . $this->schemaVersion . '">' . "\n";\r
+               \r
+               if( is_array( $tables = $this->db->MetaTables( 'TABLES' ) ) ) {\r
+                       foreach( $tables as $table ) {\r
+                               $schema .= '    <table name="' . $table . '">' . "\n";\r
+                               \r
+                               // grab details from database\r
+                               $rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE -1' );\r
+                               $fields = $this->db->MetaColumns( $table );\r
+                               $indexes = $this->db->MetaIndexes( $table );\r
+                               \r
+                               if( is_array( $fields ) ) {\r
+                                       foreach( $fields as $details ) {\r
+                                               $extra = '';\r
+                                               $content = array();\r
+                                               \r
+                                               if( $details->max_length > 0 ) {\r
+                                                       $extra .= ' size="' . $details->max_length . '"';\r
                                                }\r
+                                               \r
+                                               if( $details->primary_key ) {\r
+                                                       $content[] = '<PRIMARY/>';\r
+                                               } elseif( $details->not_null ) {\r
+                                                       $content[] = '<NOTNULL/>';\r
+                                               }\r
+                                               \r
+                                               if( $details->has_default ) {\r
+                                                       $content[] = '<DEFAULT value="' . $details->default_value . '"/>';\r
+                                               }\r
+                                               \r
+                                               if( $details->auto_increment ) {\r
+                                                       $content[] = '<AUTOINCREMENT/>';\r
+                                               }\r
+                                               \r
+                                               // this stops the creation of 'R' columns,\r
+                                               // AUTOINCREMENT is used to create auto columns\r
+                                               $details->primary_key = 0;\r
+                                               $type = $rs->MetaType( $details );\r
+                                               \r
+                                               $schema .= '            <field name="' . $details->name . '" type="' . $type . '"' . $extra . '>';\r
+                                               \r
+                                               if( !empty( $content ) ) {\r
+                                                       $schema .= "\n                  " . implode( "\n                        ", $content ) . "\n             ";\r
+                                               }\r
+                                               \r
+                                               $schema .= '</field>' . "\n";\r
                                        }\r
-                                       foreach( $tableSQL as $query ) {\r
-                                               array_push( $this->sqlArray, $query );\r
-                                       }\r
-                                       $this->table->destroy();\r
                                }\r
-                               break;\r
                                \r
-                       case "DROP":    // Drop an item\r
-                               logMsg( "DROPPING" );\r
-                               if( isset( $this->table ) ) {\r
-                                       // Drop a table or field\r
-                                       $dropSQL = $this->table->drop( $this->dict );                                   \r
-                               } \r
-                               if( isset( $this->index ) ) {\r
-                                       // Drop an index\r
-                                       $dropSQL = $this->index->drop();\r
+                               if( is_array( $indexes ) ) {\r
+                                       foreach( $indexes as $index => $details ) {\r
+                                               $schema .= '            <index name="' . $index . '">' . "\n";\r
+                                               \r
+                                               if( $details['unique'] ) {\r
+                                                       $schema .= '                    <UNIQUE/>' . "\n";\r
+                                               }\r
+                                               \r
+                                               foreach( $details['columns'] as $column ) {\r
+                                                       $schema .= '                    <col>' . $column . '</col>' . "\n";\r
+                                               }\r
+                                               \r
+                                               $schema .= '            </index>' . "\n";\r
+                                       }\r
                                }\r
-                               break;\r
                                \r
-                       case "INDEX":   // Index element\r
-                               if( isset( $this->index ) ) {\r
-                                       $indexSQL = $this->index->create( $this->dict );\r
-                                       foreach( $indexSQL as $query ) {\r
-                                               array_push( $this->sqlArray, $query );\r
+                               if( $data ) {\r
+                                       $rs = $this->db->Execute( 'SELECT * FROM ' . $table );\r
+                                       \r
+                                       if( is_object( $rs ) ) {\r
+                                               $schema .= '            <data>' . "\n";\r
+                                               \r
+                                               while( $row = $rs->FetchRow() ) {\r
+                                                       $schema .= '                    <row><f>' . implode( '</f><f>', $row ) . '</f></row>' . "\n";\r
+                                               }\r
+                                               \r
+                                               $schema .= '            </data>' . "\n";\r
                                        }\r
-                                       $this->index->destroy();\r
-                               }\r
-                               break;\r
-                       \r
-                       case "QUERY":   // Queryset element\r
-                               if( isset( $this->querySet ) and isset( $this->querySet->query ) ) $this->querySet->addQuery();\r
-                               break;\r
-                       \r
-                       case "SQL":     // Query SQL element\r
-                               if( isset( $this->querySet ) ) {\r
-                                       $querySQL = $this->querySet->create();\r
-                                       $this->sqlArray = array_merge( $this->sqlArray, $querySQL );;\r
-                                       $this->querySet->destroy();\r
                                }\r
-                               break;\r
                                \r
-                       default:\r
-                               if( $this->debug ) print "<LI>CLOSING $name</UL>\n";\r
+                               $schema .= '    </table>' . "\n";\r
+                       }\r
                }\r
+               \r
+               $this->db->SetFetchMode( $old_mode );\r
+               \r
+               $schema .= '</schema>';\r
+               return $schema;\r
        }\r
        \r
        /**\r
-    * Set object prefix\r
-    *\r
-    * Sets a standard prefix that will be prepended to all database tables during\r
-    * database creation. Calling setPrefix with no arguments clears the prefix.\r
-    *\r
-    * @param string $prefix Prefix\r
-    * @return boolean       TRUE if successful, else FALSE\r
-    */\r
-    function setPrefix( $prefix = '' ) {\r
-\r
-            if( !preg_match( '/[^\w]/', $prefix ) and strlen( $prefix < XMLS_PREFIX_MAXLEN ) ) {\r
-                $this->objectPrefix = $prefix;\r
-                logMsg( "Prepended prefix: $prefix" );\r
-                return TRUE;\r
-            } else {\r
-               logMsg( "No prefix" );\r
-                return FALSE;\r
-            }\r
-    }\r
+       * Sets a prefix for database objects\r
+       *\r
+       * Call this method to set a standard prefix that will be prepended to all database tables \r
+       * and indices when the schema is parsed. Calling setPrefix with no arguments clears the prefix.\r
+       *\r
+       * @param string $prefix Prefix that will be prepended.\r
+       * @param boolean $underscore If TRUE, automatically append an underscore character to the prefix.\r
+       * @return boolean TRUE if successful, else FALSE\r
+       */\r
+       function SetPrefix( $prefix = '', $underscore = TRUE ) {\r
+               switch( TRUE ) {\r
+                       // clear prefix\r
+                       case empty( $prefix ):\r
+                               logMsg( 'Cleared prefix' );\r
+                               $this->objectPrefix = '';\r
+                               return TRUE;\r
+                       // prefix too long\r
+                       case strlen( $prefix ) > XMLS_PREFIX_MAXLEN:\r
+                       // prefix contains invalid characters\r
+                       case !preg_match( '/^[a-z][a-z0-9]+$/i', $prefix ):\r
+                               logMsg( 'Invalid prefix: ' . $prefix );\r
+                               return FALSE;\r
+               }\r
+               \r
+               if( $underscore AND substr( $prefix, -1 ) != '_' ) {\r
+                       $prefix .= '_';\r
+               }\r
+               \r
+               // prefix valid\r
+               logMsg( 'Set prefix: ' . $prefix );\r
+               $this->objectPrefix = $prefix;\r
+               return TRUE;\r
+       }\r
        \r
+       /**\r
+       * Returns an object name with the current prefix prepended.\r
+       *\r
+       * @param string $name Name\r
+       * @return string        Prefixed name\r
+       *\r
+       * @access private\r
+       */\r
+       function prefix( $name = '' ) {\r
+               // if prefix is set\r
+               if( !empty( $this->objectPrefix ) ) {\r
+                       // Prepend the object prefix to the table name\r
+                       // prepend after quote if used\r
+                       return preg_replace( '/^(`?)(.+)$/', '$1' . $this->objectPrefix . '$2', $name );\r
+               }\r
+               \r
+               // No prefix set. Use name provided.\r
+               return $name;\r
+       }\r
        \r
        /**\r
        * Checks if element references a specific platform\r
        *\r
-       * Returns TRUE is no platform is specified or if we are currently\r
-       * using the specified platform.\r
-       *\r
-       * @param string $platform       Requested platform\r
-       * @returns boolean      TRUE if platform check succeeds\r
+       * @param string $platform Requested platform\r
+       * @returns boolean TRUE if platform check succeeds\r
        *\r
        * @access private\r
        */\r
        function supportedPlatform( $platform = NULL ) {\r
+               $regex = '/^(\w*\|)*' . $this->db->databaseType . '(\|\w*)*$/';\r
                \r
-               $dbType = $this->dbType;\r
-               $regex = "/^(\w*\|)*" . $dbType . "(\|\w*)*$/";\r
-               \r
-               if( !isset( $platform ) or preg_match( $regex, $platform ) ) {\r
+               if( !isset( $platform ) OR preg_match( $regex, $platform ) ) {\r
                        logMsg( "Platform $platform is supported" );\r
                        return TRUE;\r
                } else {\r
@@ -1164,38 +1836,116 @@ class adoSchema {
        }\r
        \r
        /**\r
-       * Destructor: Destroys an adoSchema object. \r
+       * Clears the array of generated SQL.\r
+       *\r
+       * @access private\r
+       */\r
+       function clearSQL() {\r
+               $this->sqlArray = array();\r
+       }\r
+       \r
+       /**\r
+       * Adds SQL into the SQL array.\r
+       *\r
+       * @param mixed $sql SQL to Add\r
+       * @return boolean TRUE if successful, else FALSE.\r
+       *\r
+       * @access private\r
+       */      \r
+       function addSQL( $sql = NULL ) {\r
+               if( is_array( $sql ) ) {\r
+                       foreach( $sql as $line ) {\r
+                               $this->addSQL( $line );\r
+                       }\r
+                       \r
+                       return TRUE;\r
+               }\r
+               \r
+               if( is_string( $sql ) ) {\r
+                       $this->sqlArray[] = $sql;\r
+                       \r
+                       // if executeInline is enabled, and either no errors have occurred or continueOnError is enabled, execute SQL.\r
+                       if( $this->ExecuteInline() && ( $this->success == 2 || $this->ContinueOnError() ) ) {\r
+                               $saved = $this->db->debug;\r
+                               $this->db->debug = $this->debug;\r
+                               $ok = $this->db->Execute( $sql );\r
+                               $this->db->debug = $saved;\r
+                               \r
+                               if( !$ok ) {\r
+                                       if( $this->debug ) {\r
+                                               ADOConnection::outp( $this->db->ErrorMsg() );\r
+                                       }\r
+                                       \r
+                                       $this->success = 1;\r
+                               }\r
+                       }\r
+                       \r
+                       return TRUE;\r
+               }\r
+               \r
+               return FALSE;\r
+       }\r
+       \r
+       /**\r
+       * Gets the SQL array in the specified format.\r
+       *\r
+       * @param string $format Format\r
+       * @return mixed SQL\r
+       *       \r
+       * @access private\r
+       */\r
+       function getSQL( $format = NULL, $sqlArray = NULL ) {\r
+               if( !is_array( $sqlArray ) ) {\r
+                       $sqlArray = $this->sqlArray;\r
+               }\r
+               \r
+               if( !is_array( $sqlArray ) ) {\r
+                       return FALSE;\r
+               }\r
+               \r
+               switch( strtolower( $format ) ) {\r
+                       case 'string':\r
+                       case 'text':\r
+                               return !empty( $sqlArray ) ? implode( ";\n\n", $sqlArray ) . ';' : '';\r
+                       case'html':\r
+                               return !empty( $sqlArray ) ? nl2br( htmlentities( implode( ";\n\n", $sqlArray ) . ';' ) ) : '';\r
+               }\r
+               \r
+               return $this->sqlArray;\r
+       }\r
+       \r
+       /**\r
+       * Destroys an adoSchema object.\r
        *\r
-       * You should call this to clean up when you're finished with adoSchema.\r
+       * Call this method to clean up after an adoSchema object that is no longer in use.\r
+       * @deprecated adoSchema now cleans up automatically.\r
        */\r
        function Destroy() {\r
-               xml_parser_free( $this->xmlParser );\r
                set_magic_quotes_runtime( $this->mgq );\r
                unset( $this );\r
        }\r
 }\r
 \r
 /**\r
-* Message loggging function\r
+* Message logging function\r
 *\r
 * @access private\r
 */\r
 function logMsg( $msg, $title = NULL ) {\r
        if( XMLS_DEBUG ) {\r
-               print "<PRE>";\r
+               echo '<pre>';\r
+               \r
                if( isset( $title ) ) {\r
-                       print "<H3>$title</H3>";\r
-               }\r
-               if( isset( $this ) ) {\r
-                       print "[" . get_class( $this ) . "] ";\r
+                       echo '<h3>' . htmlentities( $title ) . '</h3>';\r
                }\r
-               if( is_array( $msg ) or is_object( $msg ) ) {\r
-                       print_r( $msg );\r
-                       print "<BR/>";\r
-               } else {\r
-                       print "$msg<BR/>";\r
+               \r
+               if( is_object( $this ) ) {\r
+                       echo '[' . get_class( $this ) . '] ';\r
                }\r
-               print "</PRE>";\r
+               \r
+               print_r( $msg );\r
+               \r
+               echo '</pre>';\r
        }\r
 }\r
 ?>
\ No newline at end of file
index 46a72684e5c423bef41165485071853785ed831c..4a0efd204e95826d4338743f5e0c815a237bfc51 100644 (file)
-<?php \r
-/*\r
- * Set tabs to 4 for best viewing.\r
- * \r
- * Latest version is available at http://php.weblogs.com/adodb\r
- * \r
- * This is the main include file for ADOdb.\r
- * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php\r
- *\r
- * The ADOdb files are formatted so that doxygen can be used to generate documentation.\r
- * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/\r
- */\r
-\r
-/**\r
-       \mainpage       \r
-       \r
-        @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved.\r
-\r
-       Released under both BSD license and Lesser GPL library license. You can choose which license\r
-       you prefer.\r
-       \r
-       PHP's database access functions are not standardised. This creates a need for a database \r
-       class library to hide the differences between the different database API's (encapsulate \r
-       the differences) so we can easily switch databases.\r
-\r
-       We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,\r
-       Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,\r
-       ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and\r
-       other databases via ODBC. \r
-        \r
-       Latest Download at http://php.weblogs.com/adodb<br>\r
-       Manual is at http://php.weblogs.com/adodb_manual\r
-         \r
- */\r
\r
- if (!defined('_ADODB_LAYER')) {\r
-       define('_ADODB_LAYER',1);\r
-       \r
-       //==============================================================================================        \r
-       // CONSTANT DEFINITIONS\r
-       //==============================================================================================        \r
-\r
-\r
-       /** \r
-        * Set ADODB_DIR to the directory where this file resides...\r
-        * This constant was formerly called $ADODB_RootPath\r
-        */\r
-       if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));\r
-       \r
-       //==============================================================================================        \r
-       // GLOBAL VARIABLES\r
-       //==============================================================================================        \r
-\r
-       GLOBAL \r
-               $ADODB_vers,            // database version\r
-               $ADODB_COUNTRECS,       // count number of records returned - slows down query\r
-               $ADODB_CACHE_DIR,       // directory to cache recordsets\r
-               $ADODB_EXTENSION,   // ADODB extension installed\r
-               $ADODB_COMPAT_PATCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF\r
-               $ADODB_FETCH_MODE;      // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...\r
-       \r
-       //==============================================================================================        \r
-       // GLOBAL SETUP\r
-       //==============================================================================================        \r
-       \r
-       $ADODB_EXTENSION = defined('ADODB_EXTENSION');\r
-       if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {\r
-               \r
-               define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');\r
-       \r
-       // allow [ ] @ ` and . in table names\r
-               define('ADODB_TABLE_REGEX','([]0-9a-z_\`\.\@\[-]*)');\r
-       \r
-       // prefetching used by oracle\r
-               if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);\r
-       \r
-       \r
-       /*\r
-       Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.\r
-       This currently works only with mssql, odbc, oci8po and ibase derived drivers.\r
-       \r
-               0 = assoc lowercase field names. $rs->fields['orderid']\r
-               1 = assoc uppercase field names. $rs->fields['ORDERID']\r
-               2 = use native-case field names. $rs->fields['OrderID']\r
-       */\r
-       \r
-               define('ADODB_FETCH_DEFAULT',0);\r
-               define('ADODB_FETCH_NUM',1);\r
-               define('ADODB_FETCH_ASSOC',2);\r
-               define('ADODB_FETCH_BOTH',3);\r
-               \r
-               if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);\r
-       \r
-               if (strnatcmp(PHP_VERSION,'4.3.0')>=0) {\r
-                       define('ADODB_PHPVER',0x4300);\r
-               } else if (strnatcmp(PHP_VERSION,'4.2.0')>=0) {\r
-                       define('ADODB_PHPVER',0x4200);\r
-               } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {\r
-                       define('ADODB_PHPVER',0x4050);\r
-               } else {\r
-                       define('ADODB_PHPVER',0x4000);\r
-               }\r
-       }\r
-       \r
-       //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);\r
-       \r
-       \r
-       /**\r
-               Accepts $src and $dest arrays, replacing string $data\r
-       */\r
-       function ADODB_str_replace($src, $dest, $data)\r
-       {\r
-               if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);\r
-               \r
-               $s = reset($src);\r
-               $d = reset($dest);\r
-               while ($s !== false) {\r
-                       $data = str_replace($s,$d,$data);\r
-                       $s = next($src);\r
-                       $d = next($dest);\r
-               }\r
-               return $data;\r
-       }\r
-       \r
-       function ADODB_Setup()\r
-       {\r
-       GLOBAL \r
-               $ADODB_vers,            // database version\r
-               $ADODB_COUNTRECS,       // count number of records returned - slows down query\r
-               $ADODB_CACHE_DIR,       // directory to cache recordsets\r
-               $ADODB_FETCH_MODE;\r
-               \r
-               $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;\r
-               \r
-               if (!isset($ADODB_CACHE_DIR)) {\r
-                       $ADODB_CACHE_DIR = '/tmp';\r
-               } else {\r
-                       // do not accept url based paths, eg. http:/ or ftp:/\r
-                       if (strpos($ADODB_CACHE_DIR,'://') !== false) \r
-                               die("Illegal path http:// or ftp://");\r
-               }\r
-               \r
-                       \r
-               // Initialize random number generator for randomizing cache flushes\r
-               srand(((double)microtime())*1000000);\r
-               \r
-               /**\r
-                * ADODB version as a string.\r
-                */\r
-               $ADODB_vers = 'V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';\r
-       \r
-               /**\r
-                * Determines whether recordset->RecordCount() is used. \r
-                * Set to false for highest performance -- RecordCount() will always return -1 then\r
-                * for databases that provide "virtual" recordcounts...\r
-                */\r
-               if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true; \r
-       }\r
-       \r
-       \r
-       //==============================================================================================        \r
-       // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB\r
-       //==============================================================================================        \r
-       \r
-       ADODB_Setup();\r
-\r
-       //==============================================================================================        \r
-       // CLASS ADOFieldObject\r
-       //==============================================================================================        \r
-       /**\r
-        * Helper class for FetchFields -- holds info on a column\r
-        */\r
-       class ADOFieldObject { \r
-               var $name = '';\r
-               var $max_length=0;\r
-               var $type="";\r
-\r
-               // additional fields by dannym... (danny_milo@yahoo.com)\r
-               var $not_null = false; \r
-               // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^\r
-               // so we can as well make not_null standard (leaving it at "false" does not harm anyways)\r
-\r
-               var $has_default = false; // this one I have done only in mysql and postgres for now ... \r
-                       // others to come (dannym)\r
-               var $default_value; // default, if any, and supported. Check has_default first.\r
-       }\r
-       \r
-\r
-       \r
-       function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)\r
-       {\r
-               //print "Errorno ($fn errno=$errno m=$errmsg) ";\r
-               $thisConnection->_transOK = false;\r
-               if ($thisConnection->_oldRaiseFn) {\r
-                       $fn = $thisConnection->_oldRaiseFn;\r
-                       $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);\r
-               }\r
-       }\r
-       \r
-       //==============================================================================================        \r
-       // CLASS ADOConnection\r
-       //==============================================================================================        \r
-       \r
-       /**\r
-        * Connection object. For connecting to databases, and executing queries.\r
-        */ \r
-       class ADOConnection {\r
-       //\r
-       // PUBLIC VARS \r
-       //\r
-       var $dataProvider = 'native';\r
-       var $databaseType = '';         /// RDBMS currently in use, eg. odbc, mysql, mssql                                      \r
-       var $database = '';                     /// Name of database to be used.        \r
-       var $host = '';                         /// The hostname of the database server \r
-       var $user = '';                         /// The username which is used to connect to the database server. \r
-       var $password = '';             /// Password for the username. For security, we no longer store it.\r
-       var $debug = false;             /// if set to true will output sql statements\r
-       var $maxblobsize = 256000;      /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro\r
-       var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase    \r
-       var $substr = 'substr';         /// substring operator\r
-       var $length = 'length';         /// string length operator\r
-       var $random = 'rand()';         /// random function\r
-       var $upperCase = false;         /// uppercase function\r
-       var $fmtDate = "'Y-m-d'";       /// used by DBDate() as the default date format used by the database\r
-       var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.\r
-       var $true = '1';                        /// string that represents TRUE for a database\r
-       var $false = '0';                       /// string that represents FALSE for a database\r
-       var $replaceQuote = "\\'";      /// string to use to replace quotes\r
-       var $nameQuote = '"';           /// string to use to quote identifiers and names\r
-       var $charSet=false;             /// character set to use - only for interbase\r
-       var $metaDatabasesSQL = '';\r
-       var $metaTablesSQL = '';\r
-       var $uniqueOrderBy = false; /// All order by columns have to be unique\r
-       var $emptyDate = '&nbsp;';\r
-       var $emptyTimeStamp = '&nbsp;';\r
-       var $lastInsID = false;\r
-       //--\r
-       var $hasInsertID = false;               /// supports autoincrement ID?\r
-       var $hasAffectedRows = false;   /// supports affected rows for update/delete?\r
-       var $hasTop = false;                    /// support mssql/access SELECT TOP 10 * FROM TABLE\r
-       var $hasLimit = false;                  /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10\r
-       var $readOnly = false;                  /// this is a readonly database - used by phpLens\r
-       var $hasMoveFirst = false;  /// has ability to run MoveFirst(), scrolling backwards\r
-       var $hasGenID = false;          /// can generate sequences using GenID();\r
-       var $hasTransactions = true; /// has transactions\r
-       //--\r
-       var $genID = 0;                         /// sequence id used by GenID();\r
-       var $raiseErrorFn = false;      /// error function to call\r
-       var $isoDates = false; /// accepts dates in ISO format\r
-       var $cacheSecs = 3600; /// cache for 1 hour\r
-       var $sysDate = false; /// name of function that returns the current date\r
-       var $sysTimeStamp = false; /// name of function that returns the current timestamp\r
-       var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets\r
-       \r
-       var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '\r
-       var $numCacheHits = 0; \r
-       var $numCacheMisses = 0;\r
-       var $pageExecuteCountRows = true;\r
-       var $uniqueSort = false; /// indicates that all fields in order by must be unique\r
-       var $leftOuter = false; /// operator to use for left outer join in WHERE clause\r
-       var $rightOuter = false; /// operator to use for right outer join in WHERE clause\r
-       var $ansiOuter = false; /// whether ansi outer join syntax supported\r
-       var $autoRollback = false; // autoRollback on PConnect().\r
-       var $poorAffectedRows = false; // affectedRows not working or unreliable\r
-       \r
-       var $fnExecute = false;\r
-       var $fnCacheExecute = false;\r
-       var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char\r
-       var $rsPrefix = "ADORecordSet_";\r
-       \r
-       var $autoCommit = true;         /// do not modify this yourself - actually private\r
-       var $transOff = 0;                      /// temporarily disable transactions\r
-       var $transCnt = 0;                      /// count of nested transactions\r
-       \r
-       var $fetchMode=false;\r
-        //\r
-        // PRIVATE VARS\r
-        //\r
-       var $_oldRaiseFn =  false;\r
-       var $_transOK = null;\r
-       var $_connectionID      = false;        /// The returned link identifier whenever a successful database connection is made.     \r
-       var $_errorMsg = false;         /// A variable which was used to keep the returned last error message.  The value will\r
-                                                               /// then returned by the errorMsg() function    \r
-       var $_errorCode = false;        /// Last error code, not guaranteed to be used - only by oci8                                   \r
-       var $_queryID = false;          /// This variable keeps the last created result link identifier\r
-       \r
-       var $_isPersistentConnection = false;   /// A boolean variable to state whether its a persistent connection or normal connection.       */\r
-       var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.\r
-       var $_evalAll = false;\r
-       var $_affected = false;\r
-       var $_logsql = false;\r
-       \r
-\r
-       \r
-       /**\r
-        * Constructor\r
-        */\r
-       function ADOConnection()                        \r
-       {\r
-               die('Virtual Class -- cannot instantiate');\r
-       }\r
-       \r
-       /**\r
-               Get server version info...\r
-               \r
-               @returns An array with 2 elements: $arr['string'] is the description string, \r
-                       and $arr[version] is the version (also a string).\r
-       */\r
-       function ServerInfo()\r
-       {\r
-               return array('description' => '', 'version' => '');\r
-       }\r
-       \r
-       function _findvers($str)\r
-       {\r
-               if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];\r
-               else return '';\r
-       }\r
-       \r
-       /**\r
-       * All error messages go through this bottleneck function.\r
-       * You can define your own handler by defining the function name in ADODB_OUTP.\r
-       */\r
-       function outp($msg,$newline=true)\r
-       {\r
-       global $HTTP_SERVER_VARS,$ADODB_FLUSH;\r
-       \r
-               if (defined('ADODB_OUTP')) {\r
-                       $fn = ADODB_OUTP;\r
-                       $fn($msg,$newline);\r
-                       return;\r
-               }\r
-               \r
-               if ($newline) $msg .= "<br>\n";\r
-               \r
-               if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg;\r
-               else echo strip_tags($msg);\r
-               if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); //  dp not flush if output buffering enabled - useless - thx to Jesse Mullan \r
-               \r
-       }\r
-       \r
-       /**\r
-        * Connect to database\r
-        *\r
-        * @param [argHostname]         Host to connect to\r
-        * @param [argUsername]         Userid to login\r
-        * @param [argPassword]         Associated password\r
-        * @param [argDatabaseName]     database\r
-        * @param [forceNew]            force new connection\r
-        *\r
-        * @return true or false\r
-        */       \r
-       function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) \r
-       {\r
-               if ($argHostname != "") $this->host = $argHostname;\r
-               if ($argUsername != "") $this->user = $argUsername;\r
-               if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons\r
-               if ($argDatabaseName != "") $this->database = $argDatabaseName;         \r
-               \r
-               $this->_isPersistentConnection = false; \r
-               if ($fn = $this->raiseErrorFn) {\r
-                       if ($forceNew) {\r
-                               if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;\r
-                       } else {\r
-                                if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;\r
-                       }\r
-                       $err = $this->ErrorMsg();\r
-                       if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";\r
-                       $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);\r
-               } else {\r
-                       if ($forceNew) {\r
-                               if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;\r
-                       } else {\r
-                               if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;\r
-                       }\r
-               }\r
-               if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());\r
-               return false;\r
-       }       \r
-       \r
-        function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)\r
-        {\r
-               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);\r
-        }\r
-       \r
-       \r
-       /**\r
-        * Always force a new connection to database - currently only works with oracle\r
-        *\r
-        * @param [argHostname]         Host to connect to\r
-        * @param [argUsername]         Userid to login\r
-        * @param [argPassword]         Associated password\r
-        * @param [argDatabaseName]     database\r
-        *\r
-        * @return true or false\r
-        */       \r
-       function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") \r
-       {\r
-               return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);\r
-       }\r
-       \r
-       /**\r
-        * Establish persistent connect to database\r
-        *\r
-        * @param [argHostname]         Host to connect to\r
-        * @param [argUsername]         Userid to login\r
-        * @param [argPassword]         Associated password\r
-        * @param [argDatabaseName]     database\r
-        *\r
-        * @return return true or false\r
-        */     \r
-       function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")\r
-       {\r
-               if (defined('ADODB_NEVER_PERSIST')) \r
-                       return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);\r
-               \r
-               if ($argHostname != "") $this->host = $argHostname;\r
-               if ($argUsername != "") $this->user = $argUsername;\r
-               if ($argPassword != "") $this->password = $argPassword;\r
-               if ($argDatabaseName != "") $this->database = $argDatabaseName;         \r
-                       \r
-               $this->_isPersistentConnection = true;  \r
-               \r
-               if ($fn = $this->raiseErrorFn) {\r
-                       if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;\r
-                       $err = $this->ErrorMsg();\r
-                       if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";\r
-                       $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);\r
-               } else \r
-                       if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;\r
-\r
-               if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());\r
-               return false;\r
-       }\r
-\r
-       // Format date column in sql string given an input format that understands Y M D\r
-       function SQLDate($fmt, $col=false)\r
-       {       \r
-               if (!$col) $col = $this->sysDate;\r
-               return $col; // child class implement\r
-       }\r
-       \r
-       /**\r
-        * Should prepare the sql statement and return the stmt resource.\r
-        * For databases that do not support this, we return the $sql. To ensure\r
-        * compatibility with databases that do not support prepare:\r
-        *\r
-        *   $stmt = $db->Prepare("insert into table (id, name) values (?,?)");\r
-        *   $db->Execute($stmt,array(1,'Jill')) or die('insert failed');\r
-        *   $db->Execute($stmt,array(2,'Joe')) or die('insert failed');\r
-        *\r
-        * @param sql   SQL to send to database\r
-        *\r
-        * @return return FALSE, or the prepared statement, or the original sql if\r
-        *                      if the database does not support prepare.\r
-        *\r
-        */     \r
-       function Prepare($sql)\r
-       {\r
-               return $sql;\r
-       }\r
-\r
-       /**\r
-        * Some databases, eg. mssql require a different function for preparing\r
-        * stored procedures. So we cannot use Prepare().\r
-        *\r
-        * Should prepare the stored procedure  and return the stmt resource.\r
-        * For databases that do not support this, we return the $sql. To ensure\r
-        * compatibility with databases that do not support prepare:\r
-        *\r
-        * @param sql   SQL to send to database\r
-        *\r
-        * @return return FALSE, or the prepared statement, or the original sql if\r
-        *                      if the database does not support prepare.\r
-        *\r
-        */     \r
-       function PrepareSP($sql,$param=false)\r
-       {\r
-               return $this->Prepare($sql,$param);\r
-       }\r
-       \r
-       /**\r
-       * PEAR DB Compat\r
-       */\r
-       function Quote($s)\r
-       {\r
-               return $this->qstr($s,false);\r
-       }\r
-       \r
-       /**\r
-        Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>\r
-       */\r
-       function QMagic($s)\r
-       {\r
-               return $this->qstr($s,get_magic_quotes_gpc());\r
-       }\r
-\r
-       function q(&$s)\r
-       {\r
-               $s = $this->qstr($s,false);\r
-       }\r
-       \r
-       /**\r
-       * PEAR DB Compat - do not use internally. \r
-       */\r
-       function ErrorNative()\r
-       {\r
-               return $this->ErrorNo();\r
-       }\r
-\r
-       \r
-   /**\r
-       * PEAR DB Compat - do not use internally. \r
-       */\r
-       function nextId($seq_name)\r
-       {\r
-               return $this->GenID($seq_name);\r
-       }\r
-\r
-       /**\r
-       *        Lock a row, will escalate and lock the table if row locking not supported\r
-       *       will normally free the lock at the end of the transaction\r
-       *\r
-       *  @param $table        name of table to lock\r
-       *  @param $where        where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock\r
-       */\r
-       function RowLock($table,$where)\r
-       {\r
-               return false;\r
-       }\r
-       \r
-       function CommitLock($table)\r
-       {\r
-               return $this->CommitTrans();\r
-       }\r
-       \r
-       function RollbackLock($table)\r
-       {\r
-               return $this->RollbackTrans();\r
-       }\r
-       \r
-       /**\r
-       * PEAR DB Compat - do not use internally. \r
-       *\r
-       * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical\r
-       *       for easy porting :-)\r
-       *\r
-       * @param mode   The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM\r
-       * @returns              The previous fetch mode\r
-       */\r
-       function SetFetchMode($mode)\r
-       {       \r
-               $old = $this->fetchMode;\r
-               $this->fetchMode = $mode;\r
-               \r
-               if ($old === false) {\r
-               global $ADODB_FETCH_MODE;\r
-                       return $ADODB_FETCH_MODE;\r
-               }\r
-               return $old;\r
-       }\r
-       \r
-\r
-       /**\r
-       * PEAR DB Compat - do not use internally. \r
-       */\r
-       function &Query($sql, $inputarr=false)\r
-       {\r
-               $rs = &$this->Execute($sql, $inputarr);\r
-               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
-               return $rs;\r
-       }\r
-\r
-       \r
-       /**\r
-       * PEAR DB Compat - do not use internally\r
-       */\r
-       function &LimitQuery($sql, $offset, $count, $params=false)\r
-       {\r
-               $rs = &$this->SelectLimit($sql, $count, $offset, $params); \r
-               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
-               return $rs;\r
-       }\r
-\r
-       \r
-       /**\r
-       * PEAR DB Compat - do not use internally\r
-       */\r
-       function Disconnect()\r
-       {\r
-               return $this->Close();\r
-       }\r
-       \r
-       /*\r
-                returns placeholder for parameter, eg.\r
-                $DB->Param('a')\r
-                \r
-                will return ':a' for Oracle, and '?' for most other databases...\r
-       */\r
-       function Param($name)\r
-       {\r
-               return '?';\r
-       }\r
-       \r
-       /*\r
-               InParameter and OutParameter are self-documenting versions of Parameter().\r
-       */\r
-       function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)\r
-       {\r
-               return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);\r
-       }\r
-       \r
-       /*\r
-       */\r
-       function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)\r
-       {\r
-               return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);\r
-       \r
-       }\r
-       \r
-       /* \r
-       Usage in oracle\r
-               $stmt = $db->Prepare('select * from table where id =:myid and group=:group');\r
-               $db->Parameter($stmt,$id,'myid');\r
-               $db->Parameter($stmt,$group,'group',64);\r
-               $db->Execute();\r
-               \r
-               @param $stmt Statement returned by Prepare() or PrepareSP().\r
-               @param $var PHP variable to bind to\r
-               @param $name Name of stored procedure variable name to bind to.\r
-               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.\r
-               @param [$maxLen] Holds an maximum length of the variable.\r
-               @param [$type] The data type of $var. Legal values depend on driver.\r
-\r
-       */\r
-       function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)\r
-       {\r
-               return false;\r
-       }\r
-       \r
-       /**\r
-               Improved method of initiating a transaction. Used together with CompleteTrans().\r
-               Advantages include:\r
-               \r
-               a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.\r
-                  Only the outermost block is treated as a transaction.<br>\r
-               b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>\r
-               c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block\r
-                  are disabled, making it backward compatible.\r
-       */\r
-       function StartTrans($errfn = 'ADODB_TransMonitor')\r
-       {\r
-               if ($this->transOff > 0) {\r
-                       $this->transOff += 1;\r
-                       return;\r
-               }\r
-               \r
-               $this->_oldRaiseFn = $this->raiseErrorFn;\r
-               $this->raiseErrorFn = $errfn;\r
-               $this->_transOK = true;\r
-               \r
-               if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");\r
-               $this->BeginTrans();\r
-               $this->transOff = 1;\r
-       }\r
-       \r
-       /**\r
-               Used together with StartTrans() to end a transaction. Monitors connection\r
-               for sql errors, and will commit or rollback as appropriate.\r
-               \r
-               @autoComplete if true, monitor sql errors and commit and rollback as appropriate, \r
-               and if set to false force rollback even if no SQL error detected.\r
-               @returns true on commit, false on rollback.\r
-       */\r
-       function CompleteTrans($autoComplete = true)\r
-       {\r
-               if ($this->transOff > 1) {\r
-                       $this->transOff -= 1;\r
-                       return true;\r
-               }\r
-               $this->raiseErrorFn = $this->_oldRaiseFn;\r
-               \r
-               $this->transOff = 0;\r
-               if ($this->_transOK && $autoComplete) {\r
-                       if (!$this->CommitTrans()) {\r
-                               $this->_transOK = false;\r
-                               if ($this->debug) ADOConnection::outp("Smart Commit failed");\r
-                       } else\r
-                               if ($this->debug) ADOConnection::outp("Smart Commit occurred");\r
-               } else {\r
-                       $this->RollbackTrans();\r
-                       if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");\r
-               }\r
-               \r
-               return $this->_transOK;\r
-       }\r
-       \r
-       /*\r
-               At the end of a StartTrans/CompleteTrans block, perform a rollback.\r
-       */\r
-       function FailTrans()\r
-       {\r
-               if ($this->debug) \r
-                       if ($this->transOff == 0) {\r
-                               ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");\r
-                       } else {\r
-                               ADOConnection::outp("FailTrans was called");\r
-                               adodb_backtrace();\r
-                       }\r
-               $this->_transOK = false;\r
-       }\r
-       \r
-       /**\r
-               Check if transaction has failed, only for Smart Transactions.\r
-       */\r
-       function HasFailedTrans()\r
-       {\r
-               if ($this->transOff > 0) return $this->_transOK == false;\r
-               return false;\r
-       }\r
-       \r
-       /**\r
-        * Execute SQL \r
-        *\r
-        * @param sql           SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)\r
-        * @param [inputarr]    holds the input data to bind to. Null elements will be set to null.\r
-        * @return              RecordSet or false\r
-        */\r
-       function &Execute($sql,$inputarr=false) \r
-       {\r
-               if ($this->fnExecute) {\r
-                       $fn = $this->fnExecute;\r
-                       $ret =& $fn($this,$sql,$inputarr);\r
-                       if (isset($ret)) return $ret;\r
-               }\r
-               if ($inputarr && is_array($inputarr)) {\r
-                       $element0 = reset($inputarr);\r
-                       # is_object check is because oci8 descriptors can be passed in\r
-                       $array_2d = is_array($element0) && !is_object(reset($element0));\r
-                       \r
-                       if (!is_array($sql) && !$this->_bindInputArray) {\r
-                               $sqlarr = explode('?',$sql);\r
-                                       \r
-                               if (!$array_2d) $inputarr = array($inputarr);\r
-                               foreach($inputarr as $arr) {\r
-                                       $sql = ''; $i = 0;\r
-                                       foreach($arr as $v) {\r
-                                               $sql .= $sqlarr[$i];\r
-                                               // from Ron Baldwin <ron.baldwin@sourceprose.com>\r
-                                               // Only quote string types      \r
-                                               if (gettype($v) == 'string')\r
-                                                       $sql .= $this->qstr($v);\r
-                                               else if ($v === null)\r
-                                                       $sql .= 'NULL';\r
-                                               else\r
-                                                       $sql .= $v;\r
-                                               $i += 1;\r
-                                       }\r
-                                       $sql .= $sqlarr[$i];\r
-                                       \r
-                                       if ($i+1 != sizeof($sqlarr))    \r
-                                               ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));\r
-               \r
-                                       $ret =& $this->_Execute($sql,false);\r
-                                       if (!$ret) return $ret;\r
-                               }       \r
-                       } else {\r
-                               if ($array_2d) {\r
-                                       $stmt = $this->Prepare($sql);\r
-                                       foreach($inputarr as $arr) {\r
-                                               $ret =& $this->_Execute($stmt,$arr);\r
-                                               if (!$ret) return $ret;\r
-                                       }\r
-                               } else\r
-                                       $ret =& $this->_Execute($sql,$inputarr);\r
-                       }\r
-               } else {\r
-                       $ret =& $this->_Execute($sql,false);\r
-               }\r
-\r
-               return $ret;\r
-       }\r
-       \r
-       function& _Execute($sql,$inputarr=false)\r
-       {\r
-               // debug version of query\r
-               if ($this->debug) {\r
-               global $HTTP_SERVER_VARS;\r
-                       $ss = '';\r
-                       if ($inputarr) {\r
-                               foreach($inputarr as $kk=>$vv) {\r
-                                       if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';\r
-                                       $ss .= "($kk=>'$vv') ";\r
-                               }\r
-                               $ss = "[ $ss ]";\r
-                       }\r
-                       $sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql);\r
-                       \r
-                       // check if running from browser or command-line\r
-                       $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);\r
-                       \r
-                       if ($inBrowser)\r
-                               if ($this->debug === -1)\r
-                               ADOConnection::outp( "<br>\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<br>\n",false);\r
-                               else ADOConnection::outp( "<hr />\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<hr />\n",false);\r
-                       else\r
-                               ADOConnection::outp(  "=----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false);\r
-                       \r
-                       $this->_queryID = $this->_query($sql,$inputarr);\r
-                       /* \r
-                               Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql\r
-                               because ErrorNo() calls Execute('SELECT @ERROR'), causing recure\r
-                       */\r
-                       if ($this->databaseType == 'mssql') { \r
-                       // ErrorNo is a slow function call in mssql, and not reliable\r
-                       // in PHP 4.0.6\r
-                               if($emsg = $this->ErrorMsg()) {\r
-                                       $err = $this->ErrorNo();\r
-                                       if ($err) {\r
-                                               ADOConnection::outp($err.': '.$emsg);\r
-                                       }\r
-                               }\r
-                       } else \r
-                               if (!$this->_queryID) {\r
-                                       $e = $this->ErrorNo();\r
-                                       $m = $this->ErrorMsg();\r
-                                       ADOConnection::outp($e .': '. $m );\r
-                               }\r
-               } else {\r
-                       // non-debug version of query\r
-                       \r
-                       $this->_queryID =@$this->_query($sql,$inputarr);\r
-               }\r
-               \r
-               /************************\r
-                       OK, query executed\r
-               *************************/\r
-               // error handling if query fails\r
-               if ($this->_queryID === false) {\r
-                       if ($this->debug == 99) adodb_backtrace(true,5);        \r
-                       $fn = $this->raiseErrorFn;\r
-                       if ($fn) {\r
-                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);\r
-                       } \r
-                               \r
-                       return false;\r
-               } else if ($this->_queryID === true) {\r
-               // return simplified empty recordset for inserts/updates/deletes with lower overhead\r
-                       $rs =& new ADORecordSet_empty();\r
-                       return $rs;\r
-               }\r
-               \r
-               // return real recordset from select statement\r
-               $rsclass = $this->rsPrefix.$this->databaseType;\r
-               $rs =& new $rsclass($this->_queryID,$this->fetchMode); // &new not supported by older PHP versions\r
-               $rs->connection = &$this; // Pablo suggestion\r
-               $rs->Init();\r
-               if (is_array($sql)) $rs->sql = $sql[0];\r
-               else $rs->sql = $sql;\r
-               if ($rs->_numOfRows <= 0) {\r
-               global $ADODB_COUNTRECS;\r
-       \r
-                       if ($ADODB_COUNTRECS) {\r
-                               if (!$rs->EOF){ \r
-                                       $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));\r
-                                       $rs->_queryID = $this->_queryID;\r
-                               } else\r
-                                       $rs->_numOfRows = 0;\r
-                       }\r
-               }\r
-               return $rs;\r
-       }\r
-\r
-       function CreateSequence($seqname='adodbseq',$startID=1)\r
-       {\r
-               if (empty($this->_genSeqSQL)) return false;\r
-               return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));\r
-       }\r
-\r
-       function DropSequence($seqname)\r
-       {\r
-               if (empty($this->_dropSeqSQL)) return false;\r
-               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));\r
-       }\r
-\r
-       /**\r
-        * Generates a sequence id and stores it in $this->genID;\r
-        * GenID is only available if $this->hasGenID = true;\r
-        *\r
-        * @param seqname               name of sequence to use\r
-        * @param startID               if sequence does not exist, start at this ID\r
-        * @return              0 if not supported, otherwise a sequence id\r
-        */\r
-       function GenID($seqname='adodbseq',$startID=1)\r
-       {\r
-               if (!$this->hasGenID) {\r
-                       return 0; // formerly returns false pre 1.60\r
-               }\r
-               \r
-               $getnext = sprintf($this->_genIDSQL,$seqname);\r
-               \r
-               $holdtransOK = $this->_transOK;\r
-               $rs = @$this->Execute($getnext);\r
-               if (!$rs) {\r
-                       $this->_transOK = $holdtransOK; //if the status was ok before reset\r
-                       $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));\r
-                       $rs = $this->Execute($getnext);\r
-               }\r
-               if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);\r
-               else $this->genID = 0; // false\r
-       \r
-               if ($rs) $rs->Close();\r
-\r
-               return $this->genID;\r
-       }       \r
-\r
-       /**\r
-        * @return  the last inserted ID. Not all databases support this.\r
-        */ \r
-       function Insert_ID()\r
-       {\r
-               if ($this->_logsql && $this->lastInsID) return $this->lastInsID;\r
-               if ($this->hasInsertID) return $this->_insertid();\r
-               if ($this->debug) {\r
-                       ADOConnection::outp( '<p>Insert_ID error</p>');\r
-                       adodb_backtrace();\r
-               }\r
-               return false;\r
-       }\r
-\r
-\r
-       /**\r
-        * Portable Insert ID. Pablo Roca <pabloroca@mvps.org>\r
-        *\r
-        * @return  the last inserted ID. All databases support this. But aware possible\r
-        * problems in multiuser environments. Heavy test this before deploying.\r
-        */ \r
-       function PO_Insert_ID($table="", $id="") \r
-       {\r
-          if ($this->hasInsertID){\r
-                  return $this->Insert_ID();\r
-          } else {\r
-                  return $this->GetOne("SELECT MAX($id) FROM $table");\r
-          }\r
-       }\r
-\r
-       /**\r
-       * @return # rows affected by UPDATE/DELETE\r
-       */ \r
-       function Affected_Rows()\r
-       {\r
-               if ($this->hasAffectedRows) {\r
-                       if ($this->fnExecute === 'adodb_log_sql') {\r
-                               if ($this->_logsql && $this->_affected !== false) return $this->_affected;\r
-                       }\r
-                       $val = $this->_affectedrows();\r
-                       return ($val < 0) ? false : $val;\r
-               }\r
-                                 \r
-               if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);\r
-               return false;\r
-       }\r
-       \r
-       \r
-       /**\r
-        * @return  the last error message\r
-        */\r
-       function ErrorMsg()\r
-       {\r
-               return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;\r
-       }\r
-       \r
-       \r
-       /**\r
-        * @return the last error number. Normally 0 means no error.\r
-        */\r
-       function ErrorNo() \r
-       {\r
-               return ($this->_errorMsg) ? -1 : 0;\r
-       }\r
-       \r
-       function MetaError($err=false)\r
-       {\r
-               include_once(ADODB_DIR."/adodb-error.inc.php");\r
-               if ($err === false) $err = $this->ErrorNo();\r
-               return adodb_error($this->dataProvider,$this->databaseType,$err);\r
-       }\r
-       \r
-       function MetaErrorMsg($errno)\r
-       {\r
-               include_once(ADODB_DIR."/adodb-error.inc.php");\r
-               return adodb_errormsg($errno);\r
-       }\r
-       \r
-       /**\r
-        * @returns an array with the primary key columns in it.\r
-        */\r
-       function MetaPrimaryKeys($table, $owner=false)\r
-       {\r
-       // owner not used in base class - see oci8\r
-               $p = array();\r
-               $objs =& $this->MetaColumns($table);\r
-               if ($objs) {\r
-                       foreach($objs as $v) {\r
-                               if (!empty($v->primary_key))\r
-                                       $p[] = $v->name;\r
-                       }\r
-               }\r
-               if (sizeof($p)) return $p;\r
-               if (function_exists('ADODB_VIEW_PRIMARYKEYS'))\r
-                       return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);\r
-               return false;\r
-       }\r
-       \r
-       /**\r
-        * @returns assoc array where keys are tables, and values are foreign keys\r
-        */\r
-       function MetaForeignKeys($table, $owner=false, $upper=false)\r
-       {\r
-               return false;\r
-       }\r
-       /**\r
-        * Choose a database to connect to. Many databases do not support this.\r
-        *\r
-        * @param dbName        is the name of the database to select\r
-        * @return              true or false\r
-        */\r
-       function SelectDB($dbName) \r
-       {return false;}\r
-       \r
-       \r
-       /**\r
-       * Will select, getting rows from $offset (1-based), for $nrows. \r
-       * This simulates the MySQL "select * from table limit $offset,$nrows" , and\r
-       * the PostgreSQL "select * from table limit $nrows offset $offset". Note that\r
-       * MySQL and PostgreSQL parameter ordering is the opposite of the other.\r
-       * eg. \r
-       *  SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)\r
-       *  SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)\r
-       *\r
-       * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)\r
-       * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set\r
-       *\r
-       * @param sql\r
-       * @param [offset]       is the row to start calculations from (1-based)\r
-       * @param [nrows]                is the number of rows to get\r
-       * @param [inputarr]     array of bind variables\r
-       * @param [secs2cache]           is a private parameter only used by jlim\r
-       * @return               the recordset ($rs->databaseType == 'array')\r
-       */\r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
-       {\r
-               if ($this->hasTop && $nrows > 0) {\r
-               // suggested by Reinhard Balling. Access requires top after distinct \r
-                // Informix requires first before distinct - F Riosa\r
-                       $ismssql = (strpos($this->databaseType,'mssql') !== false);\r
-                       if ($ismssql) $isaccess = false;\r
-                       else $isaccess = (strpos($this->databaseType,'access') !== false);\r
-                       \r
-                       if ($offset <= 0) {\r
-                               \r
-                                       // access includes ties in result\r
-                                       if ($isaccess) {\r
-                                               $sql = preg_replace(\r
-                                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);\r
-\r
-                                               if ($secs2cache>0) {\r
-                                                       $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);\r
-                                               } else {\r
-                                                       $ret =& $this->Execute($sql,$inputarr);\r
-                                               }\r
-                                               return $ret; // PHP5 fix\r
-                                       } else if ($ismssql){\r
-                                               $sql = preg_replace(\r
-                                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);\r
-                                       } else {\r
-                                               $sql = preg_replace(\r
-                                               '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);\r
-                                       }\r
-                       } else {\r
-                               $nn = $nrows + $offset;\r
-                               if ($isaccess || $ismssql) {\r
-                                       $sql = preg_replace(\r
-                                       '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);\r
-                               } else {\r
-                                       $sql = preg_replace(\r
-                                       '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);\r
-                               }\r
-                       }\r
-               }\r
-               \r
-               // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer  rows\r
-               // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.\r
-               global $ADODB_COUNTRECS;\r
-               \r
-               $savec = $ADODB_COUNTRECS;\r
-               $ADODB_COUNTRECS = false;\r
-                       \r
-               if ($offset>0){\r
-                       if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);\r
-                       else $rs = &$this->Execute($sql,$inputarr);\r
-               } else {\r
-                       if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);\r
-                       else $rs = &$this->Execute($sql,$inputarr);\r
-               }\r
-               $ADODB_COUNTRECS = $savec;\r
-               if ($rs && !$rs->EOF) {\r
-                       $rs =& $this->_rs2rs($rs,$nrows,$offset);\r
-               }\r
-               //print_r($rs);\r
-               return $rs;\r
-       }\r
-       \r
-       /**\r
-       * Create serializable recordset. Breaks rs link to connection.\r
-       *\r
-       * @param rs                     the recordset to serialize\r
-       */\r
-       function &SerializableRS(&$rs)\r
-       {\r
-               $rs2 =& $this->_rs2rs($rs);\r
-               $ignore = false;\r
-               $rs2->connection =& $ignore;\r
-               \r
-               return $rs2;\r
-       }\r
-       \r
-       /**\r
-       * Convert database recordset to an array recordset\r
-       * input recordset's cursor should be at beginning, and\r
-       * old $rs will be closed.\r
-       *\r
-       * @param rs                     the recordset to copy\r
-       * @param [nrows]        number of rows to retrieve (optional)\r
-       * @param [offset]       offset by number of rows (optional)\r
-       * @return                       the new recordset\r
-       */\r
-       function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)\r
-       {\r
-               if (! $rs) return false;\r
-               \r
-               $dbtype = $rs->databaseType;\r
-               if (!$dbtype) {\r
-                       $rs = &$rs;  // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?\r
-                       return $rs;\r
-               }\r
-               if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {\r
-                       $rs->MoveFirst();\r
-                       $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?\r
-                       return $rs;\r
-               }\r
-               $flds = array();\r
-               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {\r
-                       $flds[] = $rs->FetchField($i);\r
-               }\r
-               $arr =& $rs->GetArrayLimit($nrows,$offset);\r
-               //print_r($arr);\r
-               if ($close) $rs->Close();\r
-               \r
-               $arrayClass = $this->arrayClass;\r
-               \r
-               $rs2 =& new $arrayClass();\r
-               $rs2->connection = &$this;\r
-               $rs2->sql = $rs->sql;\r
-               $rs2->dataProvider = $this->dataProvider;\r
-               $rs2->InitArrayFields($arr,$flds);\r
-               return $rs2;\r
-       }\r
-       \r
-       /*\r
-       * Return all rows. Compat with PEAR DB\r
-       */\r
-       function &GetAll($sql, $inputarr=false)\r
-       {\r
-               $arr =& $this->GetArray($sql,$inputarr);\r
-               return $arr;\r
-       }\r
-       \r
-       function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)\r
-       {\r
-               $rs =& $this->Execute($sql, $inputarr);\r
-               if (!$rs) return false;\r
-               \r
-               $arr =& $rs->GetAssoc($force_array,$first2cols);\r
-               return $arr;\r
-       }\r
-       \r
-       function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)\r
-       {\r
-               if (!is_numeric($secs2cache)) {\r
-                       $first2cols = $force_array;\r
-                       $force_array = $inputarr;\r
-               }\r
-               $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);\r
-               if (!$rs) return false;\r
-               \r
-               $arr =& $rs->GetAssoc($force_array,$first2cols);\r
-               return $arr;\r
-       }\r
-       \r
-       /**\r
-       * Return first element of first row of sql statement. Recordset is disposed\r
-       * for you.\r
-       *\r
-       * @param sql                    SQL statement\r
-       * @param [inputarr]             input bind array\r
-       */\r
-       function GetOne($sql,$inputarr=false)\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-               $crecs = $ADODB_COUNTRECS;\r
-               $ADODB_COUNTRECS = false;\r
-               \r
-               $ret = false;\r
-               $rs = &$this->Execute($sql,$inputarr);\r
-               if ($rs) {              \r
-                       if (!$rs->EOF) $ret = reset($rs->fields);\r
-                       $rs->Close();\r
-               } \r
-               $ADODB_COUNTRECS = $crecs;\r
-               return $ret;\r
-       }\r
-       \r
-       function CacheGetOne($secs2cache,$sql=false,$inputarr=false)\r
-       {\r
-               $ret = false;\r
-               $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);\r
-               if ($rs) {              \r
-                       if (!$rs->EOF) $ret = reset($rs->fields);\r
-                       $rs->Close();\r
-               } \r
-               \r
-               return $ret;\r
-       }\r
-       \r
-       function GetCol($sql, $inputarr = false, $trim = false)\r
-       {\r
-               $rv = false;\r
-               $rs = &$this->Execute($sql, $inputarr);\r
-               if ($rs) {\r
-                       $rv = array();\r
-                       if ($trim) {\r
-                               while (!$rs->EOF) {\r
-                                       $rv[] = trim(reset($rs->fields));\r
-                                       $rs->MoveNext();\r
-                               }\r
-                       } else {\r
-                               while (!$rs->EOF) {\r
-                                       $rv[] = reset($rs->fields);\r
-                                       $rs->MoveNext();\r
-                               }\r
-                       }\r
-                       $rs->Close();\r
-               }\r
-               return $rv;\r
-       }\r
-       \r
-       function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)\r
-       {\r
-               $rv = false;\r
-               $rs = &$this->CacheExecute($secs, $sql, $inputarr);\r
-               if ($rs) {\r
-                       if ($trim) {\r
-                               while (!$rs->EOF) {\r
-                                       $rv[] = trim(reset($rs->fields));\r
-                                       $rs->MoveNext();\r
-                               }\r
-                       } else {\r
-                               while (!$rs->EOF) {\r
-                                       $rv[] = reset($rs->fields);\r
-                                       $rs->MoveNext();\r
-                               }\r
-                       }\r
-                       $rs->Close();\r
-               }\r
-               return $rv;\r
-       }\r
\r
-       /*\r
-               Calculate the offset of a date for a particular database and generate\r
-                       appropriate SQL. Useful for calculating future/past dates and storing\r
-                       in a database.\r
-                       \r
-               If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.\r
-       */\r
-       function OffsetDate($dayFraction,$date=false)\r
-       {               \r
-               if (!$date) $date = $this->sysDate;\r
-               return  '('.$date.'+'.$dayFraction.')';\r
-       }\r
-       \r
-       \r
-       /**\r
-       *\r
-       * @param sql                    SQL statement\r
-       * @param [inputarr]             input bind array\r
-       */\r
-       function &GetArray($sql,$inputarr=false)\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-               \r
-               $savec = $ADODB_COUNTRECS;\r
-               $ADODB_COUNTRECS = false;\r
-               $rs =& $this->Execute($sql,$inputarr);\r
-               $ADODB_COUNTRECS = $savec;\r
-               if (!$rs) \r
-                       if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
-                       else return false;\r
-               $arr =& $rs->GetArray();\r
-               $rs->Close();\r
-               return $arr;\r
-       }\r
-       \r
-       function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-               \r
-               $savec = $ADODB_COUNTRECS;\r
-               $ADODB_COUNTRECS = false;\r
-               $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);\r
-               $ADODB_COUNTRECS = $savec;\r
-               \r
-               if (!$rs) \r
-                       if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();\r
-                       else return false;\r
-               \r
-               $arr =& $rs->GetArray();\r
-               $rs->Close();\r
-               return $arr;\r
-       }\r
-       \r
-       \r
-       \r
-       /**\r
-       * Return one row of sql statement. Recordset is disposed for you.\r
-       *\r
-       * @param sql                    SQL statement\r
-       * @param [inputarr]             input bind array\r
-       */\r
-       function &GetRow($sql,$inputarr=false)\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-               $crecs = $ADODB_COUNTRECS;\r
-               $ADODB_COUNTRECS = false;\r
-               \r
-               $rs =& $this->Execute($sql,$inputarr);\r
-               \r
-               $ADODB_COUNTRECS = $crecs;\r
-               if ($rs) {\r
-                       if (!$rs->EOF) $arr = $rs->fields;\r
-                       else $arr = array();\r
-                       $rs->Close();\r
-                       return $arr;\r
-               }\r
-               \r
-               return false;\r
-       }\r
-       \r
-       function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)\r
-       {\r
-               $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);\r
-               if ($rs) {\r
-                       $arr = false;\r
-                       if (!$rs->EOF) $arr = $rs->fields;\r
-                       $rs->Close();\r
-                       return $arr;\r
-               }\r
-               return false;\r
-       }\r
-       \r
-       /**\r
-       * Insert or replace a single record. Note: this is not the same as MySQL's replace. \r
-       * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.\r
-       * Also note that no table locking is done currently, so it is possible that the\r
-       * record be inserted twice by two programs...\r
-       *\r
-       * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');\r
-       *\r
-       * $table                table name\r
-       * $fieldArray   associative array of data (you must quote strings yourself).\r
-       * $keyCol               the primary key field name or if compound key, array of field names\r
-       * autoQuote             set to true to use a hueristic to quote strings. Works with nulls and numbers\r
-       *                                       but does not work with dates nor SQL functions.\r
-       * has_autoinc   the primary key is an auto-inc field, so skip in insert.\r
-       *\r
-       * Currently blob replace not supported\r
-       *\r
-       * returns 0 = fail, 1 = update, 2 = insert \r
-       */\r
-       \r
-       function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)\r
-       {\r
-               global $ADODB_INCLUDED_LIB;\r
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
-               \r
-               return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);\r
-       }\r
-       \r
-       \r
-       /**\r
-       * Will select, getting rows from $offset (1-based), for $nrows. \r
-       * This simulates the MySQL "select * from table limit $offset,$nrows" , and\r
-       * the PostgreSQL "select * from table limit $nrows offset $offset". Note that\r
-       * MySQL and PostgreSQL parameter ordering is the opposite of the other.\r
-       * eg. \r
-       *  CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)\r
-       *  CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)\r
-       *\r
-       * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set\r
-       *\r
-       * @param [secs2cache]   seconds to cache data, set to 0 to force query. This is optional\r
-       * @param sql\r
-       * @param [offset]       is the row to start calculations from (1-based)\r
-       * @param [nrows]        is the number of rows to get\r
-       * @param [inputarr]     array of bind variables\r
-       * @return               the recordset ($rs->databaseType == 'array')\r
-       */\r
-       function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)\r
-       {       \r
-               if (!is_numeric($secs2cache)) {\r
-                       if ($sql === false) $sql = -1;\r
-                       if ($offset == -1) $offset = false;\r
-                                                                         // sql,       nrows, offset,inputarr\r
-                       $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);\r
-               } else {\r
-                       if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");\r
-                       $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
-               }\r
-               return $rs;\r
-       }\r
-       \r
-       /**\r
-       * Flush cached recordsets that match a particular $sql statement. \r
-       * If $sql == false, then we purge all files in the cache.\r
-       */\r
-       function CacheFlush($sql=false,$inputarr=false)\r
-       {\r
-       global $ADODB_CACHE_DIR;\r
-       \r
-               if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {\r
-                       if (strncmp(PHP_OS,'WIN',3) === 0) {\r
-                               $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';\r
-                       } else {\r
-                               $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache'; \r
-                               // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';\r
-                       }\r
-                       if ($this->debug) {\r
-                               ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");\r
-                       } else {\r
-                               exec($cmd);\r
-                       }\r
-                       return;\r
-               } \r
-               $f = $this->_gencachename($sql.serialize($inputarr),false);\r
-               adodb_write_file($f,''); // is adodb_write_file needed?\r
-               if (!@unlink($f)) {\r
-                       if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");\r
-               }\r
-       }\r
-       \r
-       /**\r
-       * Private function to generate filename for caching.\r
-       * Filename is generated based on:\r
-       *\r
-       *  - sql statement\r
-       *  - database type (oci8, ibase, ifx, etc)\r
-       *  - database name\r
-       *  - userid\r
-       *\r
-       * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). \r
-       * Assuming that we can have 50,000 files per directory with good performance, \r
-       * then we can scale to 12.8 million unique cached recordsets. Wow!\r
-       */\r
-       function _gencachename($sql,$createdir)\r
-       {\r
-       global $ADODB_CACHE_DIR;\r
-               \r
-               $m = md5($sql.$this->databaseType.$this->database.$this->user);\r
-               $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2);\r
-               if ($createdir && !file_exists($dir)) {\r
-                       $oldu = umask(0);\r
-                       if (!mkdir($dir,0771)) \r
-                               if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");\r
-                       umask($oldu);\r
-               }\r
-               return $dir.'/adodb_'.$m.'.cache';\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Execute SQL, caching recordsets.\r
-        *\r
-        * @param [secs2cache]  seconds to cache data, set to 0 to force query. \r
-        *                                        This is an optional parameter.\r
-        * @param sql           SQL statement to execute\r
-        * @param [inputarr]    holds the input data  to bind to\r
-        * @return              RecordSet or false\r
-        */\r
-       function &CacheExecute($secs2cache,$sql=false,$inputarr=false)\r
-       {\r
-               if (!is_numeric($secs2cache)) {\r
-                       $inputarr = $sql;\r
-                       $sql = $secs2cache;\r
-                       $secs2cache = $this->cacheSecs;\r
-               }\r
-               global $ADODB_INCLUDED_CSV;\r
-               if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');\r
-               \r
-               if (is_array($sql)) $sql = $sql[0];\r
-                       \r
-               $md5file = $this->_gencachename($sql.serialize($inputarr),true);\r
-               $err = '';\r
-               \r
-               if ($secs2cache > 0){\r
-                       $rs = &csv2rs($md5file,$err,$secs2cache);\r
-                       $this->numCacheHits += 1;\r
-               } else {\r
-                       $err='Timeout 1';\r
-                       $rs = false;\r
-                       $this->numCacheMisses += 1;\r
-               }\r
-               if (!$rs) {\r
-               // no cached rs found\r
-                       if ($this->debug) {\r
-                               if (get_magic_quotes_runtime()) {\r
-                                       ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");\r
-                               }\r
-                               if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");\r
-                       }\r
-                       $rs = &$this->Execute($sql,$inputarr);\r
-                       if ($rs) {\r
-                               $eof = $rs->EOF;\r
-                               $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately\r
-                               $txt = _rs2serialize($rs,false,$sql); // serialize\r
-               \r
-                               if (!adodb_write_file($md5file,$txt,$this->debug)) {\r
-                                       if ($fn = $this->raiseErrorFn) {\r
-                                               $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);\r
-                                       }\r
-                                       if ($this->debug) ADOConnection::outp( " Cache write error");\r
-                               }\r
-                               if ($rs->EOF && !$eof) {\r
-                                       $rs->MoveFirst();\r
-                                       //$rs = &csv2rs($md5file,$err);         \r
-                                       $rs->connection = &$this; // Pablo suggestion\r
-                               }  \r
-                               \r
-                       } else\r
-                               @unlink($md5file);\r
-               } else {\r
-                       $this->_errorMsg = '';\r
-                       $this->_errorCode = 0;\r
-                       \r
-                       if ($this->fnCacheExecute) {\r
-                               $fn = $this->fnCacheExecute;\r
-                               $fn($this, $secs2cache, $sql, $inputarr);\r
-                       }\r
-               // ok, set cached object found\r
-                       $rs->connection = &$this; // Pablo suggestion\r
-                       if ($this->debug){ \r
-                       global $HTTP_SERVER_VARS;\r
-                                       \r
-                               $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);\r
-                               $ttl = $rs->timeCreated + $secs2cache - time();\r
-                               $s = is_array($sql) ? $sql[0] : $sql;\r
-                               if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';\r
-                               \r
-                               ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");\r
-                       }\r
-               }\r
-               return $rs;\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Generates an Update Query based on an existing recordset.\r
-        * $arrFields is an associative array of fields with the value\r
-        * that should be assigned.\r
-        *\r
-        * Note: This function should only be used on a recordset\r
-        *         that is run against a single table and sql should only \r
-        *               be a simple select stmt with no groupby/orderby/limit\r
-        *\r
-        * "Jonathan Younger" <jyounger@unilab.com>\r
-        */\r
-       function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false)\r
-       {\r
-               global $ADODB_INCLUDED_LIB;\r
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
-               return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq);\r
-       }\r
-\r
-\r
-       /**\r
-        * Generates an Insert Query based on an existing recordset.\r
-        * $arrFields is an associative array of fields with the value\r
-        * that should be assigned.\r
-        *\r
-        * Note: This function should only be used on a recordset\r
-        *         that is run against a single table.\r
-        */\r
-       function GetInsertSQL(&$rs, $arrFields,$magicq=false)\r
-       {       \r
-               global $ADODB_INCLUDED_LIB;\r
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
-               return _adodb_getinsertsql($this,$rs,$arrFields,$magicq);\r
-       }\r
-       \r
-\r
-       /**\r
-       * Update a blob column, given a where clause. There are more sophisticated\r
-       * blob handling functions that we could have implemented, but all require\r
-       * a very complex API. Instead we have chosen something that is extremely\r
-       * simple to understand and use. \r
-       *\r
-       * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.\r
-       *\r
-       * Usage to update a $blobvalue which has a primary key blob_id=1 into a \r
-       * field blobtable.blobcolumn:\r
-       *\r
-       *       UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');\r
-       *\r
-       * Insert example:\r
-       *\r
-       *       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
-       *       $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
-       */\r
-       \r
-       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
-       {\r
-               return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;\r
-       }\r
-\r
-       /**\r
-       * Usage:\r
-       *       UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');\r
-       *       \r
-       *       $blobtype supports 'BLOB' and 'CLOB'\r
-       *\r
-       *       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
-       *       $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');\r
-       */\r
-       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')\r
-       {\r
-               $fd = fopen($path,'rb');\r
-               if ($fd === false) return false;\r
-               $val = fread($fd,filesize($path));\r
-               fclose($fd);\r
-               return $this->UpdateBlob($table,$column,$val,$where,$blobtype);\r
-       }\r
-       \r
-       function BlobDecode($blob)\r
-       {\r
-               return $blob;\r
-       }\r
-       \r
-       function BlobEncode($blob)\r
-       {\r
-               return $blob;\r
-       }\r
-       \r
-       function SetCharSet($charset)\r
-       {\r
-               return false;\r
-       }\r
-       \r
-       function IfNull( $field, $ifNull ) \r
-       {\r
-               return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";\r
-       }\r
-       \r
-       function LogSQL($enable=true)\r
-       {\r
-               include_once(ADODB_DIR.'/adodb-perf.inc.php');\r
-               \r
-               if ($enable) $this->fnExecute = 'adodb_log_sql';\r
-               else $this->fnExecute = false;\r
-               \r
-               $old = $this->_logsql;  \r
-               $this->_logsql = $enable;\r
-               if ($enable && !$old) $this->_affected = false;\r
-               return $old;\r
-       }\r
-       \r
-       function GetCharSet()\r
-       {\r
-               return false;\r
-       }\r
-       \r
-       /**\r
-       * Usage:\r
-       *       UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');\r
-       *\r
-       *       $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');\r
-       *       $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');\r
-       */\r
-       function UpdateClob($table,$column,$val,$where)\r
-       {\r
-               return $this->UpdateBlob($table,$column,$val,$where,'CLOB');\r
-       }\r
-       \r
-       \r
-       /**\r
-       *  Change the SQL connection locale to a specified locale.\r
-       *  This is used to get the date formats written depending on the client locale.\r
-       */\r
-       function SetDateLocale($locale = 'En')\r
-       {\r
-               $this->locale = $locale;\r
-               switch ($locale)\r
-               {\r
-                       default:\r
-                       case 'En':\r
-                               $this->fmtDate="Y-m-d";\r
-                               $this->fmtTimeStamp = "Y-m-d H:i:s";\r
-                               break;\r
-       \r
-                       case 'Fr':\r
-                       case 'Ro':\r
-                       case 'It':\r
-                               $this->fmtDate="d-m-Y";\r
-                               $this->fmtTimeStamp = "d-m-Y H:i:s";\r
-                               break;\r
-                               \r
-                       case 'Ge':\r
-                               $this->fmtDate="d.m.Y";\r
-                               $this->fmtTimeStamp = "d.m.Y H:i:s";\r
-                               break;\r
-               }\r
-       }\r
-       \r
-       \r
-       /**\r
-        *  $meta       contains the desired type, which could be...\r
-        *      C for character. You will have to define the precision yourself.\r
-        *      X for teXt. For unlimited character lengths.\r
-        *      B for Binary\r
-        *  F for floating point, with no need to define scale and precision\r
-        *      N for decimal numbers, you will have to define the (scale, precision) yourself\r
-        *      D for date\r
-        *      T for timestamp\r
-        *      L for logical/Boolean\r
-        *      I for integer\r
-        *      R for autoincrement counter/integer\r
-        *  and if you want to use double-byte, add a 2 to the end, like C2 or X2.\r
-        * \r
-        *\r
-        * @return the actual type of the data or false if no such type available\r
-       */\r
-       function ActualType($meta)\r
-       {\r
-               switch($meta) {\r
-               case 'C':\r
-               case 'X':\r
-                       return 'VARCHAR';\r
-               case 'B':\r
-                       \r
-               case 'D':\r
-               case 'T':\r
-               case 'L':\r
-               \r
-               case 'R':\r
-                       \r
-               case 'I':\r
-               case 'N':\r
-                       return false;\r
-               }\r
-       }\r
-\r
-       \r
-       /**\r
-        * Close Connection\r
-        */\r
-       function Close() \r
-       {\r
-               return $this->_close();\r
-               \r
-               // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need \r
-               // to be closed too!\r
-               //if ($this->_isPersistentConnection != true) return $this->_close();\r
-               //else return true;     \r
-       }\r
-       \r
-       /**\r
-        * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().\r
-        *\r
-        * @return true if succeeded or false if database does not support transactions\r
-        */\r
-       function BeginTrans() {return false;}\r
-       \r
-       \r
-       /**\r
-        * If database does not support transactions, always return true as data always commited\r
-        *\r
-        * @param $ok  set to false to rollback transaction, true to commit\r
-        *\r
-        * @return true/false.\r
-        */\r
-       function CommitTrans($ok=true) \r
-       { return true;}\r
-       \r
-       \r
-       /**\r
-        * If database does not support transactions, rollbacks always fail, so return false\r
-        *\r
-        * @return true/false.\r
-        */\r
-       function RollbackTrans() \r
-       { return false;}\r
-\r
-\r
-       /**\r
-        * return the databases that the driver can connect to. \r
-        * Some databases will return an empty array.\r
-        *\r
-        * @return an array of database names.\r
-        */\r
-               function MetaDatabases() \r
-               {\r
-               global $ADODB_FETCH_MODE;\r
-               \r
-                       if ($this->metaDatabasesSQL) {\r
-                               $save = $ADODB_FETCH_MODE; \r
-                               $ADODB_FETCH_MODE = ADODB_FETCH_NUM; \r
-                               \r
-                               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
-                               \r
-                               $arr = $this->GetCol($this->metaDatabasesSQL);\r
-                               if (isset($savem)) $this->SetFetchMode($savem);\r
-                               $ADODB_FETCH_MODE = $save; \r
-                       \r
-                               return $arr;\r
-                       }\r
-                       \r
-                       return false;\r
-               }\r
-               \r
-       /**\r
-        * @param ttype can either be 'VIEW' or 'TABLE' or false. \r
-        *              If false, both views and tables are returned.\r
-        *              "VIEW" returns only views\r
-        *              "TABLE" returns only tables\r
-        * @param showSchema returns the schema/user with the table name, eg. USER.TABLE\r
-        * @param mask  is the input mask - only supported by oci8 and postgresql\r
-        *\r
-        * @return  array of tables for current database.\r
-        */ \r
-       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               if ($mask) return false;\r
-               \r
-               if ($this->metaTablesSQL) {\r
-                       // complicated state saving by the need for backward compat\r
-                       $save = $ADODB_FETCH_MODE; \r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM; \r
-                       \r
-                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
-                       \r
-                       $rs = $this->Execute($this->metaTablesSQL);\r
-                       if (isset($savem)) $this->SetFetchMode($savem);\r
-                       $ADODB_FETCH_MODE = $save; \r
-                       \r
-                       if ($rs === false) return false;\r
-                       $arr =& $rs->GetArray();\r
-                       $arr2 = array();\r
-                       \r
-                       if ($hast = ($ttype && isset($arr[0][1]))) { \r
-                               $showt = strncmp($ttype,'T',1);\r
-                       }\r
-                       \r
-                       for ($i=0; $i < sizeof($arr); $i++) {\r
-                               if ($hast) {\r
-                                       if ($showt == 0) {\r
-                                               if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);\r
-                                       } else {\r
-                                               if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);\r
-                                       }\r
-                               } else\r
-                                       $arr2[] = trim($arr[$i][0]);\r
-                       }\r
-                       $rs->Close();\r
-                       return $arr2;\r
-               }\r
-               return false;\r
-       }\r
-       \r
-       \r
-       function _findschema(&$table,&$schema)\r
-       {\r
-               if (!$schema && ($at = strpos($table,'.')) !== false) {\r
-                       $schema = substr($table,0,$at);\r
-                       $table = substr($table,$at+1);\r
-               }\r
-       }\r
-       \r
-       /**\r
-        * List columns in a database as an array of ADOFieldObjects. \r
-        * See top of file for definition of object.\r
-        *\r
-        * @param table table name to query\r
-        * @param upper uppercase table name (required by some databases)\r
-        * @schema is optional database schema to use - not supported by all databases.\r
-        *\r
-        * @return  array of ADOFieldObjects for current table.\r
-        */\r
-       function &MetaColumns($table,$upper=true) \r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-               \r
-               if (!empty($this->metaColumnsSQL)) {\r
-               \r
-                       $schema = false;\r
-                       $this->_findschema($table,$schema);\r
-               \r
-                       $save = $ADODB_FETCH_MODE;\r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table));\r
-                       if (isset($savem)) $this->SetFetchMode($savem);\r
-                       $ADODB_FETCH_MODE = $save;\r
-                       if ($rs === false) return false;\r
-\r
-                       $retarr = array();\r
-                       while (!$rs->EOF) { //print_r($rs->fields);\r
-                               $fld =& new ADOFieldObject();\r
-                               $fld->name = $rs->fields[0];\r
-                               $fld->type = $rs->fields[1];\r
-                               if (isset($rs->fields[3]) && $rs->fields[3]) {\r
-                                       if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];\r
-                                       $fld->scale = $rs->fields[4];\r
-                                       if ($fld->scale>0) $fld->max_length += 1;\r
-                               } else\r
-                                       $fld->max_length = $rs->fields[2];\r
-                                       \r
-                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
-                               else $retarr[strtoupper($fld->name)] = $fld;\r
-                               $rs->MoveNext();\r
-                       }\r
-                       $rs->Close();\r
-                       return $retarr; \r
-               }\r
-               return false;\r
-       }\r
-       \r
-    /**\r
-      * List indexes on a table as an array.\r
-      * @param table        table name to query\r
-      * @param primary include primary keys.\r
-         *\r
-      * @return array of indexes on current table.\r
-      */\r
-     function &MetaIndexes($table, $primary = false, $owner = false)\r
-     {\r
-             return FALSE;\r
-     }\r
-\r
-       /**\r
-        * List columns names in a table as an array. \r
-        * @param table table name to query\r
-        *\r
-        * @return  array of column names for current table.\r
-        */ \r
-       function &MetaColumnNames($table) \r
-       {\r
-               $objarr =& $this->MetaColumns($table);\r
-               if (!is_array($objarr)) return false;\r
-               \r
-               $arr = array();\r
-               foreach($objarr as $v) {\r
-                       $arr[] = $v->name;\r
-               }\r
-               return $arr;\r
-       }\r
-                       \r
-       /**\r
-        * Different SQL databases used different methods to combine strings together.\r
-        * This function provides a wrapper. \r
-        * \r
-        * param s      variable number of string parameters\r
-        *\r
-        * Usage: $db->Concat($str1,$str2);\r
-        * \r
-        * @return concatenated string\r
-        */      \r
-       function Concat()\r
-       {       \r
-               $arr = func_get_args();\r
-               return implode($this->concat_operator, $arr);\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Converts a date "d" to a string that the database can understand.\r
-        *\r
-        * @param d     a date in Unix date time format.\r
-        *\r
-        * @return  date string in database date format\r
-        */\r
-       function DBDate($d)\r
-       {\r
-               if (empty($d) && $d !== 0) return 'null';\r
-\r
-               if (is_string($d) && !is_numeric($d)) {\r
-                       if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;\r
-                       if ($this->isoDates) return "'$d'";\r
-                       $d = ADOConnection::UnixDate($d);\r
-               }\r
-\r
-               return adodb_date($this->fmtDate,$d);\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Converts a timestamp "ts" to a string that the database can understand.\r
-        *\r
-        * @param ts    a timestamp in Unix date time format.\r
-        *\r
-        * @return  timestamp string in database timestamp format\r
-        */\r
-       function DBTimeStamp($ts)\r
-       {\r
-               if (empty($ts) && $ts !== 0) return 'null';\r
-\r
-               # strlen(14) allows YYYYMMDDHHMMSS format\r
-               if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) \r
-                       return adodb_date($this->fmtTimeStamp,$ts);\r
-               \r
-               if ($ts === 'null') return $ts;\r
-               if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";\r
-               \r
-               $ts = ADOConnection::UnixTimeStamp($ts);\r
-               return adodb_date($this->fmtTimeStamp,$ts);\r
-       }\r
-       \r
-       /**\r
-        * Also in ADORecordSet.\r
-        * @param $v is a date string in YYYY-MM-DD format\r
-        *\r
-        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format\r
-        */\r
-       function UnixDate($v)\r
-       {\r
-               if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", \r
-                       ($v), $rr)) return false;\r
-\r
-               if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;\r
-               // h-m-s-MM-DD-YY\r
-               return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);\r
-       }\r
-       \r
-\r
-       /**\r
-        * Also in ADORecordSet.\r
-        * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format\r
-        *\r
-        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format\r
-        */\r
-       function UnixTimeStamp($v)\r
-       {\r
-               if (!preg_match( \r
-                       "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", \r
-                       ($v), $rr)) return false;\r
-                       \r
-               if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;\r
-       \r
-               // h-m-s-MM-DD-YY\r
-               if (!isset($rr[5])) return  adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);\r
-               return  @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);\r
-       }\r
-       \r
-       /**\r
-        * Also in ADORecordSet.\r
-        *\r
-        * Format database date based on user defined format.\r
-        *\r
-        * @param v     is the character date in YYYY-MM-DD format, returned by database\r
-        * @param fmt   is the format to apply to it, using date()\r
-        *\r
-        * @return a date formated as user desires\r
-        */\r
-        \r
-       function UserDate($v,$fmt='Y-m-d')\r
-       {\r
-               $tt = $this->UnixDate($v);\r
-               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR\r
-               if (($tt === false || $tt == -1) && $v != false) return $v;\r
-               else if ($tt == 0) return $this->emptyDate;\r
-               else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR\r
-               }\r
-               \r
-               return adodb_date($fmt,$tt);\r
-       \r
-       }\r
-       \r
-               /**\r
-        *\r
-        * @param v     is the character timestamp in YYYY-MM-DD hh:mm:ss format\r
-        * @param fmt   is the format to apply to it, using date()\r
-        *\r
-        * @return a timestamp formated as user desires\r
-        */\r
-       function UserTimeStamp($v,$fmt='Y-m-d H:i:s')\r
-       {\r
-               # strlen(14) allows YYYYMMDDHHMMSS format\r
-               if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);\r
-               $tt = $this->UnixTimeStamp($v);\r
-               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR\r
-               if (($tt === false || $tt == -1) && $v != false) return $v;\r
-               if ($tt == 0) return $this->emptyTimeStamp;\r
-               return adodb_date($fmt,$tt);\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Correctly quotes a string so that all strings are escaped. We prefix and append\r
-        * to the string single-quotes.\r
-        * An example is  $db->qstr("Don't bother",magic_quotes_runtime());\r
-        * \r
-        * @param s                     the string to quote\r
-        * @param [magic_quotes]        if $s is GET/POST var, set to get_magic_quotes_gpc().\r
-        *                              This undoes the stupidity of magic quotes for GPC.\r
-        *\r
-        * @return  quoted string to be sent back to database\r
-        */\r
-       function qstr($s,$magic_quotes=false)\r
-       {       \r
-               if (!$magic_quotes) {\r
-               \r
-                       if ($this->replaceQuote[0] == '\\'){\r
-                               // only since php 4.0.5\r
-                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);\r
-                               //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));\r
-                       }\r
-                       return  "'".str_replace("'",$this->replaceQuote,$s)."'";\r
-               }\r
-               \r
-               // undo magic quotes for "\r
-               $s = str_replace('\\"','"',$s);\r
-               \r
-               if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything\r
-                       return "'$s'";\r
-               else {// change \' to '' for sybase/mssql\r
-                       $s = str_replace('\\\\','\\',$s);\r
-                       return "'".str_replace("\\'",$this->replaceQuote,$s)."'";\r
-               }\r
-       }\r
-       \r
-       \r
-       /**\r
-       * Will select the supplied $page number from a recordset, given that it is paginated in pages of \r
-       * $nrows rows per page. It also saves two boolean values saying if the given page is the first \r
-       * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.\r
-       *\r
-       * See readme.htm#ex8 for an example of usage.\r
-       *\r
-       * @param sql\r
-       * @param nrows          is the number of rows per page to get\r
-       * @param page           is the page number to get (1-based)\r
-       * @param [inputarr]     array of bind variables\r
-       * @param [secs2cache]           is a private parameter only used by jlim\r
-       * @return               the recordset ($rs->databaseType == 'array')\r
-       *\r
-       * NOTE: phpLens uses a different algorithm and does not use PageExecute().\r
-       *\r
-       */\r
-       function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) \r
-       {\r
-               global $ADODB_INCLUDED_LIB;\r
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
-               if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);\r
-               return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);\r
-\r
-       }\r
-       \r
-               \r
-       /**\r
-       * Will select the supplied $page number from a recordset, given that it is paginated in pages of \r
-       * $nrows rows per page. It also saves two boolean values saying if the given page is the first \r
-       * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.\r
-       *\r
-       * @param secs2cache     seconds to cache data, set to 0 to force query\r
-       * @param sql\r
-       * @param nrows          is the number of rows per page to get\r
-       * @param page           is the page number to get (1-based)\r
-       * @param [inputarr]     array of bind variables\r
-       * @return               the recordset ($rs->databaseType == 'array')\r
-       */\r
-       function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) \r
-       {\r
-               /*switch($this->dataProvider) {\r
-               case 'postgres':\r
-               case 'mysql': \r
-                       break;\r
-               default: $secs2cache = 0; break;\r
-               }*/\r
-               $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);\r
-               return $rs;\r
-       }\r
-\r
-} // end class ADOConnection\r
-       \r
-       \r
-       \r
-       //==============================================================================================        \r
-       // CLASS ADOFetchObj\r
-       //==============================================================================================        \r
-               \r
-       /**\r
-       * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().\r
-       */\r
-       class ADOFetchObj {\r
-       };\r
-       \r
-       //==============================================================================================        \r
-       // CLASS ADORecordSet_empty\r
-       //==============================================================================================        \r
-       \r
-       /**\r
-       * Lightweight recordset when there are no records to be returned\r
-       */\r
-       class ADORecordSet_empty\r
-       {\r
-               var $dataProvider = 'empty';\r
-               var $databaseType = false;\r
-               var $EOF = true;\r
-               var $_numOfRows = 0;\r
-               var $fields = false;\r
-               var $connection = false;\r
-               function RowCount() {return 0;}\r
-               function RecordCount() {return 0;}\r
-               function PO_RecordCount(){return 0;}\r
-               function Close(){return true;}\r
-               function FetchRow() {return false;}\r
-               function FieldCount(){ return 0;}\r
-       }\r
-       \r
-       //==============================================================================================        \r
-       // DATE AND TIME FUNCTIONS\r
-       //==============================================================================================        \r
-       include_once(ADODB_DIR.'/adodb-time.inc.php');\r
-       \r
-       //==============================================================================================        \r
-       // CLASS ADORecordSet\r
-       //==============================================================================================        \r
-\r
-       if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');\r
-       else include_once(ADODB_DIR.'/adodb-iterator.inc.php');\r
-   /**\r
-        * RecordSet class that represents the dataset returned by the database.\r
-        * To keep memory overhead low, this class holds only the current row in memory.\r
-        * No prefetching of data is done, so the RecordCount() can return -1 ( which\r
-        * means recordcount not known).\r
-        */\r
-       class ADORecordSet extends ADODB_BASE_RS {\r
-       /*\r
-        * public variables     \r
-        */\r
-       var $dataProvider = "native";\r
-       var $fields = false;    /// holds the current row data\r
-       var $blobSize = 100;    /// any varchar/char field this size or greater is treated as a blob\r
-                                                       /// in other words, we use a text area for editing.\r
-       var $canSeek = false;   /// indicates that seek is supported\r
-       var $sql;                               /// sql text\r
-       var $EOF = false;               /// Indicates that the current record position is after the last record in a Recordset object. \r
-       \r
-       var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0\r
-       var $emptyDate = '&nbsp;'; /// what to display when $time==0\r
-       var $debug = false;\r
-       var $timeCreated=0;     /// datetime in Unix format rs created -- for cached recordsets\r
-\r
-       var $bind = false;              /// used by Fields() to hold array - should be private?\r
-       var $fetchMode;                 /// default fetch mode\r
-       var $connection = false; /// the parent connection\r
-       /*\r
-        *      private variables       \r
-        */\r
-       var $_numOfRows = -1;   /** number of rows, or -1 */\r
-       var $_numOfFields = -1; /** number of fields in recordset */\r
-       var $_queryID = -1;             /** This variable keeps the result link identifier.     */\r
-       var $_currentRow = -1;  /** This variable keeps the current row in the Recordset.       */\r
-       var $_closed = false;   /** has recordset been closed */\r
-       var $_inited = false;   /** Init() should only be called once */\r
-       var $_obj;                              /** Used by FetchObj */\r
-       var $_names;                    /** Used by FetchObj */\r
-       \r
-       var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */\r
-       var $_atFirstPage = false;      /** Added by Iván Oliva to implement recordset pagination */\r
-       var $_atLastPage = false;       /** Added by Iván Oliva to implement recordset pagination */\r
-       var $_lastPageNo = -1; \r
-       var $_maxRecordCount = 0;\r
-       var $dateHasTime = false;\r
-       \r
-       /**\r
-        * Constructor\r
-        *\r
-        * @param queryID       this is the queryID returned by ADOConnection->_query()\r
-        *\r
-        */\r
-       function ADORecordSet($queryID) \r
-       {\r
-               $this->_queryID = $queryID;\r
-       }\r
-       \r
-       \r
-       \r
-       function Init()\r
-       {\r
-               if ($this->_inited) return;\r
-               $this->_inited = true;\r
-               if ($this->_queryID) @$this->_initrs();\r
-               else {\r
-                       $this->_numOfRows = 0;\r
-                       $this->_numOfFields = 0;\r
-               }\r
-               if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {\r
-                       \r
-                       $this->_currentRow = 0;\r
-                       if ($this->EOF = ($this->_fetch() === false)) {\r
-                               $this->_numOfRows = 0; // _numOfRows could be -1\r
-                       }\r
-               } else {\r
-                       $this->EOF = true;\r
-               }\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Generate a SELECT tag string from a recordset, and return the string.\r
-        * If the recordset has 2 cols, we treat the 1st col as the containing \r
-        * the text to display to the user, and 2nd col as the return value. Default\r
-        * strings are compared with the FIRST column.\r
-        *\r
-        * @param name                  name of SELECT tag\r
-        * @param [defstr]              the value to hilite. Use an array for multiple hilites for listbox.\r
-        * @param [blank1stItem]        true to leave the 1st item in list empty\r
-        * @param [multiple]            true for listbox, false for popup\r
-        * @param [size]                #rows to show for listbox. not used by popup\r
-        * @param [selectAttr]          additional attributes to defined for SELECT tag.\r
-        *                              useful for holding javascript onChange='...' handlers.\r
-        & @param [compareFields0]      when we have 2 cols in recordset, we compare the defstr with \r
-        *                              column 0 (1st col) if this is true. This is not documented.\r
-        *\r
-        * @return HTML\r
-        *\r
-        * changes by glen.davies@cce.ac.nz to support multiple hilited items\r
-        */\r
-       function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,\r
-                       $size=0, $selectAttr='',$compareFields0=true)\r
-       {\r
-               global $ADODB_INCLUDED_LIB;\r
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
-               return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,\r
-                       $size, $selectAttr,$compareFields0);\r
-       }\r
-       \r
-       /**\r
-        * Generate a SELECT tag string from a recordset, and return the string.\r
-        * If the recordset has 2 cols, we treat the 1st col as the containing \r
-        * the text to display to the user, and 2nd col as the return value. Default\r
-        * strings are compared with the SECOND column.\r
-        *\r
-        */\r
-       function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')  \r
-       {\r
-               global $ADODB_INCLUDED_LIB;\r
-               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
-               return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple,\r
-                       $size, $selectAttr,false);\r
-       }\r
-\r
-\r
-       /**\r
-        * return recordset as a 2-dimensional array.\r
-        *\r
-        * @param [nRows]  is the number of rows to return. -1 means every row.\r
-        *\r
-        * @return an array indexed by the rows (0-based) from the recordset\r
-        */\r
-       function &GetArray($nRows = -1) \r
-       {\r
-       global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows);\r
-               \r
-               $results = array();\r
-               $cnt = 0;\r
-               while (!$this->EOF && $nRows != $cnt) {\r
-                       $results[] = $this->fields;\r
-                       $this->MoveNext();\r
-                       $cnt++;\r
-               }\r
-               return $results;\r
-       }\r
-       \r
-       function &GetAll($nRows = -1)\r
-       {\r
-               $arr =& $this->GetArray($nRows);\r
-               return $arr;\r
-       }\r
-       \r
-       /*\r
-       * Some databases allow multiple recordsets to be returned. This function\r
-       * will return true if there is a next recordset, or false if no more.\r
-       */\r
-       function NextRecordSet()\r
-       {\r
-               return false;\r
-       }\r
-       \r
-       /**\r
-        * return recordset as a 2-dimensional array. \r
-        * Helper function for ADOConnection->SelectLimit()\r
-        *\r
-        * @param offset        is the row to start calculations from (1-based)\r
-        * @param [nrows]       is the number of rows to return\r
-        *\r
-        * @return an array indexed by the rows (0-based) from the recordset\r
-        */\r
-       function &GetArrayLimit($nrows,$offset=-1) \r
-       {       \r
-               if ($offset <= 0) {\r
-                       $arr =& $this->GetArray($nrows);\r
-                       return $arr;\r
-               } \r
-               \r
-               $this->Move($offset);\r
-               \r
-               $results = array();\r
-               $cnt = 0;\r
-               while (!$this->EOF && $nrows != $cnt) {\r
-                       $results[$cnt++] = $this->fields;\r
-                       $this->MoveNext();\r
-               }\r
-               \r
-               return $results;\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Synonym for GetArray() for compatibility with ADO.\r
-        *\r
-        * @param [nRows]  is the number of rows to return. -1 means every row.\r
-        *\r
-        * @return an array indexed by the rows (0-based) from the recordset\r
-        */\r
-       function &GetRows($nRows = -1) \r
-       {\r
-               $arr =& $this->GetArray($nRows);\r
-               return $arr;\r
-       }\r
-       \r
-       /**\r
-        * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. \r
-        * The first column is treated as the key and is not included in the array. \r
-        * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless\r
-        * $force_array == true.\r
-        *\r
-        * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional\r
-        *      array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,\r
-        *      read the source.\r
-        *\r
-        * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and \r
-        * instead of returning array[col0] => array(remaining cols), return array[col0] => col1\r
-        *\r
-        * @return an associative array indexed by the first column of the array, \r
-        *      or false if the  data has less than 2 cols.\r
-        */\r
-       function &GetAssoc($force_array = false, $first2cols = false) {\r
-               $cols = $this->_numOfFields;\r
-               if ($cols < 2) {\r
-                       return false;\r
-               }\r
-               $numIndex = isset($this->fields[0]);\r
-               $results = array();\r
-               \r
-               if (!$first2cols && ($cols > 2 || $force_array)) {\r
-                       if ($numIndex) {\r
-                               while (!$this->EOF) {\r
-                                       $results[trim($this->fields[0])] = array_slice($this->fields, 1);\r
-                                       $this->MoveNext();\r
-                               }\r
-                       } else {\r
-                               while (!$this->EOF) {\r
-                                       $results[trim(reset($this->fields))] = array_slice($this->fields, 1);\r
-                                       $this->MoveNext();\r
-                               }\r
-                       }\r
-               } else {\r
-                       // return scalar values\r
-                       if ($numIndex) {\r
-                               while (!$this->EOF) {\r
-                               // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string\r
-                                       $results[trim(($this->fields[0]))] = $this->fields[1];\r
-                                       $this->MoveNext();\r
-                               }\r
-                       } else {\r
-                               while (!$this->EOF) {\r
-                               // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string\r
-                                       $v1 = trim(reset($this->fields));\r
-                                       $v2 = ''.next($this->fields); \r
-                                       $results[$v1] = $v2;\r
-                                       $this->MoveNext();\r
-                               }\r
-                       }\r
-               }\r
-               return $results; \r
-       }\r
-       \r
-       \r
-       /**\r
-        *\r
-        * @param v     is the character timestamp in YYYY-MM-DD hh:mm:ss format\r
-        * @param fmt   is the format to apply to it, using date()\r
-        *\r
-        * @return a timestamp formated as user desires\r
-        */\r
-       function UserTimeStamp($v,$fmt='Y-m-d H:i:s')\r
-       {\r
-               if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);\r
-               $tt = $this->UnixTimeStamp($v);\r
-               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR\r
-               if (($tt === false || $tt == -1) && $v != false) return $v;\r
-               if ($tt === 0) return $this->emptyTimeStamp;\r
-               return adodb_date($fmt,$tt);\r
-       }\r
-       \r
-       \r
-       /**\r
-        * @param v     is the character date in YYYY-MM-DD format, returned by database\r
-        * @param fmt   is the format to apply to it, using date()\r
-        *\r
-        * @return a date formated as user desires\r
-        */\r
-       function UserDate($v,$fmt='Y-m-d')\r
-       {\r
-               $tt = $this->UnixDate($v);\r
-               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR\r
-               if (($tt === false || $tt == -1) && $v != false) return $v;\r
-               else if ($tt == 0) return $this->emptyDate;\r
-               else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR\r
-               }\r
-               return adodb_date($fmt,$tt);\r
-       \r
-       }\r
-       \r
-       \r
-       /**\r
-        * @param $v is a date string in YYYY-MM-DD format\r
-        *\r
-        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format\r
-        */\r
-       function UnixDate($v)\r
-       {\r
-               \r
-               if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", \r
-                       ($v), $rr)) return false;\r
-                       \r
-               if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;\r
-               // h-m-s-MM-DD-YY\r
-               return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);\r
-       }\r
-       \r
-\r
-       /**\r
-        * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format\r
-        *\r
-        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format\r
-        */\r
-       function UnixTimeStamp($v)\r
-       {\r
-               \r
-               if (!preg_match( \r
-                       "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", \r
-                       ($v), $rr)) return false;\r
-               if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;\r
-       \r
-               // h-m-s-MM-DD-YY\r
-               if (!isset($rr[5])) return  adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);\r
-               return  @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);\r
-       }\r
-       \r
-       \r
-       /**\r
-       * PEAR DB Compat - do not use internally\r
-       */\r
-       function Free()\r
-       {\r
-               return $this->Close();\r
-       }\r
-       \r
-       \r
-       /**\r
-       * PEAR DB compat, number of rows\r
-       */\r
-       function NumRows()\r
-       {\r
-               return $this->_numOfRows;\r
-       }\r
-       \r
-       \r
-       /**\r
-       * PEAR DB compat, number of cols\r
-       */\r
-       function NumCols()\r
-       {\r
-               return $this->_numOfFields;\r
-       }\r
-       \r
-       /**\r
-       * Fetch a row, returning false if no more rows. \r
-       * This is PEAR DB compat mode.\r
-       *\r
-       * @return false or array containing the current record\r
-       */\r
-       function FetchRow()\r
-       {\r
-               if ($this->EOF) return false;\r
-               $arr = $this->fields;\r
-               $this->_currentRow++;\r
-               if (!$this->_fetch()) $this->EOF = true;\r
-               return $arr;\r
-       }\r
-       \r
-       \r
-       /**\r
-       * Fetch a row, returning PEAR_Error if no more rows. \r
-       * This is PEAR DB compat mode.\r
-       *\r
-       * @return DB_OK or error object\r
-       */\r
-       function FetchInto(&$arr)\r
-       {\r
-               if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;\r
-               $arr = $this->fields;\r
-               $this->MoveNext();\r
-               return 1; // DB_OK\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Move to the first row in the recordset. Many databases do NOT support this.\r
-        *\r
-        * @return true or false\r
-        */\r
-       function MoveFirst() \r
-       {\r
-               if ($this->_currentRow == 0) return true;\r
-               return $this->Move(0);                  \r
-       }                       \r
-\r
-       \r
-       /**\r
-        * Move to the last row in the recordset. \r
-        *\r
-        * @return true or false\r
-        */\r
-       function MoveLast() \r
-       {\r
-               if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);\r
-               if ($this->EOF) return false;\r
-               while (!$this->EOF) {\r
-                       $f = $this->fields;\r
-                       $this->MoveNext();\r
-               }\r
-               $this->fields = $f;\r
-               $this->EOF = false;\r
-               return true;\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Move to next record in the recordset.\r
-        *\r
-        * @return true if there still rows available, or false if there are no more rows (EOF).\r
-        */\r
-       function MoveNext() \r
-       {\r
-               if (!$this->EOF) {\r
-                       $this->_currentRow++;\r
-                       if ($this->_fetch()) return true;\r
-               }\r
-               $this->EOF = true;\r
-               /* -- tested error handling when scrolling cursor -- seems useless.\r
-               $conn = $this->connection;\r
-               if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {\r
-                       $fn = $conn->raiseErrorFn;\r
-                       $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);\r
-               }\r
-               */\r
-               return false;\r
-       }       \r
-       \r
-       /**\r
-        * Random access to a specific row in the recordset. Some databases do not support\r
-        * access to previous rows in the databases (no scrolling backwards).\r
-        *\r
-        * @param rowNumber is the row to move to (0-based)\r
-        *\r
-        * @return true if there still rows available, or false if there are no more rows (EOF).\r
-        */\r
-       function Move($rowNumber = 0) \r
-       {\r
-               $this->EOF = false;\r
-               if ($rowNumber == $this->_currentRow) return true;\r
-               if ($rowNumber >= $this->_numOfRows)\r
-                       if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;\r
-                               \r
-               if ($this->canSeek) { \r
-       \r
-                       if ($this->_seek($rowNumber)) {\r
-                               $this->_currentRow = $rowNumber;\r
-                               if ($this->_fetch()) {\r
-                                       return true;\r
-                               }\r
-                       } else {\r
-                               $this->EOF = true;\r
-                               return false;\r
-                       }\r
-               } else {\r
-                       if ($rowNumber < $this->_currentRow) return false;\r
-                       global $ADODB_EXTENSION;\r
-                       if ($ADODB_EXTENSION) {\r
-                               while (!$this->EOF && $this->_currentRow < $rowNumber) {\r
-                                       adodb_movenext($this);\r
-                               }\r
-                       } else {\r
-                       \r
-                               while (! $this->EOF && $this->_currentRow < $rowNumber) {\r
-                                       $this->_currentRow++;\r
-                                       \r
-                                       if (!$this->_fetch()) $this->EOF = true;\r
-                               }\r
-                       }\r
-                       return !($this->EOF);\r
-               }\r
-               \r
-               $this->fields = false;  \r
-               $this->EOF = true;\r
-               return false;\r
-       }\r
-       \r
-               \r
-       /**\r
-        * Get the value of a field in the current row by column name.\r
-        * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.\r
-        * \r
-        * @param colname  is the field to access\r
-        *\r
-        * @return the value of $colname column\r
-        */\r
-       function Fields($colname)\r
-       {\r
-               return $this->fields[$colname];\r
-       }\r
-       \r
-       function GetAssocKeys($upper=true)\r
-       {\r
-               $this->bind = array();\r
-               for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                       $o =& $this->FetchField($i);\r
-                       if ($upper === 2) $this->bind[$o->name] = $i;\r
-                       else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;\r
-               }\r
-       }\r
-       \r
-  /**\r
-   * Use associative array to get fields array for databases that do not support\r
-   * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it\r
-   *\r
-   * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC\r
-   * before you execute your SQL statement, and access $rs->fields['col'] directly.\r
-   *\r
-   * $upper  0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField\r
-   */\r
-       function &GetRowAssoc($upper=1)\r
-       {\r
-               $record = array();\r
-        //     if (!$this->fields) return $record;\r
-               \r
-               if (!$this->bind) {\r
-                       $this->GetAssocKeys($upper);\r
-               }\r
-               \r
-               foreach($this->bind as $k => $v) {\r
-                       $record[$k] = $this->fields[$v];\r
-               }\r
-\r
-               return $record;\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Clean up recordset\r
-        *\r
-        * @return true or false\r
-        */\r
-       function Close() \r
-       {\r
-               // free connection object - this seems to globally free the object\r
-               // and not merely the reference, so don't do this...\r
-               // $this->connection = false; \r
-               if (!$this->_closed) {\r
-                       $this->_closed = true;\r
-                       return $this->_close();         \r
-               } else\r
-                       return true;\r
-       }\r
-       \r
-       /**\r
-        * synonyms RecordCount and RowCount    \r
-        *\r
-        * @return the number of rows or -1 if this is not supported\r
-        */\r
-       function RecordCount() {return $this->_numOfRows;}\r
-       \r
-       \r
-       /*\r
-       * If we are using PageExecute(), this will return the maximum possible rows\r
-       * that can be returned when paging a recordset.\r
-       */\r
-       function MaxRecordCount()\r
-       {\r
-               return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();\r
-       }\r
-       \r
-       /**\r
-        * synonyms RecordCount and RowCount    \r
-        *\r
-        * @return the number of rows or -1 if this is not supported\r
-        */\r
-       function RowCount() {return $this->_numOfRows;} \r
-       \r
-\r
-        /**\r
-        * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>\r
-        *\r
-        * @return  the number of records from a previous SELECT. All databases support this.\r
-        *\r
-        * But aware possible problems in multiuser environments. For better speed the table\r
-        * must be indexed by the condition. Heavy test this before deploying.\r
-        */ \r
-       function PO_RecordCount($table="", $condition="") {\r
-               \r
-               $lnumrows = $this->_numOfRows;\r
-               // the database doesn't support native recordcount, so we do a workaround\r
-               if ($lnumrows == -1 && $this->connection) {\r
-                       IF ($table) {\r
-                               if ($condition) $condition = " WHERE " . $condition; \r
-                               $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");\r
-                               if ($resultrows) $lnumrows = reset($resultrows->fields);\r
-                       }\r
-               }\r
-               return $lnumrows;\r
-       }\r
-       \r
-       /**\r
-        * @return the current row in the recordset. If at EOF, will return the last row. 0-based.\r
-        */\r
-       function CurrentRow() {return $this->_currentRow;}\r
-       \r
-       /**\r
-        * synonym for CurrentRow -- for ADO compat\r
-        *\r
-        * @return the current row in the recordset. If at EOF, will return the last row. 0-based.\r
-        */\r
-       function AbsolutePosition() {return $this->_currentRow;}\r
-       \r
-       /**\r
-        * @return the number of columns in the recordset. Some databases will set this to 0\r
-        * if no records are returned, others will return the number of columns in the query.\r
-        */\r
-       function FieldCount() {return $this->_numOfFields;}   \r
-\r
-\r
-       /**\r
-        * Get the ADOFieldObject of a specific column.\r
-        *\r
-        * @param fieldoffset   is the column position to access(0-based).\r
-        *\r
-        * @return the ADOFieldObject for that column, or false.\r
-        */\r
-       function &FetchField($fieldoffset) \r
-       {\r
-               // must be defined by child class\r
-       }       \r
-       \r
-       /**\r
-        * Get the ADOFieldObjects of all columns in an array.\r
-        *\r
-        */\r
-       function FieldTypesArray()\r
-       {\r
-               $arr = array();\r
-               for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) \r
-                       $arr[] = $this->FetchField($i);\r
-               return $arr;\r
-       }\r
-       \r
-       /**\r
-       * Return the fields array of the current row as an object for convenience.\r
-       * The default case is lowercase field names.\r
-       *\r
-       * @return the object with the properties set to the fields of the current row\r
-       */\r
-       function &FetchObj()\r
-       {\r
-               $o =& $this->FetchObject(false);\r
-               return $o;\r
-       }\r
-       \r
-       /**\r
-       * Return the fields array of the current row as an object for convenience.\r
-       * The default case is uppercase.\r
-       * \r
-       * @param $isupper to set the object property names to uppercase\r
-       *\r
-       * @return the object with the properties set to the fields of the current row\r
-       */\r
-       function &FetchObject($isupper=true)\r
-       {\r
-               if (empty($this->_obj)) {\r
-                       $this->_obj =& new ADOFetchObj();\r
-                       $this->_names = array();\r
-                       for ($i=0; $i <$this->_numOfFields; $i++) {\r
-                               $f = $this->FetchField($i);\r
-                               $this->_names[] = $f->name;\r
-                       }\r
-               }\r
-               $i = 0;\r
-               $o = &$this->_obj;\r
-               for ($i=0; $i <$this->_numOfFields; $i++) {\r
-                       $name = $this->_names[$i];\r
-                       if ($isupper) $n = strtoupper($name);\r
-                       else $n = $name;\r
-                       \r
-                       $o->$n = $this->Fields($name);\r
-               }\r
-               return $o;\r
-       }\r
-       \r
-       /**\r
-       * Return the fields array of the current row as an object for convenience.\r
-       * The default is lower-case field names.\r
-       * \r
-       * @return the object with the properties set to the fields of the current row,\r
-       *       or false if EOF\r
-       *\r
-       * Fixed bug reported by tim@orotech.net\r
-       */\r
-       function &FetchNextObj()\r
-       {\r
-               return $this->FetchNextObject(false);\r
-       }\r
-       \r
-       \r
-       /**\r
-       * Return the fields array of the current row as an object for convenience. \r
-       * The default is upper case field names.\r
-       * \r
-       * @param $isupper to set the object property names to uppercase\r
-       *\r
-       * @return the object with the properties set to the fields of the current row,\r
-       *       or false if EOF\r
-       *\r
-       * Fixed bug reported by tim@orotech.net\r
-       */\r
-       function &FetchNextObject($isupper=true)\r
-       {\r
-               $o = false;\r
-               if ($this->_numOfRows != 0 && !$this->EOF) {\r
-                       $o = $this->FetchObject($isupper);      \r
-                       $this->_currentRow++;\r
-                       if ($this->_fetch()) return $o;\r
-               }\r
-               $this->EOF = true;\r
-               return $o;\r
-       }\r
-       \r
-       /**\r
-        * Get the metatype of the column. This is used for formatting. This is because\r
-        * many databases use different names for the same type, so we transform the original\r
-        * type to our standardised version which uses 1 character codes:\r
-        *\r
-        * @param t  is the type passed in. Normally is ADOFieldObject->type.\r
-        * @param len is the maximum length of that field. This is because we treat character\r
-        *      fields bigger than a certain size as a 'B' (blob).\r
-        * @param fieldobj is the field object returned by the database driver. Can hold\r
-        *      additional info (eg. primary_key for mysql).\r
-        * \r
-        * @return the general type of the data: \r
-        *      C for character < 200 chars\r
-        *      X for teXt (>= 200 chars)\r
-        *      B for Binary\r
-        *      N for numeric floating point\r
-        *      D for date\r
-        *      T for timestamp\r
-        *      L for logical/Boolean\r
-        *      I for integer\r
-        *      R for autoincrement counter/integer\r
-        * \r
-        *\r
-       */\r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-       // changed in 2.32 to hashing instead of switch stmt for speed...\r
-       static $typeMap = array(\r
-               'VARCHAR' => 'C',\r
-               'VARCHAR2' => 'C',\r
-               'CHAR' => 'C',\r
-               'C' => 'C',\r
-               'STRING' => 'C',\r
-               'NCHAR' => 'C',\r
-               'NVARCHAR' => 'C',\r
-               'VARYING' => 'C',\r
-               'BPCHAR' => 'C',\r
-               'CHARACTER' => 'C',\r
-               'INTERVAL' => 'C',  # Postgres\r
-               ##\r
-               'LONGCHAR' => 'X',\r
-               'TEXT' => 'X',\r
-               'NTEXT' => 'X',\r
-               'M' => 'X',\r
-               'X' => 'X',\r
-               'CLOB' => 'X',\r
-               'NCLOB' => 'X',\r
-               'LVARCHAR' => 'X',\r
-               ##\r
-               'BLOB' => 'B',\r
-               'IMAGE' => 'B',\r
-               'BINARY' => 'B',\r
-               'VARBINARY' => 'B',\r
-               'LONGBINARY' => 'B',\r
-               'B' => 'B',\r
-               ##\r
-               'YEAR' => 'D', // mysql\r
-               'DATE' => 'D',\r
-               'D' => 'D',\r
-               ##\r
-               'TIME' => 'T',\r
-               'TIMESTAMP' => 'T',\r
-               'DATETIME' => 'T',\r
-               'TIMESTAMPTZ' => 'T',\r
-               'T' => 'T',\r
-               ##\r
-               'BOOL' => 'L',\r
-               'BOOLEAN' => 'L', \r
-               'BIT' => 'L',\r
-               'L' => 'L',\r
-               ##\r
-               'COUNTER' => 'R',\r
-               'R' => 'R',\r
-               'SERIAL' => 'R', // ifx\r
-               'INT IDENTITY' => 'R',\r
-               ##\r
-               'INT' => 'I',\r
-               'INTEGER' => 'I',\r
-               'INTEGER UNSIGNED' => 'I',\r
-               'SHORT' => 'I',\r
-               'TINYINT' => 'I',\r
-               'SMALLINT' => 'I',\r
-               'I' => 'I',\r
-               ##\r
-               'LONG' => 'N', // interbase is numeric, oci8 is blob\r
-               'BIGINT' => 'N', // this is bigger than PHP 32-bit integers\r
-               'DECIMAL' => 'N',\r
-               'DEC' => 'N',\r
-               'REAL' => 'N',\r
-               'DOUBLE' => 'N',\r
-               'DOUBLE PRECISION' => 'N',\r
-               'SMALLFLOAT' => 'N',\r
-               'FLOAT' => 'N',\r
-               'NUMBER' => 'N',\r
-               'NUM' => 'N',\r
-               'NUMERIC' => 'N',\r
-               'MONEY' => 'N',\r
-               \r
-               ## informix 9.2\r
-               'SQLINT' => 'I', \r
-               'SQLSERIAL' => 'I', \r
-               'SQLSMINT' => 'I', \r
-               'SQLSMFLOAT' => 'N', \r
-               'SQLFLOAT' => 'N', \r
-               'SQLMONEY' => 'N', \r
-               'SQLDECIMAL' => 'N', \r
-               'SQLDATE' => 'D', \r
-               'SQLVCHAR' => 'C', \r
-               'SQLCHAR' => 'C', \r
-               'SQLDTIME' => 'T', \r
-               'SQLINTERVAL' => 'N', \r
-               'SQLBYTES' => 'B', \r
-               'SQLTEXT' => 'X' \r
-               );\r
-               \r
-               $tmap = false;\r
-               $t = strtoupper($t);\r
-               $tmap = @$typeMap[$t];\r
-               switch ($tmap) {\r
-               case 'C':\r
-               \r
-                       // is the char field is too long, return as text field... \r
-                       if ($this->blobSize >= 0) {\r
-                               if ($len > $this->blobSize) return 'X';\r
-                       } else if ($len > 250) {\r
-                               return 'X';\r
-                       }\r
-                       return 'C';\r
-                       \r
-               case 'I':\r
-                       if (!empty($fieldobj->primary_key)) return 'R';\r
-                       return 'I';\r
-               \r
-               case false:\r
-                       return 'N';\r
-                       \r
-               case 'B':\r
-                        if (isset($fieldobj->binary)) \r
-                                return ($fieldobj->binary) ? 'B' : 'X';\r
-                       return 'B';\r
-               \r
-               case 'D':\r
-                       if (!empty($this->dateHasTime)) return 'T';\r
-                       return 'D';\r
-                       \r
-               default: \r
-                       if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';\r
-                       return $tmap;\r
-               }\r
-       }\r
-       \r
-       function _close() {}\r
-       \r
-       /**\r
-        * set/returns the current recordset page when paginating\r
-        */\r
-       function AbsolutePage($page=-1)\r
-       {\r
-               if ($page != -1) $this->_currentPage = $page;\r
-               return $this->_currentPage;\r
-       }\r
-       \r
-       /**\r
-        * set/returns the status of the atFirstPage flag when paginating\r
-        */\r
-       function AtFirstPage($status=false)\r
-       {\r
-               if ($status != false) $this->_atFirstPage = $status;\r
-               return $this->_atFirstPage;\r
-       }\r
-       \r
-       function LastPageNo($page = false)\r
-       {\r
-               if ($page != false) $this->_lastPageNo = $page;\r
-               return $this->_lastPageNo;\r
-       }\r
-       \r
-       /**\r
-        * set/returns the status of the atLastPage flag when paginating\r
-        */\r
-       function AtLastPage($status=false)\r
-       {\r
-               if ($status != false) $this->_atLastPage = $status;\r
-               return $this->_atLastPage;\r
-       }\r
-       \r
-} // end class ADORecordSet\r
-       \r
-       //==============================================================================================        \r
-       // CLASS ADORecordSet_array\r
-       //==============================================================================================        \r
-       \r
-       /**\r
-        * This class encapsulates the concept of a recordset created in memory\r
-        * as an array. This is useful for the creation of cached recordsets.\r
-        * \r
-        * Note that the constructor is different from the standard ADORecordSet\r
-        */\r
-       \r
-       class ADORecordSet_array extends ADORecordSet\r
-       {\r
-               var $databaseType = 'array';\r
-\r
-               var $_array;    // holds the 2-dimensional data array\r
-               var $_types;    // the array of types of each column (C B I L M)\r
-               var $_colnames; // names of each column in array\r
-               var $_skiprow1; // skip 1st row because it holds column names\r
-               var $_fieldarr; // holds array of field objects\r
-               var $canSeek = true;\r
-               var $affectedrows = false;\r
-               var $insertid = false;\r
-               var $sql = '';\r
-               var $compat = false;\r
-               /**\r
-                * Constructor\r
-                *\r
-                */\r
-               function ADORecordSet_array($fakeid=1)\r
-               {\r
-               global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;\r
-               \r
-                       // fetch() on EOF does not delete $this->fields\r
-                       $this->compat = !empty($ADODB_COMPAT_FETCH);\r
-                       $this->ADORecordSet($fakeid); // fake queryID           \r
-                       $this->fetchMode = $ADODB_FETCH_MODE;\r
-               }\r
-               \r
-               \r
-               /**\r
-                * Setup the array.\r
-                *\r
-                * @param array         is a 2-dimensional array holding the data.\r
-                *                      The first row should hold the column names \r
-                *                      unless paramter $colnames is used.\r
-                * @param typearr       holds an array of types. These are the same types \r
-                *                      used in MetaTypes (C,B,L,I,N).\r
-                * @param [colnames]    array of column names. If set, then the first row of\r
-                *                      $array should not hold the column names.\r
-                */\r
-               function InitArray($array,$typearr,$colnames=false)\r
-               {\r
-                       $this->_array = $array;\r
-                       $this->_types = $typearr;       \r
-                       if ($colnames) {\r
-                               $this->_skiprow1 = false;\r
-                               $this->_colnames = $colnames;\r
-                       } else  {\r
-                               $this->_skiprow1 = true;\r
-                               $this->_colnames = $array[0];\r
-                       }\r
-                       $this->Init();\r
-               }\r
-               /**\r
-                * Setup the Array and datatype file objects\r
-                *\r
-                * @param array         is a 2-dimensional array holding the data.\r
-                *                      The first row should hold the column names \r
-                *                      unless paramter $colnames is used.\r
-                * @param fieldarr      holds an array of ADOFieldObject's.\r
-                */\r
-               function InitArrayFields($array,$fieldarr)\r
-               {\r
-                       $this->_array = $array;\r
-                       $this->_skiprow1= false;\r
-                       if ($fieldarr) {\r
-                               $this->_fieldobjects = $fieldarr;\r
-                       } \r
-                       $this->Init();\r
-               }\r
-               \r
-               function &GetArray($nRows=-1)\r
-               {\r
-                       if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {\r
-                               return $this->_array;\r
-                       } else {\r
-                               $arr =& ADORecordSet::GetArray($nRows);\r
-                               return $arr;\r
-                       }\r
-               }\r
-               \r
-               function _initrs()\r
-               {\r
-                       $this->_numOfRows =  sizeof($this->_array);\r
-                       if ($this->_skiprow1) $this->_numOfRows -= 1;\r
-               \r
-                       $this->_numOfFields =(isset($this->_fieldobjects)) ?\r
-                                sizeof($this->_fieldobjects):sizeof($this->_types);\r
-               }\r
-               \r
-               /* Use associative array to get fields array */\r
-               function Fields($colname)\r
-               {\r
-                       if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];\r
-       \r
-                       if (!$this->bind) {\r
-                               $this->bind = array();\r
-                               for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                                       $o = $this->FetchField($i);\r
-                                       $this->bind[strtoupper($o->name)] = $i;\r
-                               }\r
-                       }\r
-                       return $this->fields[$this->bind[strtoupper($colname)]];\r
-               }\r
-               \r
-               function &FetchField($fieldOffset = -1) \r
-               {\r
-                       if (isset($this->_fieldobjects)) {\r
-                               return $this->_fieldobjects[$fieldOffset];\r
-                       }\r
-                       $o =  new ADOFieldObject();\r
-                       $o->name = $this->_colnames[$fieldOffset];\r
-                       $o->type =  $this->_types[$fieldOffset];\r
-                       $o->max_length = -1; // length not known\r
-                       \r
-                       return $o;\r
-               }\r
-                       \r
-               function _seek($row)\r
-               {\r
-                       if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {\r
-                               $this->_currentRow = $row;\r
-                               if ($this->_skiprow1) $row += 1;\r
-                               $this->fields = $this->_array[$row];\r
-                               return true;\r
-                       }\r
-                       return false;\r
-               }\r
-               \r
-               function MoveNext() \r
-               {\r
-                       if (!$this->EOF) {              \r
-                               $this->_currentRow++;\r
-                               \r
-                               $pos = $this->_currentRow;\r
-                               \r
-                               if ($this->_numOfRows <= $pos) {\r
-                                       if (!$this->compat) $this->fields = false;\r
-                               } else {\r
-                                       if ($this->_skiprow1) $pos += 1;\r
-                                       $this->fields = $this->_array[$pos];\r
-                                       return true;\r
-                               }               \r
-                               $this->EOF = true;\r
-                       }\r
-                       \r
-                       return false;\r
-               }       \r
-       \r
-               function _fetch()\r
-               {\r
-                       $pos = $this->_currentRow;\r
-                       \r
-                       if ($this->_numOfRows <= $pos) {\r
-                               if (!$this->compat) $this->fields = false;\r
-                               return false;\r
-                       }\r
-                       if ($this->_skiprow1) $pos += 1;\r
-                       $this->fields = $this->_array[$pos];\r
-                       return true;\r
-               }\r
-               \r
-               function _close() \r
-               {\r
-                       return true;    \r
-               }\r
-       \r
-       } // ADORecordSet_array\r
-\r
-       //==============================================================================================        \r
-       // HELPER FUNCTIONS\r
-       //==============================================================================================                        \r
-       \r
-       /**\r
-        * Synonym for ADOLoadCode. Private function. Do not use.\r
-        *\r
-        * @deprecated\r
-        */\r
-       function ADOLoadDB($dbType) \r
-       { \r
-               return ADOLoadCode($dbType);\r
-       }\r
-               \r
-       /**\r
-        * Load the code for a specific database driver. Private function. Do not use.\r
-        */\r
-       function ADOLoadCode($dbType) \r
-       {\r
-       global $ADODB_LASTDB;\r
-       \r
-               if (!$dbType) return false;\r
-               $db = strtolower($dbType);\r
-               switch ($db) {\r
-                       case 'maxsql': $db = 'mysqlt'; break;\r
-                       case 'postgres':\r
-                       case 'pgsql': $db = 'postgres7'; break;\r
-               }\r
-               $ok = @include_once(ADODB_DIR."/drivers/adodb-".$db.".inc.php");\r
-               $ADODB_LASTDB = $db;\r
-               \r
-               if ($ok) return $db;\r
-               \r
-               $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";\r
-               if (file_exists($file)) ADOConnection::outp("Missing file: $file");\r
-               else ADOConnection::outp("Syntax error in file: $file");\r
-               return false;\r
-       }\r
-\r
-       /**\r
-        * synonym for ADONewConnection for people like me who cannot remember the correct name\r
-        */\r
-       function &NewADOConnection($db='')\r
-       {\r
-               $tmp =& ADONewConnection($db);\r
-               return $tmp;\r
-       }\r
-       \r
-       /**\r
-        * Instantiate a new Connection class for a specific database driver.\r
-        *\r
-        * @param [db]  is the database Connection object to create. If undefined,\r
-        *      use the last database driver that was loaded by ADOLoadCode().\r
-        *\r
-        * @return the freshly created instance of the Connection class.\r
-        */\r
-       function &ADONewConnection($db='')\r
-       {\r
-       GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;\r
-               \r
-               if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);\r
-               $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;\r
-               \r
-               if (!empty($ADODB_NEWCONNECTION)) {\r
-                       $obj = $ADODB_NEWCONNECTION($db);\r
-                       if ($obj) {\r
-                               if ($errorfn)  $obj->raiseErrorFn = $errorfn;\r
-                               return $obj;\r
-                       }\r
-               }\r
-               \r
-               if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';\r
-               if (empty($db)) $db = $ADODB_LASTDB;\r
-               \r
-               if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);\r
-               \r
-               if (!$db) {\r
-                        if ($errorfn) {\r
-                               // raise an error\r
-                               $ignore = false;\r
-                               $errorfn('ADONewConnection', 'ADONewConnection', -998,\r
-                                                "could not load the database driver for '$db",\r
-                                                $db,false,$ignore);\r
-                       } else\r
-                                ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);\r
-                               \r
-                       return false;\r
-               }\r
-               \r
-               $cls = 'ADODB_'.$db;\r
-               if (!class_exists($cls)) {\r
-                       adodb_backtrace();\r
-                       return false;\r
-               }\r
-               \r
-               $obj =& new $cls();\r
-               if ($errorfn) $obj->raiseErrorFn = $errorfn;\r
-               \r
-               return $obj;\r
-       }\r
-       \r
-       // $perf == true means called by NewPerfMonitor()\r
-       function _adodb_getdriver($provider,$drivername,$perf=false)\r
-       {\r
-               if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado') \r
-                       $drivername = $provider;\r
-               else {\r
-                       if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5);\r
-                       else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4);\r
-                       else \r
-                       switch($drivername) {\r
-                       case 'oracle': $drivername = 'oci8';break;\r
-                       //case 'sybase': $drivername = 'mssql';break;\r
-                       case 'access': \r
-                                               if ($perf) $drivername = '';\r
-                                               break;\r
-                       case 'db2':     \r
-                                               if ($perf) break;\r
-                       default:\r
-                               $drivername = 'generic';\r
-                               break;\r
-                       }\r
-               }\r
-               \r
-               return $drivername;\r
-       }\r
-       \r
-       function &NewPerfMonitor(&$conn)\r
-       {\r
-               $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);\r
-               if (!$drivername || $drivername == 'generic') return false;\r
-               include_once(ADODB_DIR.'/adodb-perf.inc.php');\r
-               @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");\r
-               $class = "Perf_$drivername";\r
-               if (!class_exists($class)) return false;\r
-               $perf =& new $class($conn);\r
-               \r
-               return $perf;\r
-       }\r
-       \r
-       function &NewDataDictionary(&$conn)\r
-       {\r
-               $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);\r
-               \r
-               include_once(ADODB_DIR.'/adodb-lib.inc.php');\r
-               include_once(ADODB_DIR.'/adodb-datadict.inc.php');\r
-               $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";\r
-\r
-               if (!file_exists($path)) {\r
-                       ADOConnection::outp("Database driver '$path' not available");\r
-                       return false;\r
-               }\r
-               include_once($path);\r
-               $class = "ADODB2_$drivername";\r
-               $dict =& new $class();\r
-               $dict->dataProvider = $conn->dataProvider;\r
-               $dict->connection = &$conn;\r
-               $dict->upperName = strtoupper($drivername);\r
-               $dict->quote = $conn->nameQuote;\r
-               if (is_resource($conn->_connectionID))\r
-                       $dict->serverInfo = $conn->ServerInfo();\r
-               \r
-               return $dict;\r
-       }\r
-\r
-\r
-       /**\r
-       * Save a file $filename and its $contents (normally for caching) with file locking\r
-       */\r
-       function adodb_write_file($filename, $contents,$debug=false)\r
-       { \r
-       # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows\r
-       # So to simulate locking, we assume that rename is an atomic operation.\r
-       # First we delete $filename, then we create a $tempfile write to it and \r
-       # rename to the desired $filename. If the rename works, then we successfully \r
-       # modified the file exclusively.\r
-       # What a stupid need - having to simulate locking.\r
-       # Risks:\r
-       # 1. $tempfile name is not unique -- very very low\r
-       # 2. unlink($filename) fails -- ok, rename will fail\r
-       # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs\r
-       # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and  cache updated\r
-               if (strncmp(PHP_OS,'WIN',3) === 0) {\r
-                       // skip the decimal place\r
-                       $mtime = substr(str_replace(' ','_',microtime()),2); \r
-                       // getmypid() actually returns 0 on Win98 - never mind!\r
-                       $tmpname = $filename.uniqid($mtime).getmypid();\r
-                       if (!($fd = fopen($tmpname,'a'))) return false;\r
-                       $ok = ftruncate($fd,0);                 \r
-                       if (!fwrite($fd,$contents)) $ok = false;\r
-                       fclose($fd);\r
-                       chmod($tmpname,0644);\r
-                       // the tricky moment\r
-                       @unlink($filename);\r
-                       if (!@rename($tmpname,$filename)) {\r
-                               unlink($tmpname);\r
-                               $ok = false;\r
-                       }\r
-                       if (!$ok) {\r
-                               if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));\r
-                       }\r
-                       return $ok;\r
-               }\r
-               if (!($fd = fopen($filename, 'a'))) return false;\r
-               if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {\r
-                       $ok = fwrite( $fd, $contents );\r
-                       fclose($fd);\r
-                       chmod($filename,0644);\r
-               }else {\r
-                       fclose($fd);\r
-                       if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");\r
-                       $ok = false;\r
-               }\r
-       \r
-               return $ok;\r
-       }\r
-       \r
-       /*\r
-               Perform a print_r, with pre tags for better formatting.\r
-       */\r
-       function adodb_pr($var)\r
-       {\r
-               if (isset($_SERVER['HTTP_USER_AGENT'])) { \r
-                       echo " <pre>\n";print_r($var);echo "</pre>\n";\r
-               } else\r
-                       print_r($var);\r
-       }\r
-       \r
-       /*\r
-               Perform a stack-crawl and pretty print it.\r
-               \r
-               @param printOrArr  Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).\r
-               @param levels Number of levels to display\r
-       */\r
-       function adodb_backtrace($printOrArr=true,$levels=9999)\r
-       {\r
-               $s = '';\r
-               if (PHPVERSION() < 4.3) return;\r
-                \r
-               $html =  (isset($_SERVER['HTTP_USER_AGENT']));\r
-               $fmt =  ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";\r
-\r
-               $MAXSTRLEN = 64;\r
-       \r
-               $s = ($html) ? '<pre align=left>' : '';\r
-               \r
-               if (is_array($printOrArr)) $traceArr = $printOrArr;\r
-               else $traceArr = debug_backtrace();\r
-               array_shift($traceArr);\r
-               $tabs = sizeof($traceArr)-1;\r
-               \r
-               foreach ($traceArr as $arr) {\r
-                       $levels -= 1;\r
-                       if ($levels < 0) break;\r
-                       \r
-                       $args = array();\r
-                       for ($i=0; $i < $tabs; $i++) $s .=  ($html) ? ' &nbsp; ' : "\t";\r
-                       $tabs -= 1;\r
-                       if ($html) $s .= '<font face="Courier New,Courier">';\r
-                       if (isset($arr['class'])) $s .= $arr['class'].'.';\r
-                       if (isset($arr['args']))\r
-                        foreach($arr['args'] as $v) {\r
-                               if (is_null($v)) $args[] = 'null';\r
-                               else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';\r
-                               else if (is_object($v)) $args[] = 'Object:'.get_class($v);\r
-                               else if (is_bool($v)) $args[] = $v ? 'true' : 'false';\r
-                               else {\r
-                                       $v = (string) @$v;\r
-                                       $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));\r
-                                       if (strlen($v) > $MAXSTRLEN) $str .= '...';\r
-                                       $args[] = $str;\r
-                               }\r
-                       }\r
-                       $s .= $arr['function'].'('.implode(', ',$args).')';\r
-                       \r
-                       \r
-                       $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));\r
-                               \r
-                       $s .= "\n";\r
-               }       \r
-               if ($html) $s .= '</pre>';\r
-               if ($printOrArr) print $s;\r
-               \r
-               return $s;\r
-       }\r
-       \r
-} // defined\r
+<?php 
+/*
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com/adodb
+ * 
+ * This is the main include file for ADOdb.
+ * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
+ *
+ * The ADOdb files are formatted so that doxygen can be used to generate documentation.
+ * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
+ */
+
+/**
+       \mainpage       
+       
+        @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved.
+
+       Released under both BSD license and Lesser GPL library license. You can choose which license
+       you prefer.
+       
+       PHP's database access functions are not standardised. This creates a need for a database 
+       class library to hide the differences between the different database API's (encapsulate 
+       the differences) so we can easily switch databases.
+
+       We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
+       Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
+       ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
+       other databases via ODBC. 
+        
+       Latest Download at http://php.weblogs.com/adodb<br>
+       Manual is at http://php.weblogs.com/adodb_manual
+         
+ */
+ if (!defined('_ADODB_LAYER')) {
+       define('_ADODB_LAYER',1);
+       
+       //==============================================================================================        
+       // CONSTANT DEFINITIONS
+       //==============================================================================================        
+
+
+       /** 
+        * Set ADODB_DIR to the directory where this file resides...
+        * This constant was formerly called $ADODB_RootPath
+        */
+       if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
+       
+       //==============================================================================================        
+       // GLOBAL VARIABLES
+       //==============================================================================================        
+
+       GLOBAL 
+               $ADODB_vers,            // database version
+               $ADODB_COUNTRECS,       // count number of records returned - slows down query
+               $ADODB_CACHE_DIR,       // directory to cache recordsets
+               $ADODB_EXTENSION,   // ADODB extension installed
+               $ADODB_COMPAT_PATCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
+               $ADODB_FETCH_MODE;      // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
+       
+       //==============================================================================================        
+       // GLOBAL SETUP
+       //==============================================================================================        
+       
+       $ADODB_EXTENSION = defined('ADODB_EXTENSION');
+       if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
+               
+               define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
+       
+       // allow [ ] @ ` " and . in table names
+               define('ADODB_TABLE_REGEX','([]0-9a-z_\"\`\.\@\[-]*)');
+       
+       // prefetching used by oracle
+               if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
+       
+       
+       /*
+       Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
+       This currently works only with mssql, odbc, oci8po and ibase derived drivers.
+       
+               0 = assoc lowercase field names. $rs->fields['orderid']
+               1 = assoc uppercase field names. $rs->fields['ORDERID']
+               2 = use native-case field names. $rs->fields['OrderID']
+       */
+       
+               define('ADODB_FETCH_DEFAULT',0);
+               define('ADODB_FETCH_NUM',1);
+               define('ADODB_FETCH_ASSOC',2);
+               define('ADODB_FETCH_BOTH',3);
+               
+               if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
+       
+               if (strnatcmp(PHP_VERSION,'4.3.0')>=0) {
+                       define('ADODB_PHPVER',0x4300);
+               } else if (strnatcmp(PHP_VERSION,'4.2.0')>=0) {
+                       define('ADODB_PHPVER',0x4200);
+               } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
+                       define('ADODB_PHPVER',0x4050);
+               } else {
+                       define('ADODB_PHPVER',0x4000);
+               }
+       }
+       
+       //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
+       
+       
+       /**
+               Accepts $src and $dest arrays, replacing string $data
+       */
+       function ADODB_str_replace($src, $dest, $data)
+       {
+               if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
+               
+               $s = reset($src);
+               $d = reset($dest);
+               while ($s !== false) {
+                       $data = str_replace($s,$d,$data);
+                       $s = next($src);
+                       $d = next($dest);
+               }
+               return $data;
+       }
+       
+       function ADODB_Setup()
+       {
+       GLOBAL 
+               $ADODB_vers,            // database version
+               $ADODB_COUNTRECS,       // count number of records returned - slows down query
+               $ADODB_CACHE_DIR,       // directory to cache recordsets
+               $ADODB_FETCH_MODE;
+               
+               $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
+               
+               if (!isset($ADODB_CACHE_DIR)) {
+                       $ADODB_CACHE_DIR = '/tmp';
+               } else {
+                       // do not accept url based paths, eg. http:/ or ftp:/
+                       if (strpos($ADODB_CACHE_DIR,'://') !== false) 
+                               die("Illegal path http:// or ftp://");
+               }
+               
+                       
+               // Initialize random number generator for randomizing cache flushes
+               srand(((double)microtime())*1000000);
+               
+               /**
+                * ADODB version as a string.
+                */
+               $ADODB_vers = 'V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
+       
+               /**
+                * Determines whether recordset->RecordCount() is used. 
+                * Set to false for highest performance -- RecordCount() will always return -1 then
+                * for databases that provide "virtual" recordcounts...
+                */
+               if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true; 
+       }
+       
+       
+       //==============================================================================================        
+       // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
+       //==============================================================================================        
+       
+       ADODB_Setup();
+
+       //==============================================================================================        
+       // CLASS ADOFieldObject
+       //==============================================================================================        
+       /**
+        * Helper class for FetchFields -- holds info on a column
+        */
+       class ADOFieldObject { 
+               var $name = '';
+               var $max_length=0;
+               var $type="";
+
+               // additional fields by dannym... (danny_milo@yahoo.com)
+               var $not_null = false; 
+               // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
+               // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
+
+               var $has_default = false; // this one I have done only in mysql and postgres for now ... 
+                       // others to come (dannym)
+               var $default_value; // default, if any, and supported. Check has_default first.
+       }
+       
+
+       
+       function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
+       {
+               //print "Errorno ($fn errno=$errno m=$errmsg) ";
+               $thisConnection->_transOK = false;
+               if ($thisConnection->_oldRaiseFn) {
+                       $fn = $thisConnection->_oldRaiseFn;
+                       $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
+               }
+       }
+       
+       //==============================================================================================        
+       // CLASS ADOConnection
+       //==============================================================================================        
+       
+       /**
+        * Connection object. For connecting to databases, and executing queries.
+        */ 
+       class ADOConnection {
+       //
+       // PUBLIC VARS 
+       //
+       var $dataProvider = 'native';
+       var $databaseType = '';         /// RDBMS currently in use, eg. odbc, mysql, mssql                                      
+       var $database = '';                     /// Name of database to be used.        
+       var $host = '';                         /// The hostname of the database server 
+       var $user = '';                         /// The username which is used to connect to the database server. 
+       var $password = '';             /// Password for the username. For security, we no longer store it.
+       var $debug = false;             /// if set to true will output sql statements
+       var $maxblobsize = 256000;      /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro
+       var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase    
+       var $substr = 'substr';         /// substring operator
+       var $length = 'length';         /// string length operator
+       var $random = 'rand()';         /// random function
+       var $upperCase = false;         /// uppercase function
+       var $fmtDate = "'Y-m-d'";       /// used by DBDate() as the default date format used by the database
+       var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
+       var $true = '1';                        /// string that represents TRUE for a database
+       var $false = '0';                       /// string that represents FALSE for a database
+       var $replaceQuote = "\\'";      /// string to use to replace quotes
+       var $nameQuote = '"';           /// string to use to quote identifiers and names
+       var $charSet=false;             /// character set to use - only for interbase
+       var $metaDatabasesSQL = '';
+       var $metaTablesSQL = '';
+       var $uniqueOrderBy = false; /// All order by columns have to be unique
+       var $emptyDate = '&nbsp;';
+       var $emptyTimeStamp = '&nbsp;';
+       var $lastInsID = false;
+       //--
+       var $hasInsertID = false;               /// supports autoincrement ID?
+       var $hasAffectedRows = false;   /// supports affected rows for update/delete?
+       var $hasTop = false;                    /// support mssql/access SELECT TOP 10 * FROM TABLE
+       var $hasLimit = false;                  /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
+       var $readOnly = false;                  /// this is a readonly database - used by phpLens
+       var $hasMoveFirst = false;  /// has ability to run MoveFirst(), scrolling backwards
+       var $hasGenID = false;          /// can generate sequences using GenID();
+       var $hasTransactions = true; /// has transactions
+       //--
+       var $genID = 0;                         /// sequence id used by GenID();
+       var $raiseErrorFn = false;      /// error function to call
+       var $isoDates = false; /// accepts dates in ISO format
+       var $cacheSecs = 3600; /// cache for 1 hour
+       var $sysDate = false; /// name of function that returns the current date
+       var $sysTimeStamp = false; /// name of function that returns the current timestamp
+       var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
+       
+       var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
+       var $numCacheHits = 0; 
+       var $numCacheMisses = 0;
+       var $pageExecuteCountRows = true;
+       var $uniqueSort = false; /// indicates that all fields in order by must be unique
+       var $leftOuter = false; /// operator to use for left outer join in WHERE clause
+       var $rightOuter = false; /// operator to use for right outer join in WHERE clause
+       var $ansiOuter = false; /// whether ansi outer join syntax supported
+       var $autoRollback = false; // autoRollback on PConnect().
+       var $poorAffectedRows = false; // affectedRows not working or unreliable
+       
+       var $fnExecute = false;
+       var $fnCacheExecute = false;
+       var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
+       var $rsPrefix = "ADORecordSet_";
+       
+       var $autoCommit = true;         /// do not modify this yourself - actually private
+       var $transOff = 0;                      /// temporarily disable transactions
+       var $transCnt = 0;                      /// count of nested transactions
+       
+       var $fetchMode=false;
+        //
+        // PRIVATE VARS
+        //
+       var $_oldRaiseFn =  false;
+       var $_transOK = null;
+       var $_connectionID      = false;        /// The returned link identifier whenever a successful database connection is made.     
+       var $_errorMsg = false;         /// A variable which was used to keep the returned last error message.  The value will
+                                                               /// then returned by the errorMsg() function    
+       var $_errorCode = false;        /// Last error code, not guaranteed to be used - only by oci8                                   
+       var $_queryID = false;          /// This variable keeps the last created result link identifier
+       
+       var $_isPersistentConnection = false;   /// A boolean variable to state whether its a persistent connection or normal connection.       */
+       var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
+       var $_evalAll = false;
+       var $_affected = false;
+       var $_logsql = false;
+       
+
+       
+       /**
+        * Constructor
+        */
+       function ADOConnection()                        
+       {
+               die('Virtual Class -- cannot instantiate');
+       }
+       
+       /**
+               Get server version info...
+               
+               @returns An array with 2 elements: $arr['string'] is the description string, 
+                       and $arr[version] is the version (also a string).
+       */
+       function ServerInfo()
+       {
+               return array('description' => '', 'version' => '');
+       }
+       
+       function _findvers($str)
+       {
+               if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
+               else return '';
+       }
+       
+       /**
+       * All error messages go through this bottleneck function.
+       * You can define your own handler by defining the function name in ADODB_OUTP.
+       */
+       function outp($msg,$newline=true)
+       {
+       global $HTTP_SERVER_VARS,$ADODB_FLUSH;
+       
+               if (defined('ADODB_OUTP')) {
+                       $fn = ADODB_OUTP;
+                       $fn($msg,$newline);
+                       return;
+               }
+               
+               if ($newline) $msg .= "<br>\n";
+               
+               if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg;
+               else echo strip_tags($msg);
+               if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); //  dp not flush if output buffering enabled - useless - thx to Jesse Mullan 
+               
+       }
+       
+       /**
+        * Connect to database
+        *
+        * @param [argHostname]         Host to connect to
+        * @param [argUsername]         Userid to login
+        * @param [argPassword]         Associated password
+        * @param [argDatabaseName]     database
+        * @param [forceNew]            force new connection
+        *
+        * @return true or false
+        */       
+       function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) 
+       {
+               if ($argHostname != "") $this->host = $argHostname;
+               if ($argUsername != "") $this->user = $argUsername;
+               if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
+               if ($argDatabaseName != "") $this->database = $argDatabaseName;         
+               
+               $this->_isPersistentConnection = false; 
+               if ($fn = $this->raiseErrorFn) {
+                       if ($forceNew) {
+                               if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
+                       } else {
+                                if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
+                       }
+                       $err = $this->ErrorMsg();
+                       if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
+                       $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
+               } else {
+                       if ($forceNew) {
+                               if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
+                       } else {
+                               if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
+                       }
+               }
+               if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());
+               return false;
+       }       
+       
+        function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
+        {
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
+        }
+       
+       
+       /**
+        * Always force a new connection to database - currently only works with oracle
+        *
+        * @param [argHostname]         Host to connect to
+        * @param [argUsername]         Userid to login
+        * @param [argPassword]         Associated password
+        * @param [argDatabaseName]     database
+        *
+        * @return true or false
+        */       
+       function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") 
+       {
+               return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
+       }
+       
+       /**
+        * Establish persistent connect to database
+        *
+        * @param [argHostname]         Host to connect to
+        * @param [argUsername]         Userid to login
+        * @param [argPassword]         Associated password
+        * @param [argDatabaseName]     database
+        *
+        * @return return true or false
+        */     
+       function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
+       {
+               if (defined('ADODB_NEVER_PERSIST')) 
+                       return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
+               
+               if ($argHostname != "") $this->host = $argHostname;
+               if ($argUsername != "") $this->user = $argUsername;
+               if ($argPassword != "") $this->password = $argPassword;
+               if ($argDatabaseName != "") $this->database = $argDatabaseName;         
+                       
+               $this->_isPersistentConnection = true;  
+               
+               if ($fn = $this->raiseErrorFn) {
+                       if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
+                       $err = $this->ErrorMsg();
+                       if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
+                       $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
+               } else 
+                       if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
+
+               if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg());
+               return false;
+       }
+
+       // Format date column in sql string given an input format that understands Y M D
+       function SQLDate($fmt, $col=false)
+       {       
+               if (!$col) $col = $this->sysDate;
+               return $col; // child class implement
+       }
+       
+       /**
+        * Should prepare the sql statement and return the stmt resource.
+        * For databases that do not support this, we return the $sql. To ensure
+        * compatibility with databases that do not support prepare:
+        *
+        *   $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
+        *   $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
+        *   $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
+        *
+        * @param sql   SQL to send to database
+        *
+        * @return return FALSE, or the prepared statement, or the original sql if
+        *                      if the database does not support prepare.
+        *
+        */     
+       function Prepare($sql)
+       {
+               return $sql;
+       }
+
+       /**
+        * Some databases, eg. mssql require a different function for preparing
+        * stored procedures. So we cannot use Prepare().
+        *
+        * Should prepare the stored procedure  and return the stmt resource.
+        * For databases that do not support this, we return the $sql. To ensure
+        * compatibility with databases that do not support prepare:
+        *
+        * @param sql   SQL to send to database
+        *
+        * @return return FALSE, or the prepared statement, or the original sql if
+        *                      if the database does not support prepare.
+        *
+        */     
+       function PrepareSP($sql,$param=false)
+       {
+               return $this->Prepare($sql,$param);
+       }
+       
+       /**
+       * PEAR DB Compat
+       */
+       function Quote($s)
+       {
+               return $this->qstr($s,false);
+       }
+       
+       /**
+        Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
+       */
+       function QMagic($s)
+       {
+               return $this->qstr($s,get_magic_quotes_gpc());
+       }
+
+       function q(&$s)
+       {
+               $s = $this->qstr($s,false);
+       }
+       
+       /**
+       * PEAR DB Compat - do not use internally. 
+       */
+       function ErrorNative()
+       {
+               return $this->ErrorNo();
+       }
+
+       
+   /**
+       * PEAR DB Compat - do not use internally. 
+       */
+       function nextId($seq_name)
+       {
+               return $this->GenID($seq_name);
+       }
+
+       /**
+       *        Lock a row, will escalate and lock the table if row locking not supported
+       *       will normally free the lock at the end of the transaction
+       *
+       *  @param $table        name of table to lock
+       *  @param $where        where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
+       */
+       function RowLock($table,$where)
+       {
+               return false;
+       }
+       
+       function CommitLock($table)
+       {
+               return $this->CommitTrans();
+       }
+       
+       function RollbackLock($table)
+       {
+               return $this->RollbackTrans();
+       }
+       
+       /**
+       * PEAR DB Compat - do not use internally. 
+       *
+       * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
+       *       for easy porting :-)
+       *
+       * @param mode   The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
+       * @returns              The previous fetch mode
+       */
+       function SetFetchMode($mode)
+       {       
+               $old = $this->fetchMode;
+               $this->fetchMode = $mode;
+               
+               if ($old === false) {
+               global $ADODB_FETCH_MODE;
+                       return $ADODB_FETCH_MODE;
+               }
+               return $old;
+       }
+       
+
+       /**
+       * PEAR DB Compat - do not use internally. 
+       */
+       function &Query($sql, $inputarr=false)
+       {
+               $rs = &$this->Execute($sql, $inputarr);
+               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
+               return $rs;
+       }
+
+       
+       /**
+       * PEAR DB Compat - do not use internally
+       */
+       function &LimitQuery($sql, $offset, $count, $params=false)
+       {
+               $rs = &$this->SelectLimit($sql, $count, $offset, $params); 
+               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
+               return $rs;
+       }
+
+       
+       /**
+       * PEAR DB Compat - do not use internally
+       */
+       function Disconnect()
+       {
+               return $this->Close();
+       }
+       
+       /*
+                Returns placeholder for parameter, eg.
+                $DB->Param('a')
+                
+                will return ':a' for Oracle, and '?' for most other databases...
+                
+                For databases that require positioned params, eg $1, $2, $3 for postgresql,
+                       pass in Param(false) before setting the first parameter.
+       */
+       function Param($name)
+       {
+               return '?';
+       }
+       
+       /*
+               InParameter and OutParameter are self-documenting versions of Parameter().
+       */
+       function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
+       {
+               return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
+       }
+       
+       /*
+       */
+       function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
+       {
+               return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
+       
+       }
+       
+       /* 
+       Usage in oracle
+               $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
+               $db->Parameter($stmt,$id,'myid');
+               $db->Parameter($stmt,$group,'group',64);
+               $db->Execute();
+               
+               @param $stmt Statement returned by Prepare() or PrepareSP().
+               @param $var PHP variable to bind to
+               @param $name Name of stored procedure variable name to bind to.
+               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
+               @param [$maxLen] Holds an maximum length of the variable.
+               @param [$type] The data type of $var. Legal values depend on driver.
+
+       */
+       function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
+       {
+               return false;
+       }
+       
+       /**
+               Improved method of initiating a transaction. Used together with CompleteTrans().
+               Advantages include:
+               
+               a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
+                  Only the outermost block is treated as a transaction.<br>
+               b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
+               c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
+                  are disabled, making it backward compatible.
+       */
+       function StartTrans($errfn = 'ADODB_TransMonitor')
+       {
+               if ($this->transOff > 0) {
+                       $this->transOff += 1;
+                       return;
+               }
+               
+               $this->_oldRaiseFn = $this->raiseErrorFn;
+               $this->raiseErrorFn = $errfn;
+               $this->_transOK = true;
+               
+               if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
+               $this->BeginTrans();
+               $this->transOff = 1;
+       }
+       
+       /**
+               Used together with StartTrans() to end a transaction. Monitors connection
+               for sql errors, and will commit or rollback as appropriate.
+               
+               @autoComplete if true, monitor sql errors and commit and rollback as appropriate, 
+               and if set to false force rollback even if no SQL error detected.
+               @returns true on commit, false on rollback.
+       */
+       function CompleteTrans($autoComplete = true)
+       {
+               if ($this->transOff > 1) {
+                       $this->transOff -= 1;
+                       return true;
+               }
+               $this->raiseErrorFn = $this->_oldRaiseFn;
+               
+               $this->transOff = 0;
+               if ($this->_transOK && $autoComplete) {
+                       if (!$this->CommitTrans()) {
+                               $this->_transOK = false;
+                               if ($this->debug) ADOConnection::outp("Smart Commit failed");
+                       } else
+                               if ($this->debug) ADOConnection::outp("Smart Commit occurred");
+               } else {
+                       $this->RollbackTrans();
+                       if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
+               }
+               
+               return $this->_transOK;
+       }
+       
+       /*
+               At the end of a StartTrans/CompleteTrans block, perform a rollback.
+       */
+       function FailTrans()
+       {
+               if ($this->debug) 
+                       if ($this->transOff == 0) {
+                               ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
+                       } else {
+                               ADOConnection::outp("FailTrans was called");
+                               adodb_backtrace();
+                       }
+               $this->_transOK = false;
+       }
+       
+       /**
+               Check if transaction has failed, only for Smart Transactions.
+       */
+       function HasFailedTrans()
+       {
+               if ($this->transOff > 0) return $this->_transOK == false;
+               return false;
+       }
+       
+       /**
+        * Execute SQL 
+        *
+        * @param sql           SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
+        * @param [inputarr]    holds the input data to bind to. Null elements will be set to null.
+        * @return              RecordSet or false
+        */
+       function &Execute($sql,$inputarr=false) 
+       {
+               if ($this->fnExecute) {
+                       $fn = $this->fnExecute;
+                       $ret =& $fn($this,$sql,$inputarr);
+                       if (isset($ret)) return $ret;
+               }
+               if ($inputarr && is_array($inputarr)) {
+                       $element0 = reset($inputarr);
+                       # is_object check is because oci8 descriptors can be passed in
+                       $array_2d = is_array($element0) && !is_object(reset($element0));
+                       
+                       if (!is_array($sql) && !$this->_bindInputArray) {
+                               $sqlarr = explode('?',$sql);
+                                       
+                               if (!$array_2d) $inputarr = array($inputarr);
+                               foreach($inputarr as $arr) {
+                                       $sql = ''; $i = 0;
+                                       foreach($arr as $v) {
+                                               $sql .= $sqlarr[$i];
+                                               // from Ron Baldwin <ron.baldwin@sourceprose.com>
+                                               // Only quote string types      
+                                               if (gettype($v) == 'string')
+                                                       $sql .= $this->qstr($v);
+                                               else if ($v === null)
+                                                       $sql .= 'NULL';
+                                               else
+                                                       $sql .= $v;
+                                               $i += 1;
+                                       }
+                                       $sql .= $sqlarr[$i];
+                                       
+                                       if ($i+1 != sizeof($sqlarr))    
+                                               ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
+               
+                                       $ret =& $this->_Execute($sql,false);
+                                       if (!$ret) return $ret;
+                               }       
+                       } else {
+                               if ($array_2d) {
+                                       $stmt = $this->Prepare($sql);
+                                       foreach($inputarr as $arr) {
+                                               $ret =& $this->_Execute($stmt,$arr);
+                                               if (!$ret) return $ret;
+                                       }
+                               } else
+                                       $ret =& $this->_Execute($sql,$inputarr);
+                       }
+               } else {
+                       $ret =& $this->_Execute($sql,false);
+               }
+
+               return $ret;
+       }
+       
+       function& _Execute($sql,$inputarr=false)
+       {
+               // debug version of query
+               if ($this->debug) {
+               global $HTTP_SERVER_VARS;
+                       $ss = '';
+                       if ($inputarr) {
+                               foreach($inputarr as $kk=>$vv) {
+                                       if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
+                                       $ss .= "($kk=>'$vv') ";
+                               }
+                               $ss = "[ $ss ]";
+                       }
+                       $sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql);
+                       
+                       // check if running from browser or command-line
+                       $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
+                       
+                       if ($inBrowser)
+                               if ($this->debug === -1)
+                               ADOConnection::outp( "<br>\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<br>\n",false);
+                               else ADOConnection::outp( "<hr />\n($this->databaseType): ".htmlspecialchars($sqlTxt)." &nbsp; <code>$ss</code>\n<hr />\n",false);
+                       else
+                               ADOConnection::outp(  "=----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false);
+                       
+                       $this->_queryID = $this->_query($sql,$inputarr);
+                       /* 
+                               Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
+                               because ErrorNo() calls Execute('SELECT @ERROR'), causing recure
+                       */
+                       if ($this->databaseType == 'mssql') { 
+                       // ErrorNo is a slow function call in mssql, and not reliable
+                       // in PHP 4.0.6
+                               if($emsg = $this->ErrorMsg()) {
+                                       $err = $this->ErrorNo();
+                                       if ($err) {
+                                               ADOConnection::outp($err.': '.$emsg);
+                                       }
+                               }
+                       } else 
+                               if (!$this->_queryID) {
+                                       $e = $this->ErrorNo();
+                                       $m = $this->ErrorMsg();
+                                       ADOConnection::outp($e .': '. $m );
+                               }
+               } else {
+                       // non-debug version of query
+                       
+                       $this->_queryID =@$this->_query($sql,$inputarr);
+               }
+               
+               /************************
+                       OK, query executed
+               *************************/
+               // error handling if query fails
+               if ($this->_queryID === false) {
+                       if ($this->debug == 99) adodb_backtrace(true,5);        
+                       $fn = $this->raiseErrorFn;
+                       if ($fn) {
+                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
+                       } 
+                               
+                       return false;
+               } else if ($this->_queryID === true) {
+               // return simplified empty recordset for inserts/updates/deletes with lower overhead
+                       $rs =& new ADORecordSet_empty();
+                       return $rs;
+               }
+               
+               // return real recordset from select statement
+               $rsclass = $this->rsPrefix.$this->databaseType;
+               $rs =& new $rsclass($this->_queryID,$this->fetchMode); // &new not supported by older PHP versions
+               $rs->connection = &$this; // Pablo suggestion
+               $rs->Init();
+               if (is_array($sql)) $rs->sql = $sql[0];
+               else $rs->sql = $sql;
+               if ($rs->_numOfRows <= 0) {
+               global $ADODB_COUNTRECS;
+       
+                       if ($ADODB_COUNTRECS) {
+                               if (!$rs->EOF){ 
+                                       $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
+                                       $rs->_queryID = $this->_queryID;
+                               } else
+                                       $rs->_numOfRows = 0;
+                       }
+               }
+               return $rs;
+       }
+
+       function CreateSequence($seqname='adodbseq',$startID=1)
+       {
+               if (empty($this->_genSeqSQL)) return false;
+               return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
+       }
+
+       function DropSequence($seqname)
+       {
+               if (empty($this->_dropSeqSQL)) return false;
+               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
+       }
+
+       /**
+        * Generates a sequence id and stores it in $this->genID;
+        * GenID is only available if $this->hasGenID = true;
+        *
+        * @param seqname               name of sequence to use
+        * @param startID               if sequence does not exist, start at this ID
+        * @return              0 if not supported, otherwise a sequence id
+        */
+       function GenID($seqname='adodbseq',$startID=1)
+       {
+               if (!$this->hasGenID) {
+                       return 0; // formerly returns false pre 1.60
+               }
+               
+               $getnext = sprintf($this->_genIDSQL,$seqname);
+               
+               $holdtransOK = $this->_transOK;
+               $rs = @$this->Execute($getnext);
+               if (!$rs) {
+                       $this->_transOK = $holdtransOK; //if the status was ok before reset
+                       $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
+                       $rs = $this->Execute($getnext);
+               }
+               if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
+               else $this->genID = 0; // false
+       
+               if ($rs) $rs->Close();
+
+               return $this->genID;
+       }       
+
+       /**
+        * @return  the last inserted ID. Not all databases support this.
+        */ 
+       function Insert_ID()
+       {
+               if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
+               if ($this->hasInsertID) return $this->_insertid();
+               if ($this->debug) {
+                       ADOConnection::outp( '<p>Insert_ID error</p>');
+                       adodb_backtrace();
+               }
+               return false;
+       }
+
+
+       /**
+        * Portable Insert ID. Pablo Roca <pabloroca@mvps.org>
+        *
+        * @return  the last inserted ID. All databases support this. But aware possible
+        * problems in multiuser environments. Heavy test this before deploying.
+        */ 
+       function PO_Insert_ID($table="", $id="") 
+       {
+          if ($this->hasInsertID){
+                  return $this->Insert_ID();
+          } else {
+                  return $this->GetOne("SELECT MAX($id) FROM $table");
+          }
+       }
+
+       /**
+       * @return # rows affected by UPDATE/DELETE
+       */ 
+       function Affected_Rows()
+       {
+               if ($this->hasAffectedRows) {
+                       if ($this->fnExecute === 'adodb_log_sql') {
+                               if ($this->_logsql && $this->_affected !== false) return $this->_affected;
+                       }
+                       $val = $this->_affectedrows();
+                       return ($val < 0) ? false : $val;
+               }
+                                 
+               if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
+               return false;
+       }
+       
+       
+       /**
+        * @return  the last error message
+        */
+       function ErrorMsg()
+       {
+               return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
+       }
+       
+       
+       /**
+        * @return the last error number. Normally 0 means no error.
+        */
+       function ErrorNo() 
+       {
+               return ($this->_errorMsg) ? -1 : 0;
+       }
+       
+       function MetaError($err=false)
+       {
+               include_once(ADODB_DIR."/adodb-error.inc.php");
+               if ($err === false) $err = $this->ErrorNo();
+               return adodb_error($this->dataProvider,$this->databaseType,$err);
+       }
+       
+       function MetaErrorMsg($errno)
+       {
+               include_once(ADODB_DIR."/adodb-error.inc.php");
+               return adodb_errormsg($errno);
+       }
+       
+       /**
+        * @returns an array with the primary key columns in it.
+        */
+       function MetaPrimaryKeys($table, $owner=false)
+       {
+       // owner not used in base class - see oci8
+               $p = array();
+               $objs =& $this->MetaColumns($table);
+               if ($objs) {
+                       foreach($objs as $v) {
+                               if (!empty($v->primary_key))
+                                       $p[] = $v->name;
+                       }
+               }
+               if (sizeof($p)) return $p;
+               if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
+                       return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
+               return false;
+       }
+       
+       /**
+        * @returns assoc array where keys are tables, and values are foreign keys
+        */
+       function MetaForeignKeys($table, $owner=false, $upper=false)
+       {
+               return false;
+       }
+       /**
+        * Choose a database to connect to. Many databases do not support this.
+        *
+        * @param dbName        is the name of the database to select
+        * @return              true or false
+        */
+       function SelectDB($dbName) 
+       {return false;}
+       
+       
+       /**
+       * Will select, getting rows from $offset (1-based), for $nrows. 
+       * This simulates the MySQL "select * from table limit $offset,$nrows" , and
+       * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
+       * MySQL and PostgreSQL parameter ordering is the opposite of the other.
+       * eg. 
+       *  SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
+       *  SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
+       *
+       * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
+       * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
+       *
+       * @param sql
+       * @param [offset]       is the row to start calculations from (1-based)
+       * @param [nrows]                is the number of rows to get
+       * @param [inputarr]     array of bind variables
+       * @param [secs2cache]           is a private parameter only used by jlim
+       * @return               the recordset ($rs->databaseType == 'array')
+       */
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+       {
+               if ($this->hasTop && $nrows > 0) {
+               // suggested by Reinhard Balling. Access requires top after distinct 
+                // Informix requires first before distinct - F Riosa
+                       $ismssql = (strpos($this->databaseType,'mssql') !== false);
+                       if ($ismssql) $isaccess = false;
+                       else $isaccess = (strpos($this->databaseType,'access') !== false);
+                       
+                       if ($offset <= 0) {
+                               
+                                       // access includes ties in result
+                                       if ($isaccess) {
+                                               $sql = preg_replace(
+                                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
+
+                                               if ($secs2cache>0) {
+                                                       $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
+                                               } else {
+                                                       $ret =& $this->Execute($sql,$inputarr);
+                                               }
+                                               return $ret; // PHP5 fix
+                                       } else if ($ismssql){
+                                               $sql = preg_replace(
+                                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
+                                       } else {
+                                               $sql = preg_replace(
+                                               '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
+                                       }
+                       } else {
+                               $nn = $nrows + $offset;
+                               if ($isaccess || $ismssql) {
+                                       $sql = preg_replace(
+                                       '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
+                               } else {
+                                       $sql = preg_replace(
+                                       '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
+                               }
+                       }
+               }
+               
+               // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer  rows
+               // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
+               global $ADODB_COUNTRECS;
+               
+               $savec = $ADODB_COUNTRECS;
+               $ADODB_COUNTRECS = false;
+                       
+               if ($offset>0){
+                       if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
+                       else $rs = &$this->Execute($sql,$inputarr);
+               } else {
+                       if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
+                       else $rs = &$this->Execute($sql,$inputarr);
+               }
+               $ADODB_COUNTRECS = $savec;
+               if ($rs && !$rs->EOF) {
+                       $rs =& $this->_rs2rs($rs,$nrows,$offset);
+               }
+               //print_r($rs);
+               return $rs;
+       }
+       
+       /**
+       * Create serializable recordset. Breaks rs link to connection.
+       *
+       * @param rs                     the recordset to serialize
+       */
+       function &SerializableRS(&$rs)
+       {
+               $rs2 =& $this->_rs2rs($rs);
+               $ignore = false;
+               $rs2->connection =& $ignore;
+               
+               return $rs2;
+       }
+       
+       /**
+       * Convert database recordset to an array recordset
+       * input recordset's cursor should be at beginning, and
+       * old $rs will be closed.
+       *
+       * @param rs                     the recordset to copy
+       * @param [nrows]        number of rows to retrieve (optional)
+       * @param [offset]       offset by number of rows (optional)
+       * @return                       the new recordset
+       */
+       function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
+       {
+               if (! $rs) return false;
+               
+               $dbtype = $rs->databaseType;
+               if (!$dbtype) {
+                       $rs = &$rs;  // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
+                       return $rs;
+               }
+               if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
+                       $rs->MoveFirst();
+                       $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
+                       return $rs;
+               }
+               $flds = array();
+               for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
+                       $flds[] = $rs->FetchField($i);
+               }
+               $arr =& $rs->GetArrayLimit($nrows,$offset);
+               //print_r($arr);
+               if ($close) $rs->Close();
+               
+               $arrayClass = $this->arrayClass;
+               
+               $rs2 =& new $arrayClass();
+               $rs2->connection = &$this;
+               $rs2->sql = $rs->sql;
+               $rs2->dataProvider = $this->dataProvider;
+               $rs2->InitArrayFields($arr,$flds);
+               return $rs2;
+       }
+       
+       /*
+       * Return all rows. Compat with PEAR DB
+       */
+       function &GetAll($sql, $inputarr=false)
+       {
+               $arr =& $this->GetArray($sql,$inputarr);
+               return $arr;
+       }
+       
+       function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
+       {
+               $rs =& $this->Execute($sql, $inputarr);
+               if (!$rs) return false;
+               
+               $arr =& $rs->GetAssoc($force_array,$first2cols);
+               return $arr;
+       }
+       
+       function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
+       {
+               if (!is_numeric($secs2cache)) {
+                       $first2cols = $force_array;
+                       $force_array = $inputarr;
+               }
+               $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);
+               if (!$rs) return false;
+               
+               $arr =& $rs->GetAssoc($force_array,$first2cols);
+               return $arr;
+       }
+       
+       /**
+       * Return first element of first row of sql statement. Recordset is disposed
+       * for you.
+       *
+       * @param sql                    SQL statement
+       * @param [inputarr]             input bind array
+       */
+       function GetOne($sql,$inputarr=false)
+       {
+       global $ADODB_COUNTRECS;
+               $crecs = $ADODB_COUNTRECS;
+               $ADODB_COUNTRECS = false;
+               
+               $ret = false;
+               $rs = &$this->Execute($sql,$inputarr);
+               if ($rs) {              
+                       if (!$rs->EOF) $ret = reset($rs->fields);
+                       $rs->Close();
+               } 
+               $ADODB_COUNTRECS = $crecs;
+               return $ret;
+       }
+       
+       function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
+       {
+               $ret = false;
+               $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
+               if ($rs) {              
+                       if (!$rs->EOF) $ret = reset($rs->fields);
+                       $rs->Close();
+               } 
+               
+               return $ret;
+       }
+       
+       function GetCol($sql, $inputarr = false, $trim = false)
+       {
+               $rv = false;
+               $rs = &$this->Execute($sql, $inputarr);
+               if ($rs) {
+                       $rv = array();
+                       if ($trim) {
+                               while (!$rs->EOF) {
+                                       $rv[] = trim(reset($rs->fields));
+                                       $rs->MoveNext();
+                               }
+                       } else {
+                               while (!$rs->EOF) {
+                                       $rv[] = reset($rs->fields);
+                                       $rs->MoveNext();
+                               }
+                       }
+                       $rs->Close();
+               }
+               return $rv;
+       }
+       
+       function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
+       {
+               $rv = false;
+               $rs = &$this->CacheExecute($secs, $sql, $inputarr);
+               if ($rs) {
+                       if ($trim) {
+                               while (!$rs->EOF) {
+                                       $rv[] = trim(reset($rs->fields));
+                                       $rs->MoveNext();
+                               }
+                       } else {
+                               while (!$rs->EOF) {
+                                       $rv[] = reset($rs->fields);
+                                       $rs->MoveNext();
+                               }
+                       }
+                       $rs->Close();
+               }
+               return $rv;
+       }
+       /*
+               Calculate the offset of a date for a particular database and generate
+                       appropriate SQL. Useful for calculating future/past dates and storing
+                       in a database.
+                       
+               If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
+       */
+       function OffsetDate($dayFraction,$date=false)
+       {               
+               if (!$date) $date = $this->sysDate;
+               return  '('.$date.'+'.$dayFraction.')';
+       }
+       
+       
+       /**
+       *
+       * @param sql                    SQL statement
+       * @param [inputarr]             input bind array
+       */
+       function &GetArray($sql,$inputarr=false)
+       {
+       global $ADODB_COUNTRECS;
+               
+               $savec = $ADODB_COUNTRECS;
+               $ADODB_COUNTRECS = false;
+               $rs =& $this->Execute($sql,$inputarr);
+               $ADODB_COUNTRECS = $savec;
+               if (!$rs) 
+                       if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
+                       else return false;
+               $arr =& $rs->GetArray();
+               $rs->Close();
+               return $arr;
+       }
+       
+       function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
+       {
+       global $ADODB_COUNTRECS;
+               
+               $savec = $ADODB_COUNTRECS;
+               $ADODB_COUNTRECS = false;
+               $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
+               $ADODB_COUNTRECS = $savec;
+               
+               if (!$rs) 
+                       if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
+                       else return false;
+               
+               $arr =& $rs->GetArray();
+               $rs->Close();
+               return $arr;
+       }
+       
+       
+       
+       /**
+       * Return one row of sql statement. Recordset is disposed for you.
+       *
+       * @param sql                    SQL statement
+       * @param [inputarr]             input bind array
+       */
+       function &GetRow($sql,$inputarr=false)
+       {
+       global $ADODB_COUNTRECS;
+               $crecs = $ADODB_COUNTRECS;
+               $ADODB_COUNTRECS = false;
+               
+               $rs =& $this->Execute($sql,$inputarr);
+               
+               $ADODB_COUNTRECS = $crecs;
+               if ($rs) {
+                       if (!$rs->EOF) $arr = $rs->fields;
+                       else $arr = array();
+                       $rs->Close();
+                       return $arr;
+               }
+               
+               return false;
+       }
+       
+       function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
+       {
+               $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
+               if ($rs) {
+                       $arr = false;
+                       if (!$rs->EOF) $arr = $rs->fields;
+                       $rs->Close();
+                       return $arr;
+               }
+               return false;
+       }
+       
+       /**
+       * Insert or replace a single record. Note: this is not the same as MySQL's replace. 
+       * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
+       * Also note that no table locking is done currently, so it is possible that the
+       * record be inserted twice by two programs...
+       *
+       * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
+       *
+       * $table                table name
+       * $fieldArray   associative array of data (you must quote strings yourself).
+       * $keyCol               the primary key field name or if compound key, array of field names
+       * autoQuote             set to true to use a hueristic to quote strings. Works with nulls and numbers
+       *                                       but does not work with dates nor SQL functions.
+       * has_autoinc   the primary key is an auto-inc field, so skip in insert.
+       *
+       * Currently blob replace not supported
+       *
+       * returns 0 = fail, 1 = update, 2 = insert 
+       */
+       
+       function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
+       {
+               global $ADODB_INCLUDED_LIB;
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
+               
+               return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
+       }
+       
+       
+       /**
+       * Will select, getting rows from $offset (1-based), for $nrows. 
+       * This simulates the MySQL "select * from table limit $offset,$nrows" , and
+       * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
+       * MySQL and PostgreSQL parameter ordering is the opposite of the other.
+       * eg. 
+       *  CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
+       *  CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
+       *
+       * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
+       *
+       * @param [secs2cache]   seconds to cache data, set to 0 to force query. This is optional
+       * @param sql
+       * @param [offset]       is the row to start calculations from (1-based)
+       * @param [nrows]        is the number of rows to get
+       * @param [inputarr]     array of bind variables
+       * @return               the recordset ($rs->databaseType == 'array')
+       */
+       function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
+       {       
+               if (!is_numeric($secs2cache)) {
+                       if ($sql === false) $sql = -1;
+                       if ($offset == -1) $offset = false;
+                                                                         // sql,       nrows, offset,inputarr
+                       $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
+               } else {
+                       if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
+                       $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+               }
+               return $rs;
+       }
+       
+       /**
+       * Flush cached recordsets that match a particular $sql statement. 
+       * If $sql == false, then we purge all files in the cache.
+       */
+       function CacheFlush($sql=false,$inputarr=false)
+       {
+       global $ADODB_CACHE_DIR;
+       
+               if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
+                       if (strncmp(PHP_OS,'WIN',3) === 0) {
+                               $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
+                       } else {
+                               $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache'; 
+                               // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
+                       }
+                       if ($this->debug) {
+                               ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
+                       } else {
+                               exec($cmd);
+                       }
+                       return;
+               } 
+               $f = $this->_gencachename($sql.serialize($inputarr),false);
+               adodb_write_file($f,''); // is adodb_write_file needed?
+               if (!@unlink($f)) {
+                       if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
+               }
+       }
+       
+       /**
+       * Private function to generate filename for caching.
+       * Filename is generated based on:
+       *
+       *  - sql statement
+       *  - database type (oci8, ibase, ifx, etc)
+       *  - database name
+       *  - userid
+       *
+       * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). 
+       * Assuming that we can have 50,000 files per directory with good performance, 
+       * then we can scale to 12.8 million unique cached recordsets. Wow!
+       */
+       function _gencachename($sql,$createdir)
+       {
+       global $ADODB_CACHE_DIR;
+               
+               $m = md5($sql.$this->databaseType.$this->database.$this->user);
+               $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2);
+               if ($createdir && !file_exists($dir)) {
+                       $oldu = umask(0);
+                       if (!mkdir($dir,0771)) 
+                               if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
+                       umask($oldu);
+               }
+               return $dir.'/adodb_'.$m.'.cache';
+       }
+       
+       
+       /**
+        * Execute SQL, caching recordsets.
+        *
+        * @param [secs2cache]  seconds to cache data, set to 0 to force query. 
+        *                                        This is an optional parameter.
+        * @param sql           SQL statement to execute
+        * @param [inputarr]    holds the input data  to bind to
+        * @return              RecordSet or false
+        */
+       function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
+       {
+               if (!is_numeric($secs2cache)) {
+                       $inputarr = $sql;
+                       $sql = $secs2cache;
+                       $secs2cache = $this->cacheSecs;
+               }
+               global $ADODB_INCLUDED_CSV;
+               if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
+               
+               if (is_array($sql)) $sql = $sql[0];
+                       
+               $md5file = $this->_gencachename($sql.serialize($inputarr),true);
+               $err = '';
+               
+               if ($secs2cache > 0){
+                       $rs = &csv2rs($md5file,$err,$secs2cache);
+                       $this->numCacheHits += 1;
+               } else {
+                       $err='Timeout 1';
+                       $rs = false;
+                       $this->numCacheMisses += 1;
+               }
+               if (!$rs) {
+               // no cached rs found
+                       if ($this->debug) {
+                               if (get_magic_quotes_runtime()) {
+                                       ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
+                               }
+                               if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
+                       }
+                       $rs = &$this->Execute($sql,$inputarr);
+                       if ($rs) {
+                               $eof = $rs->EOF;
+                               $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
+                               $txt = _rs2serialize($rs,false,$sql); // serialize
+               
+                               if (!adodb_write_file($md5file,$txt,$this->debug)) {
+                                       if ($fn = $this->raiseErrorFn) {
+                                               $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
+                                       }
+                                       if ($this->debug) ADOConnection::outp( " Cache write error");
+                               }
+                               if ($rs->EOF && !$eof) {
+                                       $rs->MoveFirst();
+                                       //$rs = &csv2rs($md5file,$err);         
+                                       $rs->connection = &$this; // Pablo suggestion
+                               }  
+                               
+                       } else
+                               @unlink($md5file);
+               } else {
+                       $this->_errorMsg = '';
+                       $this->_errorCode = 0;
+                       
+                       if ($this->fnCacheExecute) {
+                               $fn = $this->fnCacheExecute;
+                               $fn($this, $secs2cache, $sql, $inputarr);
+                       }
+               // ok, set cached object found
+                       $rs->connection = &$this; // Pablo suggestion
+                       if ($this->debug){ 
+                       global $HTTP_SERVER_VARS;
+                                       
+                               $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
+                               $ttl = $rs->timeCreated + $secs2cache - time();
+                               $s = is_array($sql) ? $sql[0] : $sql;
+                               if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
+                               
+                               ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
+                       }
+               }
+               return $rs;
+       }
+       
+       
+       /**
+        * Generates an Update Query based on an existing recordset.
+        * $arrFields is an associative array of fields with the value
+        * that should be assigned.
+        *
+        * Note: This function should only be used on a recordset
+        *         that is run against a single table and sql should only 
+        *               be a simple select stmt with no groupby/orderby/limit
+        *
+        * "Jonathan Younger" <jyounger@unilab.com>
+        */
+       function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false)
+       {
+               global $ADODB_INCLUDED_LIB;
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
+               return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq);
+       }
+
+
+       /**
+        * Generates an Insert Query based on an existing recordset.
+        * $arrFields is an associative array of fields with the value
+        * that should be assigned.
+        *
+        * Note: This function should only be used on a recordset
+        *         that is run against a single table.
+        */
+       function GetInsertSQL(&$rs, $arrFields,$magicq=false)
+       {       
+               global $ADODB_INCLUDED_LIB;
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
+               return _adodb_getinsertsql($this,$rs,$arrFields,$magicq);
+       }
+       
+
+       /**
+       * Update a blob column, given a where clause. There are more sophisticated
+       * blob handling functions that we could have implemented, but all require
+       * a very complex API. Instead we have chosen something that is extremely
+       * simple to understand and use. 
+       *
+       * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
+       *
+       * Usage to update a $blobvalue which has a primary key blob_id=1 into a 
+       * field blobtable.blobcolumn:
+       *
+       *       UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
+       *
+       * Insert example:
+       *
+       *       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+       *       $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+       */
+       
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+       {
+               return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
+       }
+
+       /**
+       * Usage:
+       *       UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
+       *       
+       *       $blobtype supports 'BLOB' and 'CLOB'
+       *
+       *       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+       *       $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
+       */
+       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
+       {
+               $fd = fopen($path,'rb');
+               if ($fd === false) return false;
+               $val = fread($fd,filesize($path));
+               fclose($fd);
+               return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
+       }
+       
+       function BlobDecode($blob)
+       {
+               return $blob;
+       }
+       
+       function BlobEncode($blob)
+       {
+               return $blob;
+       }
+       
+       function SetCharSet($charset)
+       {
+               return false;
+       }
+       
+       function IfNull( $field, $ifNull ) 
+       {
+               return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
+       }
+       
+       function LogSQL($enable=true)
+       {
+               include_once(ADODB_DIR.'/adodb-perf.inc.php');
+               
+               if ($enable) $this->fnExecute = 'adodb_log_sql';
+               else $this->fnExecute = false;
+               
+               $old = $this->_logsql;  
+               $this->_logsql = $enable;
+               if ($enable && !$old) $this->_affected = false;
+               return $old;
+       }
+       
+       function GetCharSet()
+       {
+               return false;
+       }
+       
+       /**
+       * Usage:
+       *       UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
+       *
+       *       $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
+       *       $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
+       */
+       function UpdateClob($table,$column,$val,$where)
+       {
+               return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
+       }
+       
+       
+       /**
+       *  Change the SQL connection locale to a specified locale.
+       *  This is used to get the date formats written depending on the client locale.
+       */
+       function SetDateLocale($locale = 'En')
+       {
+               $this->locale = $locale;
+               switch ($locale)
+               {
+                       default:
+                       case 'En':
+                               $this->fmtDate="Y-m-d";
+                               $this->fmtTimeStamp = "Y-m-d H:i:s";
+                               break;
+       
+                       case 'Fr':
+                       case 'Ro':
+                       case 'It':
+                               $this->fmtDate="d-m-Y";
+                               $this->fmtTimeStamp = "d-m-Y H:i:s";
+                               break;
+                               
+                       case 'Ge':
+                               $this->fmtDate="d.m.Y";
+                               $this->fmtTimeStamp = "d.m.Y H:i:s";
+                               break;
+               }
+       }
+       
+       
+       /**
+        *  $meta       contains the desired type, which could be...
+        *      C for character. You will have to define the precision yourself.
+        *      X for teXt. For unlimited character lengths.
+        *      B for Binary
+        *  F for floating point, with no need to define scale and precision
+        *      N for decimal numbers, you will have to define the (scale, precision) yourself
+        *      D for date
+        *      T for timestamp
+        *      L for logical/Boolean
+        *      I for integer
+        *      R for autoincrement counter/integer
+        *  and if you want to use double-byte, add a 2 to the end, like C2 or X2.
+        * 
+        *
+        * @return the actual type of the data or false if no such type available
+       */
+       function ActualType($meta)
+       {
+               switch($meta) {
+               case 'C':
+               case 'X':
+                       return 'VARCHAR';
+               case 'B':
+                       
+               case 'D':
+               case 'T':
+               case 'L':
+               
+               case 'R':
+                       
+               case 'I':
+               case 'N':
+                       return false;
+               }
+       }
+
+       
+       /**
+        * Close Connection
+        */
+       function Close() 
+       {
+               return $this->_close();
+               
+               // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need 
+               // to be closed too!
+               //if ($this->_isPersistentConnection != true) return $this->_close();
+               //else return true;     
+       }
+       
+       /**
+        * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
+        *
+        * @return true if succeeded or false if database does not support transactions
+        */
+       function BeginTrans() {return false;}
+       
+       
+       /**
+        * If database does not support transactions, always return true as data always commited
+        *
+        * @param $ok  set to false to rollback transaction, true to commit
+        *
+        * @return true/false.
+        */
+       function CommitTrans($ok=true) 
+       { return true;}
+       
+       
+       /**
+        * If database does not support transactions, rollbacks always fail, so return false
+        *
+        * @return true/false.
+        */
+       function RollbackTrans() 
+       { return false;}
+
+
+       /**
+        * return the databases that the driver can connect to. 
+        * Some databases will return an empty array.
+        *
+        * @return an array of database names.
+        */
+               function MetaDatabases() 
+               {
+               global $ADODB_FETCH_MODE;
+               
+                       if ($this->metaDatabasesSQL) {
+                               $save = $ADODB_FETCH_MODE; 
+                               $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 
+                               
+                               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+                               
+                               $arr = $this->GetCol($this->metaDatabasesSQL);
+                               if (isset($savem)) $this->SetFetchMode($savem);
+                               $ADODB_FETCH_MODE = $save; 
+                       
+                               return $arr;
+                       }
+                       
+                       return false;
+               }
+               
+       /**
+        * @param ttype can either be 'VIEW' or 'TABLE' or false. 
+        *              If false, both views and tables are returned.
+        *              "VIEW" returns only views
+        *              "TABLE" returns only tables
+        * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
+        * @param mask  is the input mask - only supported by oci8 and postgresql
+        *
+        * @return  array of tables for current database.
+        */ 
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+       {
+       global $ADODB_FETCH_MODE;
+       
+               if ($mask) return false;
+               
+               if ($this->metaTablesSQL) {
+                       // complicated state saving by the need for backward compat
+                       $save = $ADODB_FETCH_MODE; 
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 
+                       
+                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+                       
+                       $rs = $this->Execute($this->metaTablesSQL);
+                       if (isset($savem)) $this->SetFetchMode($savem);
+                       $ADODB_FETCH_MODE = $save; 
+                       
+                       if ($rs === false) return false;
+                       $arr =& $rs->GetArray();
+                       $arr2 = array();
+                       
+                       if ($hast = ($ttype && isset($arr[0][1]))) { 
+                               $showt = strncmp($ttype,'T',1);
+                       }
+                       
+                       for ($i=0; $i < sizeof($arr); $i++) {
+                               if ($hast) {
+                                       if ($showt == 0) {
+                                               if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
+                                       } else {
+                                               if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
+                                       }
+                               } else
+                                       $arr2[] = trim($arr[$i][0]);
+                       }
+                       $rs->Close();
+                       return $arr2;
+               }
+               return false;
+       }
+       
+       
+       function _findschema(&$table,&$schema)
+       {
+               if (!$schema && ($at = strpos($table,'.')) !== false) {
+                       $schema = substr($table,0,$at);
+                       $table = substr($table,$at+1);
+               }
+       }
+       
+       /**
+        * List columns in a database as an array of ADOFieldObjects. 
+        * See top of file for definition of object.
+        *
+        * @param table table name to query
+        * @param upper uppercase table name (required by some databases)
+        * @schema is optional database schema to use - not supported by all databases.
+        *
+        * @return  array of ADOFieldObjects for current table.
+        */
+       function &MetaColumns($table,$upper=true) 
+       {
+       global $ADODB_FETCH_MODE;
+               
+               if (!empty($this->metaColumnsSQL)) {
+               
+                       $schema = false;
+                       $this->_findschema($table,$schema);
+               
+                       $save = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table));
+                       if (isset($savem)) $this->SetFetchMode($savem);
+                       $ADODB_FETCH_MODE = $save;
+                       if ($rs === false) return false;
+
+                       $retarr = array();
+                       while (!$rs->EOF) { //print_r($rs->fields);
+                               $fld =& new ADOFieldObject();
+                               $fld->name = $rs->fields[0];
+                               $fld->type = $rs->fields[1];
+                               if (isset($rs->fields[3]) && $rs->fields[3]) {
+                                       if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
+                                       $fld->scale = $rs->fields[4];
+                                       if ($fld->scale>0) $fld->max_length += 1;
+                               } else
+                                       $fld->max_length = $rs->fields[2];
+                                       
+                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     
+                               else $retarr[strtoupper($fld->name)] = $fld;
+                               $rs->MoveNext();
+                       }
+                       $rs->Close();
+                       return $retarr; 
+               }
+               return false;
+       }
+       
+    /**
+      * List indexes on a table as an array.
+      * @param table        table name to query
+      * @param primary include primary keys.
+         *
+      * @return array of indexes on current table.
+      */
+     function &MetaIndexes($table, $primary = false, $owner = false)
+     {
+             return FALSE;
+     }
+
+       /**
+        * List columns names in a table as an array. 
+        * @param table table name to query
+        *
+        * @return  array of column names for current table.
+        */ 
+       function &MetaColumnNames($table) 
+       {
+               $objarr =& $this->MetaColumns($table);
+               if (!is_array($objarr)) return false;
+               
+               $arr = array();
+               foreach($objarr as $v) {
+                       $arr[] = $v->name;
+               }
+               return $arr;
+       }
+                       
+       /**
+        * Different SQL databases used different methods to combine strings together.
+        * This function provides a wrapper. 
+        * 
+        * param s      variable number of string parameters
+        *
+        * Usage: $db->Concat($str1,$str2);
+        * 
+        * @return concatenated string
+        */      
+       function Concat()
+       {       
+               $arr = func_get_args();
+               return implode($this->concat_operator, $arr);
+       }
+       
+       
+       /**
+        * Converts a date "d" to a string that the database can understand.
+        *
+        * @param d     a date in Unix date time format.
+        *
+        * @return  date string in database date format
+        */
+       function DBDate($d)
+       {
+               if (empty($d) && $d !== 0) return 'null';
+
+               if (is_string($d) && !is_numeric($d)) {
+                       if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
+                       if ($this->isoDates) return "'$d'";
+                       $d = ADOConnection::UnixDate($d);
+               }
+
+               return adodb_date($this->fmtDate,$d);
+       }
+       
+       
+       /**
+        * Converts a timestamp "ts" to a string that the database can understand.
+        *
+        * @param ts    a timestamp in Unix date time format.
+        *
+        * @return  timestamp string in database timestamp format
+        */
+       function DBTimeStamp($ts)
+       {
+               if (empty($ts) && $ts !== 0) return 'null';
+
+               # strlen(14) allows YYYYMMDDHHMMSS format
+               if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) 
+                       return adodb_date($this->fmtTimeStamp,$ts);
+               
+               if ($ts === 'null') return $ts;
+               if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
+               
+               $ts = ADOConnection::UnixTimeStamp($ts);
+               return adodb_date($this->fmtTimeStamp,$ts);
+       }
+       
+       /**
+        * Also in ADORecordSet.
+        * @param $v is a date string in YYYY-MM-DD format
+        *
+        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
+        */
+       function UnixDate($v)
+       {
+               if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", 
+                       ($v), $rr)) return false;
+
+               if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
+               // h-m-s-MM-DD-YY
+               return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
+       }
+       
+
+       /**
+        * Also in ADORecordSet.
+        * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
+        *
+        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
+        */
+       function UnixTimeStamp($v)
+       {
+               if (!preg_match( 
+                       "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", 
+                       ($v), $rr)) return false;
+                       
+               if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
+       
+               // h-m-s-MM-DD-YY
+               if (!isset($rr[5])) return  adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
+               return  @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
+       }
+       
+       /**
+        * Also in ADORecordSet.
+        *
+        * Format database date based on user defined format.
+        *
+        * @param v     is the character date in YYYY-MM-DD format, returned by database
+        * @param fmt   is the format to apply to it, using date()
+        *
+        * @return a date formated as user desires
+        */
+        
+       function UserDate($v,$fmt='Y-m-d')
+       {
+               $tt = $this->UnixDate($v);
+               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
+               if (($tt === false || $tt == -1) && $v != false) return $v;
+               else if ($tt == 0) return $this->emptyDate;
+               else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
+               }
+               
+               return adodb_date($fmt,$tt);
+       
+       }
+       
+               /**
+        *
+        * @param v     is the character timestamp in YYYY-MM-DD hh:mm:ss format
+        * @param fmt   is the format to apply to it, using date()
+        *
+        * @return a timestamp formated as user desires
+        */
+       function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
+       {
+               # strlen(14) allows YYYYMMDDHHMMSS format
+               if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
+               $tt = $this->UnixTimeStamp($v);
+               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
+               if (($tt === false || $tt == -1) && $v != false) return $v;
+               if ($tt == 0) return $this->emptyTimeStamp;
+               return adodb_date($fmt,$tt);
+       }
+       
+       /**
+       * Quotes a string, without prefixing nor appending quotes. 
+       */
+       function addq($s,$magicq=false)
+       {
+               if (!$magic_quotes) {
+               
+                       if ($this->replaceQuote[0] == '\\'){
+                               // only since php 4.0.5
+                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
+                               //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
+                       }
+                       return  str_replace("'",$this->replaceQuote,$s);
+               }
+               
+               // undo magic quotes for "
+               $s = str_replace('\\"','"',$s);
+               
+               if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything
+                       return $s;
+               else {// change \' to '' for sybase/mssql
+                       $s = str_replace('\\\\','\\',$s);
+                       return str_replace("\\'",$this->replaceQuote,$s);
+               }
+       }
+       
+       /**
+        * Correctly quotes a string so that all strings are escaped. We prefix and append
+        * to the string single-quotes.
+        * An example is  $db->qstr("Don't bother",magic_quotes_runtime());
+        * 
+        * @param s                     the string to quote
+        * @param [magic_quotes]        if $s is GET/POST var, set to get_magic_quotes_gpc().
+        *                              This undoes the stupidity of magic quotes for GPC.
+        *
+        * @return  quoted string to be sent back to database
+        */
+       function qstr($s,$magic_quotes=false)
+       {       
+               if (!$magic_quotes) {
+               
+                       if ($this->replaceQuote[0] == '\\'){
+                               // only since php 4.0.5
+                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
+                               //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
+                       }
+                       return  "'".str_replace("'",$this->replaceQuote,$s)."'";
+               }
+               
+               // undo magic quotes for "
+               $s = str_replace('\\"','"',$s);
+               
+               if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything
+                       return "'$s'";
+               else {// change \' to '' for sybase/mssql
+                       $s = str_replace('\\\\','\\',$s);
+                       return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
+               }
+       }
+       
+       
+       /**
+       * Will select the supplied $page number from a recordset, given that it is paginated in pages of 
+       * $nrows rows per page. It also saves two boolean values saying if the given page is the first 
+       * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
+       *
+       * See readme.htm#ex8 for an example of usage.
+       *
+       * @param sql
+       * @param nrows          is the number of rows per page to get
+       * @param page           is the page number to get (1-based)
+       * @param [inputarr]     array of bind variables
+       * @param [secs2cache]           is a private parameter only used by jlim
+       * @return               the recordset ($rs->databaseType == 'array')
+       *
+       * NOTE: phpLens uses a different algorithm and does not use PageExecute().
+       *
+       */
+       function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
+       {
+               global $ADODB_INCLUDED_LIB;
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
+               if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
+               return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
+
+       }
+       
+               
+       /**
+       * Will select the supplied $page number from a recordset, given that it is paginated in pages of 
+       * $nrows rows per page. It also saves two boolean values saying if the given page is the first 
+       * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination.
+       *
+       * @param secs2cache     seconds to cache data, set to 0 to force query
+       * @param sql
+       * @param nrows          is the number of rows per page to get
+       * @param page           is the page number to get (1-based)
+       * @param [inputarr]     array of bind variables
+       * @return               the recordset ($rs->databaseType == 'array')
+       */
+       function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) 
+       {
+               /*switch($this->dataProvider) {
+               case 'postgres':
+               case 'mysql': 
+                       break;
+               default: $secs2cache = 0; break;
+               }*/
+               $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
+               return $rs;
+       }
+
+} // end class ADOConnection
+       
+       
+       
+       //==============================================================================================        
+       // CLASS ADOFetchObj
+       //==============================================================================================        
+               
+       /**
+       * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
+       */
+       class ADOFetchObj {
+       };
+       
+       //==============================================================================================        
+       // CLASS ADORecordSet_empty
+       //==============================================================================================        
+       
+       /**
+       * Lightweight recordset when there are no records to be returned
+       */
+       class ADORecordSet_empty
+       {
+               var $dataProvider = 'empty';
+               var $databaseType = false;
+               var $EOF = true;
+               var $_numOfRows = 0;
+               var $fields = false;
+               var $connection = false;
+               function RowCount() {return 0;}
+               function RecordCount() {return 0;}
+               function PO_RecordCount(){return 0;}
+               function Close(){return true;}
+               function FetchRow() {return false;}
+               function FieldCount(){ return 0;}
+       }
+       
+       //==============================================================================================        
+       // DATE AND TIME FUNCTIONS
+       //==============================================================================================        
+       include_once(ADODB_DIR.'/adodb-time.inc.php');
+       
+       //==============================================================================================        
+       // CLASS ADORecordSet
+       //==============================================================================================        
+
+       if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
+       else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
+   /**
+        * RecordSet class that represents the dataset returned by the database.
+        * To keep memory overhead low, this class holds only the current row in memory.
+        * No prefetching of data is done, so the RecordCount() can return -1 ( which
+        * means recordcount not known).
+        */
+       class ADORecordSet extends ADODB_BASE_RS {
+       /*
+        * public variables     
+        */
+       var $dataProvider = "native";
+       var $fields = false;    /// holds the current row data
+       var $blobSize = 100;    /// any varchar/char field this size or greater is treated as a blob
+                                                       /// in other words, we use a text area for editing.
+       var $canSeek = false;   /// indicates that seek is supported
+       var $sql;                               /// sql text
+       var $EOF = false;               /// Indicates that the current record position is after the last record in a Recordset object. 
+       
+       var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
+       var $emptyDate = '&nbsp;'; /// what to display when $time==0
+       var $debug = false;
+       var $timeCreated=0;     /// datetime in Unix format rs created -- for cached recordsets
+
+       var $bind = false;              /// used by Fields() to hold array - should be private?
+       var $fetchMode;                 /// default fetch mode
+       var $connection = false; /// the parent connection
+       /*
+        *      private variables       
+        */
+       var $_numOfRows = -1;   /** number of rows, or -1 */
+       var $_numOfFields = -1; /** number of fields in recordset */
+       var $_queryID = -1;             /** This variable keeps the result link identifier.     */
+       var $_currentRow = -1;  /** This variable keeps the current row in the Recordset.       */
+       var $_closed = false;   /** has recordset been closed */
+       var $_inited = false;   /** Init() should only be called once */
+       var $_obj;                              /** Used by FetchObj */
+       var $_names;                    /** Used by FetchObj */
+       
+       var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */
+       var $_atFirstPage = false;      /** Added by Iván Oliva to implement recordset pagination */
+       var $_atLastPage = false;       /** Added by Iván Oliva to implement recordset pagination */
+       var $_lastPageNo = -1; 
+       var $_maxRecordCount = 0;
+       var $datetime = false;
+       
+       /**
+        * Constructor
+        *
+        * @param queryID       this is the queryID returned by ADOConnection->_query()
+        *
+        */
+       function ADORecordSet($queryID) 
+       {
+               $this->_queryID = $queryID;
+       }
+       
+       
+       
+       function Init()
+       {
+               if ($this->_inited) return;
+               $this->_inited = true;
+               if ($this->_queryID) @$this->_initrs();
+               else {
+                       $this->_numOfRows = 0;
+                       $this->_numOfFields = 0;
+               }
+               if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
+                       
+                       $this->_currentRow = 0;
+                       if ($this->EOF = ($this->_fetch() === false)) {
+                               $this->_numOfRows = 0; // _numOfRows could be -1
+                       }
+               } else {
+                       $this->EOF = true;
+               }
+       }
+       
+       
+       /**
+        * Generate a SELECT tag string from a recordset, and return the string.
+        * If the recordset has 2 cols, we treat the 1st col as the containing 
+        * the text to display to the user, and 2nd col as the return value. Default
+        * strings are compared with the FIRST column.
+        *
+        * @param name                  name of SELECT tag
+        * @param [defstr]              the value to hilite. Use an array for multiple hilites for listbox.
+        * @param [blank1stItem]        true to leave the 1st item in list empty
+        * @param [multiple]            true for listbox, false for popup
+        * @param [size]                #rows to show for listbox. not used by popup
+        * @param [selectAttr]          additional attributes to defined for SELECT tag.
+        *                              useful for holding javascript onChange='...' handlers.
+        & @param [compareFields0]      when we have 2 cols in recordset, we compare the defstr with 
+        *                              column 0 (1st col) if this is true. This is not documented.
+        *
+        * @return HTML
+        *
+        * changes by glen.davies@cce.ac.nz to support multiple hilited items
+        */
+       function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
+                       $size=0, $selectAttr='',$compareFields0=true)
+       {
+               global $ADODB_INCLUDED_LIB;
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
+               return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
+                       $size, $selectAttr,$compareFields0);
+       }
+       
+       /**
+        * Generate a SELECT tag string from a recordset, and return the string.
+        * If the recordset has 2 cols, we treat the 1st col as the containing 
+        * the text to display to the user, and 2nd col as the return value. Default
+        * strings are compared with the SECOND column.
+        *
+        */
+       function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')  
+       {
+               global $ADODB_INCLUDED_LIB;
+               if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
+               return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple,
+                       $size, $selectAttr,false);
+       }
+
+
+       /**
+        * return recordset as a 2-dimensional array.
+        *
+        * @param [nRows]  is the number of rows to return. -1 means every row.
+        *
+        * @return an array indexed by the rows (0-based) from the recordset
+        */
+       function &GetArray($nRows = -1) 
+       {
+       global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows);
+               
+               $results = array();
+               $cnt = 0;
+               while (!$this->EOF && $nRows != $cnt) {
+                       $results[] = $this->fields;
+                       $this->MoveNext();
+                       $cnt++;
+               }
+               return $results;
+       }
+       
+       function &GetAll($nRows = -1)
+       {
+               $arr =& $this->GetArray($nRows);
+               return $arr;
+       }
+       
+       /*
+       * Some databases allow multiple recordsets to be returned. This function
+       * will return true if there is a next recordset, or false if no more.
+       */
+       function NextRecordSet()
+       {
+               return false;
+       }
+       
+       /**
+        * return recordset as a 2-dimensional array. 
+        * Helper function for ADOConnection->SelectLimit()
+        *
+        * @param offset        is the row to start calculations from (1-based)
+        * @param [nrows]       is the number of rows to return
+        *
+        * @return an array indexed by the rows (0-based) from the recordset
+        */
+       function &GetArrayLimit($nrows,$offset=-1) 
+       {       
+               if ($offset <= 0) {
+                       $arr =& $this->GetArray($nrows);
+                       return $arr;
+               } 
+               
+               $this->Move($offset);
+               
+               $results = array();
+               $cnt = 0;
+               while (!$this->EOF && $nrows != $cnt) {
+                       $results[$cnt++] = $this->fields;
+                       $this->MoveNext();
+               }
+               
+               return $results;
+       }
+       
+       
+       /**
+        * Synonym for GetArray() for compatibility with ADO.
+        *
+        * @param [nRows]  is the number of rows to return. -1 means every row.
+        *
+        * @return an array indexed by the rows (0-based) from the recordset
+        */
+       function &GetRows($nRows = -1) 
+       {
+               $arr =& $this->GetArray($nRows);
+               return $arr;
+       }
+       
+       /**
+        * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. 
+        * The first column is treated as the key and is not included in the array. 
+        * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
+        * $force_array == true.
+        *
+        * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
+        *      array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
+        *      read the source.
+        *
+        * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and 
+        * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
+        *
+        * @return an associative array indexed by the first column of the array, 
+        *      or false if the  data has less than 2 cols.
+        */
+       function &GetAssoc($force_array = false, $first2cols = false) {
+               $cols = $this->_numOfFields;
+               if ($cols < 2) {
+                       return false;
+               }
+               $numIndex = isset($this->fields[0]);
+               $results = array();
+               
+               if (!$first2cols && ($cols > 2 || $force_array)) {
+                       if ($numIndex) {
+                               while (!$this->EOF) {
+                                       $results[trim($this->fields[0])] = array_slice($this->fields, 1);
+                                       $this->MoveNext();
+                               }
+                       } else {
+                               while (!$this->EOF) {
+                                       $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
+                                       $this->MoveNext();
+                               }
+                       }
+               } else {
+                       // return scalar values
+                       if ($numIndex) {
+                               while (!$this->EOF) {
+                               // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
+                                       $results[trim(($this->fields[0]))] = $this->fields[1];
+                                       $this->MoveNext();
+                               }
+                       } else {
+                               while (!$this->EOF) {
+                               // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
+                                       $v1 = trim(reset($this->fields));
+                                       $v2 = ''.next($this->fields); 
+                                       $results[$v1] = $v2;
+                                       $this->MoveNext();
+                               }
+                       }
+               }
+               return $results; 
+       }
+       
+       
+       /**
+        *
+        * @param v     is the character timestamp in YYYY-MM-DD hh:mm:ss format
+        * @param fmt   is the format to apply to it, using date()
+        *
+        * @return a timestamp formated as user desires
+        */
+       function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
+       {
+               if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
+               $tt = $this->UnixTimeStamp($v);
+               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
+               if (($tt === false || $tt == -1) && $v != false) return $v;
+               if ($tt === 0) return $this->emptyTimeStamp;
+               return adodb_date($fmt,$tt);
+       }
+       
+       
+       /**
+        * @param v     is the character date in YYYY-MM-DD format, returned by database
+        * @param fmt   is the format to apply to it, using date()
+        *
+        * @return a date formated as user desires
+        */
+       function UserDate($v,$fmt='Y-m-d')
+       {
+               $tt = $this->UnixDate($v);
+               // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
+               if (($tt === false || $tt == -1) && $v != false) return $v;
+               else if ($tt == 0) return $this->emptyDate;
+               else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
+               }
+               return adodb_date($fmt,$tt);
+       
+       }
+       
+       
+       /**
+        * @param $v is a date string in YYYY-MM-DD format
+        *
+        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
+        */
+       function UnixDate($v)
+       {
+               
+               if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", 
+                       ($v), $rr)) return false;
+                       
+               if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
+               // h-m-s-MM-DD-YY
+               return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
+       }
+       
+
+       /**
+        * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
+        *
+        * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
+        */
+       function UnixTimeStamp($v)
+       {
+               
+               if (!preg_match( 
+                       "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", 
+                       ($v), $rr)) return false;
+               if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
+       
+               // h-m-s-MM-DD-YY
+               if (!isset($rr[5])) return  adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
+               return  @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
+       }
+       
+       
+       /**
+       * PEAR DB Compat - do not use internally
+       */
+       function Free()
+       {
+               return $this->Close();
+       }
+       
+       
+       /**
+       * PEAR DB compat, number of rows
+       */
+       function NumRows()
+       {
+               return $this->_numOfRows;
+       }
+       
+       
+       /**
+       * PEAR DB compat, number of cols
+       */
+       function NumCols()
+       {
+               return $this->_numOfFields;
+       }
+       
+       /**
+       * Fetch a row, returning false if no more rows. 
+       * This is PEAR DB compat mode.
+       *
+       * @return false or array containing the current record
+       */
+       function FetchRow()
+       {
+               if ($this->EOF) return false;
+               $arr = $this->fields;
+               $this->_currentRow++;
+               if (!$this->_fetch()) $this->EOF = true;
+               return $arr;
+       }
+       
+       
+       /**
+       * Fetch a row, returning PEAR_Error if no more rows. 
+       * This is PEAR DB compat mode.
+       *
+       * @return DB_OK or error object
+       */
+       function FetchInto(&$arr)
+       {
+               if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
+               $arr = $this->fields;
+               $this->MoveNext();
+               return 1; // DB_OK
+       }
+       
+       
+       /**
+        * Move to the first row in the recordset. Many databases do NOT support this.
+        *
+        * @return true or false
+        */
+       function MoveFirst() 
+       {
+               if ($this->_currentRow == 0) return true;
+               return $this->Move(0);                  
+       }                       
+
+       
+       /**
+        * Move to the last row in the recordset. 
+        *
+        * @return true or false
+        */
+       function MoveLast() 
+       {
+               if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
+               if ($this->EOF) return false;
+               while (!$this->EOF) {
+                       $f = $this->fields;
+                       $this->MoveNext();
+               }
+               $this->fields = $f;
+               $this->EOF = false;
+               return true;
+       }
+       
+       
+       /**
+        * Move to next record in the recordset.
+        *
+        * @return true if there still rows available, or false if there are no more rows (EOF).
+        */
+       function MoveNext() 
+       {
+               if (!$this->EOF) {
+                       $this->_currentRow++;
+                       if ($this->_fetch()) return true;
+               }
+               $this->EOF = true;
+               /* -- tested error handling when scrolling cursor -- seems useless.
+               $conn = $this->connection;
+               if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
+                       $fn = $conn->raiseErrorFn;
+                       $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
+               }
+               */
+               return false;
+       }       
+       
+       /**
+        * Random access to a specific row in the recordset. Some databases do not support
+        * access to previous rows in the databases (no scrolling backwards).
+        *
+        * @param rowNumber is the row to move to (0-based)
+        *
+        * @return true if there still rows available, or false if there are no more rows (EOF).
+        */
+       function Move($rowNumber = 0) 
+       {
+               $this->EOF = false;
+               if ($rowNumber == $this->_currentRow) return true;
+               if ($rowNumber >= $this->_numOfRows)
+                       if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
+                               
+               if ($this->canSeek) { 
+       
+                       if ($this->_seek($rowNumber)) {
+                               $this->_currentRow = $rowNumber;
+                               if ($this->_fetch()) {
+                                       return true;
+                               }
+                       } else {
+                               $this->EOF = true;
+                               return false;
+                       }
+               } else {
+                       if ($rowNumber < $this->_currentRow) return false;
+                       global $ADODB_EXTENSION;
+                       if ($ADODB_EXTENSION) {
+                               while (!$this->EOF && $this->_currentRow < $rowNumber) {
+                                       adodb_movenext($this);
+                               }
+                       } else {
+                       
+                               while (! $this->EOF && $this->_currentRow < $rowNumber) {
+                                       $this->_currentRow++;
+                                       
+                                       if (!$this->_fetch()) $this->EOF = true;
+                               }
+                       }
+                       return !($this->EOF);
+               }
+               
+               $this->fields = false;  
+               $this->EOF = true;
+               return false;
+       }
+       
+               
+       /**
+        * Get the value of a field in the current row by column name.
+        * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
+        * 
+        * @param colname  is the field to access
+        *
+        * @return the value of $colname column
+        */
+       function Fields($colname)
+       {
+               return $this->fields[$colname];
+       }
+       
+       function GetAssocKeys($upper=true)
+       {
+               $this->bind = array();
+               for ($i=0; $i < $this->_numOfFields; $i++) {
+                       $o =& $this->FetchField($i);
+                       if ($upper === 2) $this->bind[$o->name] = $i;
+                       else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
+               }
+       }
+       
+  /**
+   * Use associative array to get fields array for databases that do not support
+   * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it
+   *
+   * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
+   * before you execute your SQL statement, and access $rs->fields['col'] directly.
+   *
+   * $upper  0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
+   */
+       function &GetRowAssoc($upper=1)
+       {
+               $record = array();
+        //     if (!$this->fields) return $record;
+               
+               if (!$this->bind) {
+                       $this->GetAssocKeys($upper);
+               }
+               
+               foreach($this->bind as $k => $v) {
+                       $record[$k] = $this->fields[$v];
+               }
+
+               return $record;
+       }
+       
+       
+       /**
+        * Clean up recordset
+        *
+        * @return true or false
+        */
+       function Close() 
+       {
+               // free connection object - this seems to globally free the object
+               // and not merely the reference, so don't do this...
+               // $this->connection = false; 
+               if (!$this->_closed) {
+                       $this->_closed = true;
+                       return $this->_close();         
+               } else
+                       return true;
+       }
+       
+       /**
+        * synonyms RecordCount and RowCount    
+        *
+        * @return the number of rows or -1 if this is not supported
+        */
+       function RecordCount() {return $this->_numOfRows;}
+       
+       
+       /*
+       * If we are using PageExecute(), this will return the maximum possible rows
+       * that can be returned when paging a recordset.
+       */
+       function MaxRecordCount()
+       {
+               return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
+       }
+       
+       /**
+        * synonyms RecordCount and RowCount    
+        *
+        * @return the number of rows or -1 if this is not supported
+        */
+       function RowCount() {return $this->_numOfRows;} 
+       
+
+        /**
+        * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
+        *
+        * @return  the number of records from a previous SELECT. All databases support this.
+        *
+        * But aware possible problems in multiuser environments. For better speed the table
+        * must be indexed by the condition. Heavy test this before deploying.
+        */ 
+       function PO_RecordCount($table="", $condition="") {
+               
+               $lnumrows = $this->_numOfRows;
+               // the database doesn't support native recordcount, so we do a workaround
+               if ($lnumrows == -1 && $this->connection) {
+                       IF ($table) {
+                               if ($condition) $condition = " WHERE " . $condition; 
+                               $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
+                               if ($resultrows) $lnumrows = reset($resultrows->fields);
+                       }
+               }
+               return $lnumrows;
+       }
+       
+       /**
+        * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
+        */
+       function CurrentRow() {return $this->_currentRow;}
+       
+       /**
+        * synonym for CurrentRow -- for ADO compat
+        *
+        * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
+        */
+       function AbsolutePosition() {return $this->_currentRow;}
+       
+       /**
+        * @return the number of columns in the recordset. Some databases will set this to 0
+        * if no records are returned, others will return the number of columns in the query.
+        */
+       function FieldCount() {return $this->_numOfFields;}   
+
+
+       /**
+        * Get the ADOFieldObject of a specific column.
+        *
+        * @param fieldoffset   is the column position to access(0-based).
+        *
+        * @return the ADOFieldObject for that column, or false.
+        */
+       function &FetchField($fieldoffset) 
+       {
+               // must be defined by child class
+       }       
+       
+       /**
+        * Get the ADOFieldObjects of all columns in an array.
+        *
+        */
+       function FieldTypesArray()
+       {
+               $arr = array();
+               for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) 
+                       $arr[] = $this->FetchField($i);
+               return $arr;
+       }
+       
+       /**
+       * Return the fields array of the current row as an object for convenience.
+       * The default case is lowercase field names.
+       *
+       * @return the object with the properties set to the fields of the current row
+       */
+       function &FetchObj()
+       {
+               $o =& $this->FetchObject(false);
+               return $o;
+       }
+       
+       /**
+       * Return the fields array of the current row as an object for convenience.
+       * The default case is uppercase.
+       * 
+       * @param $isupper to set the object property names to uppercase
+       *
+       * @return the object with the properties set to the fields of the current row
+       */
+       function &FetchObject($isupper=true)
+       {
+               if (empty($this->_obj)) {
+                       $this->_obj =& new ADOFetchObj();
+                       $this->_names = array();
+                       for ($i=0; $i <$this->_numOfFields; $i++) {
+                               $f = $this->FetchField($i);
+                               $this->_names[] = $f->name;
+                       }
+               }
+               $i = 0;
+               $o = &$this->_obj;
+               for ($i=0; $i <$this->_numOfFields; $i++) {
+                       $name = $this->_names[$i];
+                       if ($isupper) $n = strtoupper($name);
+                       else $n = $name;
+                       
+                       $o->$n = $this->Fields($name);
+               }
+               return $o;
+       }
+       
+       /**
+       * Return the fields array of the current row as an object for convenience.
+       * The default is lower-case field names.
+       * 
+       * @return the object with the properties set to the fields of the current row,
+       *       or false if EOF
+       *
+       * Fixed bug reported by tim@orotech.net
+       */
+       function &FetchNextObj()
+       {
+               return $this->FetchNextObject(false);
+       }
+       
+       
+       /**
+       * Return the fields array of the current row as an object for convenience. 
+       * The default is upper case field names.
+       * 
+       * @param $isupper to set the object property names to uppercase
+       *
+       * @return the object with the properties set to the fields of the current row,
+       *       or false if EOF
+       *
+       * Fixed bug reported by tim@orotech.net
+       */
+       function &FetchNextObject($isupper=true)
+       {
+               $o = false;
+               if ($this->_numOfRows != 0 && !$this->EOF) {
+                       $o = $this->FetchObject($isupper);      
+                       $this->_currentRow++;
+                       if ($this->_fetch()) return $o;
+               }
+               $this->EOF = true;
+               return $o;
+       }
+       
+       /**
+        * Get the metatype of the column. This is used for formatting. This is because
+        * many databases use different names for the same type, so we transform the original
+        * type to our standardised version which uses 1 character codes:
+        *
+        * @param t  is the type passed in. Normally is ADOFieldObject->type.
+        * @param len is the maximum length of that field. This is because we treat character
+        *      fields bigger than a certain size as a 'B' (blob).
+        * @param fieldobj is the field object returned by the database driver. Can hold
+        *      additional info (eg. primary_key for mysql).
+        * 
+        * @return the general type of the data: 
+        *      C for character < 200 chars
+        *      X for teXt (>= 200 chars)
+        *      B for Binary
+        *      N for numeric floating point
+        *      D for date
+        *      T for timestamp
+        *      L for logical/Boolean
+        *      I for integer
+        *      R for autoincrement counter/integer
+        * 
+        *
+       */
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+       // changed in 2.32 to hashing instead of switch stmt for speed...
+       static $typeMap = array(
+               'VARCHAR' => 'C',
+               'VARCHAR2' => 'C',
+               'CHAR' => 'C',
+               'C' => 'C',
+               'STRING' => 'C',
+               'NCHAR' => 'C',
+               'NVARCHAR' => 'C',
+               'VARYING' => 'C',
+               'BPCHAR' => 'C',
+               'CHARACTER' => 'C',
+               'INTERVAL' => 'C',  # Postgres
+               ##
+               'LONGCHAR' => 'X',
+               'TEXT' => 'X',
+               'NTEXT' => 'X',
+               'M' => 'X',
+               'X' => 'X',
+               'CLOB' => 'X',
+               'NCLOB' => 'X',
+               'LVARCHAR' => 'X',
+               ##
+               'BLOB' => 'B',
+               'IMAGE' => 'B',
+               'BINARY' => 'B',
+               'VARBINARY' => 'B',
+               'LONGBINARY' => 'B',
+               'B' => 'B',
+               ##
+               'YEAR' => 'D', // mysql
+               'DATE' => 'D',
+               'D' => 'D',
+               ##
+               'TIME' => 'T',
+               'TIMESTAMP' => 'T',
+               'DATETIME' => 'T',
+               'TIMESTAMPTZ' => 'T',
+               'T' => 'T',
+               ##
+               'BOOL' => 'L',
+               'BOOLEAN' => 'L', 
+               'BIT' => 'L',
+               'L' => 'L',
+               ##
+               'COUNTER' => 'R',
+               'R' => 'R',
+               'SERIAL' => 'R', // ifx
+               'INT IDENTITY' => 'R',
+               ##
+               'INT' => 'I',
+               'INTEGER' => 'I',
+               'INTEGER UNSIGNED' => 'I',
+               'SHORT' => 'I',
+               'TINYINT' => 'I',
+               'SMALLINT' => 'I',
+               'I' => 'I',
+               ##
+               'LONG' => 'N', // interbase is numeric, oci8 is blob
+               'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
+               'DECIMAL' => 'N',
+               'DEC' => 'N',
+               'REAL' => 'N',
+               'DOUBLE' => 'N',
+               'DOUBLE PRECISION' => 'N',
+               'SMALLFLOAT' => 'N',
+               'FLOAT' => 'N',
+               'NUMBER' => 'N',
+               'NUM' => 'N',
+               'NUMERIC' => 'N',
+               'MONEY' => 'N',
+               
+               ## informix 9.2
+               'SQLINT' => 'I', 
+               'SQLSERIAL' => 'I', 
+               'SQLSMINT' => 'I', 
+               'SQLSMFLOAT' => 'N', 
+               'SQLFLOAT' => 'N', 
+               'SQLMONEY' => 'N', 
+               'SQLDECIMAL' => 'N', 
+               'SQLDATE' => 'D', 
+               'SQLVCHAR' => 'C', 
+               'SQLCHAR' => 'C', 
+               'SQLDTIME' => 'T', 
+               'SQLINTERVAL' => 'N', 
+               'SQLBYTES' => 'B', 
+               'SQLTEXT' => 'X' 
+               );
+               
+               $tmap = false;
+               $t = strtoupper($t);
+               $tmap = @$typeMap[$t];
+               switch ($tmap) {
+               case 'C':
+               
+                       // is the char field is too long, return as text field... 
+                       if ($this->blobSize >= 0) {
+                               if ($len > $this->blobSize) return 'X';
+                       } else if ($len > 250) {
+                               return 'X';
+                       }
+                       return 'C';
+                       
+               case 'I':
+                       if (!empty($fieldobj->primary_key)) return 'R';
+                       return 'I';
+               
+               case false:
+                       return 'N';
+                       
+               case 'B':
+                        if (isset($fieldobj->binary)) 
+                                return ($fieldobj->binary) ? 'B' : 'X';
+                       return 'B';
+               
+               case 'D':
+                       if (!empty($this->datetime)) return 'T';
+                       return 'D';
+                       
+               default: 
+                       if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
+                       return $tmap;
+               }
+       }
+       
+       function _close() {}
+       
+       /**
+        * set/returns the current recordset page when paginating
+        */
+       function AbsolutePage($page=-1)
+       {
+               if ($page != -1) $this->_currentPage = $page;
+               return $this->_currentPage;
+       }
+       
+       /**
+        * set/returns the status of the atFirstPage flag when paginating
+        */
+       function AtFirstPage($status=false)
+       {
+               if ($status != false) $this->_atFirstPage = $status;
+               return $this->_atFirstPage;
+       }
+       
+       function LastPageNo($page = false)
+       {
+               if ($page != false) $this->_lastPageNo = $page;
+               return $this->_lastPageNo;
+       }
+       
+       /**
+        * set/returns the status of the atLastPage flag when paginating
+        */
+       function AtLastPage($status=false)
+       {
+               if ($status != false) $this->_atLastPage = $status;
+               return $this->_atLastPage;
+       }
+       
+} // end class ADORecordSet
+       
+       //==============================================================================================        
+       // CLASS ADORecordSet_array
+       //==============================================================================================        
+       
+       /**
+        * This class encapsulates the concept of a recordset created in memory
+        * as an array. This is useful for the creation of cached recordsets.
+        * 
+        * Note that the constructor is different from the standard ADORecordSet
+        */
+       
+       class ADORecordSet_array extends ADORecordSet
+       {
+               var $databaseType = 'array';
+
+               var $_array;    // holds the 2-dimensional data array
+               var $_types;    // the array of types of each column (C B I L M)
+               var $_colnames; // names of each column in array
+               var $_skiprow1; // skip 1st row because it holds column names
+               var $_fieldarr; // holds array of field objects
+               var $canSeek = true;
+               var $affectedrows = false;
+               var $insertid = false;
+               var $sql = '';
+               var $compat = false;
+               /**
+                * Constructor
+                *
+                */
+               function ADORecordSet_array($fakeid=1)
+               {
+               global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
+               
+                       // fetch() on EOF does not delete $this->fields
+                       $this->compat = !empty($ADODB_COMPAT_FETCH);
+                       $this->ADORecordSet($fakeid); // fake queryID           
+                       $this->fetchMode = $ADODB_FETCH_MODE;
+               }
+               
+               
+               /**
+                * Setup the array.
+                *
+                * @param array         is a 2-dimensional array holding the data.
+                *                      The first row should hold the column names 
+                *                      unless paramter $colnames is used.
+                * @param typearr       holds an array of types. These are the same types 
+                *                      used in MetaTypes (C,B,L,I,N).
+                * @param [colnames]    array of column names. If set, then the first row of
+                *                      $array should not hold the column names.
+                */
+               function InitArray($array,$typearr,$colnames=false)
+               {
+                       $this->_array = $array;
+                       $this->_types = $typearr;       
+                       if ($colnames) {
+                               $this->_skiprow1 = false;
+                               $this->_colnames = $colnames;
+                       } else  {
+                               $this->_skiprow1 = true;
+                               $this->_colnames = $array[0];
+                       }
+                       $this->Init();
+               }
+               /**
+                * Setup the Array and datatype file objects
+                *
+                * @param array         is a 2-dimensional array holding the data.
+                *                      The first row should hold the column names 
+                *                      unless paramter $colnames is used.
+                * @param fieldarr      holds an array of ADOFieldObject's.
+                */
+               function InitArrayFields($array,$fieldarr)
+               {
+                       $this->_array = $array;
+                       $this->_skiprow1= false;
+                       if ($fieldarr) {
+                               $this->_fieldobjects = $fieldarr;
+                       } 
+                       $this->Init();
+               }
+               
+               function &GetArray($nRows=-1)
+               {
+                       if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
+                               return $this->_array;
+                       } else {
+                               $arr =& ADORecordSet::GetArray($nRows);
+                               return $arr;
+                       }
+               }
+               
+               function _initrs()
+               {
+                       $this->_numOfRows =  sizeof($this->_array);
+                       if ($this->_skiprow1) $this->_numOfRows -= 1;
+               
+                       $this->_numOfFields =(isset($this->_fieldobjects)) ?
+                                sizeof($this->_fieldobjects):sizeof($this->_types);
+               }
+               
+               /* Use associative array to get fields array */
+               function Fields($colname)
+               {
+                       if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+       
+                       if (!$this->bind) {
+                               $this->bind = array();
+                               for ($i=0; $i < $this->_numOfFields; $i++) {
+                                       $o = $this->FetchField($i);
+                                       $this->bind[strtoupper($o->name)] = $i;
+                               }
+                       }
+                       return $this->fields[$this->bind[strtoupper($colname)]];
+               }
+               
+               function &FetchField($fieldOffset = -1) 
+               {
+                       if (isset($this->_fieldobjects)) {
+                               return $this->_fieldobjects[$fieldOffset];
+                       }
+                       $o =  new ADOFieldObject();
+                       $o->name = $this->_colnames[$fieldOffset];
+                       $o->type =  $this->_types[$fieldOffset];
+                       $o->max_length = -1; // length not known
+                       
+                       return $o;
+               }
+                       
+               function _seek($row)
+               {
+                       if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
+                               $this->_currentRow = $row;
+                               if ($this->_skiprow1) $row += 1;
+                               $this->fields = $this->_array[$row];
+                               return true;
+                       }
+                       return false;
+               }
+               
+               function MoveNext() 
+               {
+                       if (!$this->EOF) {              
+                               $this->_currentRow++;
+                               
+                               $pos = $this->_currentRow;
+                               
+                               if ($this->_numOfRows <= $pos) {
+                                       if (!$this->compat) $this->fields = false;
+                               } else {
+                                       if ($this->_skiprow1) $pos += 1;
+                                       $this->fields = $this->_array[$pos];
+                                       return true;
+                               }               
+                               $this->EOF = true;
+                       }
+                       
+                       return false;
+               }       
+       
+               function _fetch()
+               {
+                       $pos = $this->_currentRow;
+                       
+                       if ($this->_numOfRows <= $pos) {
+                               if (!$this->compat) $this->fields = false;
+                               return false;
+                       }
+                       if ($this->_skiprow1) $pos += 1;
+                       $this->fields = $this->_array[$pos];
+                       return true;
+               }
+               
+               function _close() 
+               {
+                       return true;    
+               }
+       
+       } // ADORecordSet_array
+
+       //==============================================================================================        
+       // HELPER FUNCTIONS
+       //==============================================================================================                        
+       
+       /**
+        * Synonym for ADOLoadCode. Private function. Do not use.
+        *
+        * @deprecated
+        */
+       function ADOLoadDB($dbType) 
+       { 
+               return ADOLoadCode($dbType);
+       }
+               
+       /**
+        * Load the code for a specific database driver. Private function. Do not use.
+        */
+       function ADOLoadCode($dbType) 
+       {
+       global $ADODB_LASTDB;
+       
+               if (!$dbType) return false;
+               $db = strtolower($dbType);
+               switch ($db) {
+                       case 'maxsql': $db = 'mysqlt'; break;
+                       case 'postgres':
+                       case 'pgsql': $db = 'postgres7'; break;
+               }
+               @include_once(ADODB_DIR."/drivers/adodb-".$db.".inc.php");
+               $ADODB_LASTDB = $db;
+               
+               $ok = class_exists("ADODB_" . $db);
+               if ($ok) return $db;
+               
+               $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
+               if (file_exists($file)) ADOConnection::outp("Missing file: $file");
+               else ADOConnection::outp("Syntax error in file: $file");
+               return false;
+       }
+
+       /**
+        * synonym for ADONewConnection for people like me who cannot remember the correct name
+        */
+       function &NewADOConnection($db='')
+       {
+               $tmp =& ADONewConnection($db);
+               return $tmp;
+       }
+       
+       /**
+        * Instantiate a new Connection class for a specific database driver.
+        *
+        * @param [db]  is the database Connection object to create. If undefined,
+        *      use the last database driver that was loaded by ADOLoadCode().
+        *
+        * @return the freshly created instance of the Connection class.
+        */
+       function &ADONewConnection($db='')
+       {
+       GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
+               
+               if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
+               $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
+               
+               if (!empty($ADODB_NEWCONNECTION)) {
+                       $obj = $ADODB_NEWCONNECTION($db);
+                       if ($obj) {
+                               if ($errorfn)  $obj->raiseErrorFn = $errorfn;
+                               return $obj;
+                       }
+               }
+               
+               if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
+               if (empty($db)) $db = $ADODB_LASTDB;
+               
+               if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
+               
+               if (!$db) {
+                        if ($errorfn) {
+                               // raise an error
+                               $ignore = false;
+                               $errorfn('ADONewConnection', 'ADONewConnection', -998,
+                                                "could not load the database driver for '$db",
+                                                $db,false,$ignore);
+                       } else
+                                ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
+                               
+                       return false;
+               }
+               
+               $cls = 'ADODB_'.$db;
+               if (!class_exists($cls)) {
+                       adodb_backtrace();
+                       return false;
+               }
+               
+               $obj =& new $cls();
+               if ($errorfn) $obj->raiseErrorFn = $errorfn;
+               
+               return $obj;
+       }
+       
+       // $perf == true means called by NewPerfMonitor()
+       function _adodb_getdriver($provider,$drivername,$perf=false)
+       {
+               if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado') 
+                       $drivername = $provider;
+               else {
+                       if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5);
+                       else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4);
+                       else 
+                       switch($drivername) {
+                       case 'oracle': $drivername = 'oci8';break;
+                       //case 'sybase': $drivername = 'mssql';break;
+                       case 'access': 
+                                               if ($perf) $drivername = '';
+                                               break;
+                       case 'db2':     
+                                               break;
+                       default:
+                               $drivername = 'generic';
+                               break;
+                       }
+               }
+               
+               return $drivername;
+       }
+       
+       function &NewPerfMonitor(&$conn)
+       {
+               $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
+               if (!$drivername || $drivername == 'generic') return false;
+               include_once(ADODB_DIR.'/adodb-perf.inc.php');
+               @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
+               $class = "Perf_$drivername";
+               if (!class_exists($class)) return false;
+               $perf =& new $class($conn);
+               
+               return $perf;
+       }
+       
+       function &NewDataDictionary(&$conn)
+       {
+               $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
+               
+               include_once(ADODB_DIR.'/adodb-lib.inc.php');
+               include_once(ADODB_DIR.'/adodb-datadict.inc.php');
+               $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
+
+               if (!file_exists($path)) {
+                       ADOConnection::outp("Database driver '$path' not available");
+                       return false;
+               }
+               include_once($path);
+               $class = "ADODB2_$drivername";
+               $dict =& new $class();
+               $dict->dataProvider = $conn->dataProvider;
+               $dict->connection = &$conn;
+               $dict->upperName = strtoupper($drivername);
+               $dict->quote = $conn->nameQuote;
+               if (is_resource($conn->_connectionID))
+                       $dict->serverInfo = $conn->ServerInfo();
+               
+               return $dict;
+       }
+
+
+       /**
+       * Save a file $filename and its $contents (normally for caching) with file locking
+       */
+       function adodb_write_file($filename, $contents,$debug=false)
+       { 
+       # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows
+       # So to simulate locking, we assume that rename is an atomic operation.
+       # First we delete $filename, then we create a $tempfile write to it and 
+       # rename to the desired $filename. If the rename works, then we successfully 
+       # modified the file exclusively.
+       # What a stupid need - having to simulate locking.
+       # Risks:
+       # 1. $tempfile name is not unique -- very very low
+       # 2. unlink($filename) fails -- ok, rename will fail
+       # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs
+       # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and  cache updated
+               if (strncmp(PHP_OS,'WIN',3) === 0) {
+                       // skip the decimal place
+                       $mtime = substr(str_replace(' ','_',microtime()),2); 
+                       // getmypid() actually returns 0 on Win98 - never mind!
+                       $tmpname = $filename.uniqid($mtime).getmypid();
+                       if (!($fd = fopen($tmpname,'a'))) return false;
+                       $ok = ftruncate($fd,0);                 
+                       if (!fwrite($fd,$contents)) $ok = false;
+                       fclose($fd);
+                       chmod($tmpname,0644);
+                       // the tricky moment
+                       @unlink($filename);
+                       if (!@rename($tmpname,$filename)) {
+                               unlink($tmpname);
+                               $ok = false;
+                       }
+                       if (!$ok) {
+                               if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed'));
+                       }
+                       return $ok;
+               }
+               if (!($fd = fopen($filename, 'a'))) return false;
+               if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) {
+                       $ok = fwrite( $fd, $contents );
+                       fclose($fd);
+                       chmod($filename,0644);
+               }else {
+                       fclose($fd);
+                       if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");
+                       $ok = false;
+               }
+       
+               return $ok;
+       }
+       
+       /*
+               Perform a print_r, with pre tags for better formatting.
+       */
+       function adodb_pr($var)
+       {
+               if (isset($_SERVER['HTTP_USER_AGENT'])) { 
+                       echo " <pre>\n";print_r($var);echo "</pre>\n";
+               } else
+                       print_r($var);
+       }
+       
+       /*
+               Perform a stack-crawl and pretty print it.
+               
+               @param printOrArr  Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
+               @param levels Number of levels to display
+       */
+       function adodb_backtrace($printOrArr=true,$levels=9999)
+       {
+               $s = '';
+               if (PHPVERSION() < 4.3) return;
+                
+               $html =  (isset($_SERVER['HTTP_USER_AGENT']));
+               $fmt =  ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
+
+               $MAXSTRLEN = 64;
+       
+               $s = ($html) ? '<pre align=left>' : '';
+               
+               if (is_array($printOrArr)) $traceArr = $printOrArr;
+               else $traceArr = debug_backtrace();
+               array_shift($traceArr);
+               $tabs = sizeof($traceArr)-1;
+               
+               foreach ($traceArr as $arr) {
+                       $levels -= 1;
+                       if ($levels < 0) break;
+                       
+                       $args = array();
+                       for ($i=0; $i < $tabs; $i++) $s .=  ($html) ? ' &nbsp; ' : "\t";
+                       $tabs -= 1;
+                       if ($html) $s .= '<font face="Courier New,Courier">';
+                       if (isset($arr['class'])) $s .= $arr['class'].'.';
+                       if (isset($arr['args']))
+                        foreach($arr['args'] as $v) {
+                               if (is_null($v)) $args[] = 'null';
+                               else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
+                               else if (is_object($v)) $args[] = 'Object:'.get_class($v);
+                               else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
+                               else {
+                                       $v = (string) @$v;
+                                       $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
+                                       if (strlen($v) > $MAXSTRLEN) $str .= '...';
+                                       $args[] = $str;
+                               }
+                       }
+                       $s .= $arr['function'].'('.implode(', ',$args).')';
+                       
+                       
+                       $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
+                               
+                       $s .= "\n";
+               }       
+               if ($html) $s .= '</pre>';
+               if ($printOrArr) print $s;
+               
+               return $s;
+       }
+       
+} // defined
 ?>
\ No newline at end of file
index f1760c941ba9e8beef18897d5226b937dcf42895..c6a4bc53685d20492d2f210c037de07d10d65216 100644 (file)
@@ -1,92 +1,92 @@
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-*/\r
-\r
-class ADODB2_access extends ADODB_DataDict {\r
-       \r
-       var $databaseType = 'access';\r
-       var $seqField = false;\r
-       \r
-       \r
-       function ActualType($meta)\r
-       {\r
-               switch($meta) {\r
-               case 'C': return 'TEXT';\r
-               case 'XL':\r
-               case 'X': return 'MEMO'; \r
-               \r
-               case 'C2': return 'TEXT'; // up to 32K\r
-               case 'X2': return 'MEMO';\r
-               \r
-               case 'B': return 'BINARY';\r
-                       \r
-               case 'D': return 'DATETIME';\r
-               case 'T': return 'DATETIME';\r
-               \r
-               case 'L': return 'BYTE';\r
-               case 'I': return 'INTEGER';\r
-               case 'I1': return 'BYTE';\r
-               case 'I2': return 'SMALLINT';\r
-               case 'I4': return 'INTEGER';\r
-               case 'I8': return 'INTEGER';\r
-               \r
-               case 'F': return 'DOUBLE';\r
-               case 'N': return 'NUMERIC';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-       \r
-       // return string must begin with space\r
-       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)\r
-       {\r
-               if ($fautoinc) {\r
-                       $ftype = 'COUNTER';\r
-                       return '';\r
-               }\r
-               if (substr($ftype,0,7) == 'DECIMAL') $ftype = 'DECIMAL';\r
-               $suffix = '';\r
-               if (strlen($fdefault)) {\r
-                       //$suffix .= " DEFAULT $fdefault";\r
-                       if ($this->debug) ADOConnection::outp("Warning: Access does not supported DEFAULT values (field $fname)");\r
-               }\r
-               if ($fnotnull) $suffix .= ' NOT NULL';\r
-               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
-               return $suffix;\r
-       }\r
-       \r
-       function CreateDatabase($dbname,$options=false)\r
-       {\r
-               return array();\r
-       }\r
-       \r
-       \r
-       function SetSchema($schema)\r
-       {\r
-       }\r
-\r
-       function AlterColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");\r
-               return array();\r
-       }\r
-       \r
-       \r
-       function DropColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");\r
-               return array();\r
-       }\r
-       \r
-}\r
-\r
-\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+*/
+
+class ADODB2_access extends ADODB_DataDict {
+       
+       var $databaseType = 'access';
+       var $seqField = false;
+       
+       
+       function ActualType($meta)
+       {
+               switch($meta) {
+               case 'C': return 'TEXT';
+               case 'XL':
+               case 'X': return 'MEMO'; 
+               
+               case 'C2': return 'TEXT'; // up to 32K
+               case 'X2': return 'MEMO';
+               
+               case 'B': return 'BINARY';
+                       
+               case 'D': return 'DATETIME';
+               case 'T': return 'DATETIME';
+               
+               case 'L': return 'BYTE';
+               case 'I': return 'INTEGER';
+               case 'I1': return 'BYTE';
+               case 'I2': return 'SMALLINT';
+               case 'I4': return 'INTEGER';
+               case 'I8': return 'INTEGER';
+               
+               case 'F': return 'DOUBLE';
+               case 'N': return 'NUMERIC';
+               default:
+                       return $meta;
+               }
+       }
+       
+       // return string must begin with space
+       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
+       {
+               if ($fautoinc) {
+                       $ftype = 'COUNTER';
+                       return '';
+               }
+               if (substr($ftype,0,7) == 'DECIMAL') $ftype = 'DECIMAL';
+               $suffix = '';
+               if (strlen($fdefault)) {
+                       //$suffix .= " DEFAULT $fdefault";
+                       if ($this->debug) ADOConnection::outp("Warning: Access does not supported DEFAULT values (field $fname)");
+               }
+               if ($fnotnull) $suffix .= ' NOT NULL';
+               if ($fconstraint) $suffix .= ' '.$fconstraint;
+               return $suffix;
+       }
+       
+       function CreateDatabase($dbname,$options=false)
+       {
+               return array();
+       }
+       
+       
+       function SetSchema($schema)
+       {
+       }
+
+       function AlterColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
+               return array();
+       }
+       
+       
+       function DropColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
+               return array();
+       }
+       
+}
+
+
 ?>
\ No newline at end of file
index 48f2f331e94aba1b41fdbacf5ed2d1d091361517..cadf516107799561cbd110ab90060a75e262703b 100644 (file)
@@ -1,74 +1,74 @@
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-*/\r
-\r
-class ADODB2_db2 extends ADODB_DataDict {\r
-       \r
-       var $databaseType = 'db2';\r
-       var $seqField = false;\r
-       \r
-       function ActualType($meta)\r
-       {\r
-               switch($meta) {\r
-               case 'C': return 'VARCHAR';\r
-               case 'XL':\r
-               case 'X': return 'VARCHAR(3600)'; \r
-               \r
-               case 'C2': return 'VARCHAR'; // up to 32K\r
-               case 'X2': return 'VARCHAR(3600)'; // up to 32000, but default page size too small\r
-               \r
-               case 'B': return 'BLOB';\r
-                       \r
-               case 'D': return 'DATE';\r
-               case 'T': return 'TIMESTAMP';\r
-               \r
-               case 'L': return 'SMALLINT';\r
-               case 'I': return 'INTEGER';\r
-               case 'I1': return 'SMALLINT';\r
-               case 'I2': return 'SMALLINT';\r
-               case 'I4': return 'INTEGER';\r
-               case 'I8': return 'BIGINT';\r
-               \r
-               case 'F': return 'DOUBLE';\r
-               case 'N': return 'DECIMAL';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-       \r
-       // return string must begin with space\r
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)\r
-       {       \r
-               $suffix = '';\r
-               if ($fautoinc) return ' GENERATED ALWAYS AS IDENTITY'; # as identity start with \r
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
-               if ($fnotnull) $suffix .= ' NOT NULL';\r
-               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
-               return $suffix;\r
-       }\r
-\r
-       function AlterColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");\r
-               return array();\r
-       }\r
-       \r
-       \r
-       function DropColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");\r
-               return array();\r
-       }\r
-       \r
-}\r
-\r
-\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+*/
+
+class ADODB2_db2 extends ADODB_DataDict {
+       
+       var $databaseType = 'db2';
+       var $seqField = false;
+       
+       function ActualType($meta)
+       {
+               switch($meta) {
+               case 'C': return 'VARCHAR';
+               case 'XL':
+               case 'X': return 'VARCHAR(3600)'; 
+               
+               case 'C2': return 'VARCHAR'; // up to 32K
+               case 'X2': return 'VARCHAR(3600)'; // up to 32000, but default page size too small
+               
+               case 'B': return 'BLOB';
+                       
+               case 'D': return 'DATE';
+               case 'T': return 'TIMESTAMP';
+               
+               case 'L': return 'SMALLINT';
+               case 'I': return 'INTEGER';
+               case 'I1': return 'SMALLINT';
+               case 'I2': return 'SMALLINT';
+               case 'I4': return 'INTEGER';
+               case 'I8': return 'BIGINT';
+               
+               case 'F': return 'DOUBLE';
+               case 'N': return 'DECIMAL';
+               default:
+                       return $meta;
+               }
+       }
+       
+       // return string must begin with space
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
+       {       
+               $suffix = '';
+               if ($fautoinc) return ' GENERATED ALWAYS AS IDENTITY'; # as identity start with 
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+               if ($fnotnull) $suffix .= ' NOT NULL';
+               if ($fconstraint) $suffix .= ' '.$fconstraint;
+               return $suffix;
+       }
+
+       function AlterColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
+               return array();
+       }
+       
+       
+       function DropColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
+               return array();
+       }
+       
+}
+
+
 ?>
\ No newline at end of file
index 23267cceafa0b160d5630cc9c9644de0af3885ba..cb4fc462d11520f753279ca5a58f3386d1d8d5da 100644 (file)
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-*/\r
-\r
-class ADODB2_generic extends ADODB_DataDict {\r
-       \r
-       var $databaseType = 'generic';\r
-       var $seqField = false;\r
-       \r
-       \r
-       function ActualType($meta)\r
-       {\r
-               switch($meta) {\r
-               case 'C': return 'VARCHAR';\r
-               case 'XL':\r
-               case 'X': return 'VARCHAR(250)';\r
-               \r
-               case 'C2': return 'VARCHAR';\r
-               case 'X2': return 'VARCHAR(250)';\r
-               \r
-               case 'B': return 'VARCHAR';\r
-                       \r
-               case 'D': return 'DATE';\r
-               case 'T': return 'DATE';\r
-               \r
-               case 'L': return 'DECIMAL(1)';\r
-               case 'I': return 'DECIMAL(10)';\r
-               case 'I1': return 'DECIMAL(3)';\r
-               case 'I2': return 'DECIMAL(5)';\r
-               case 'I4': return 'DECIMAL(10)';\r
-               case 'I8': return 'DECIMAL(20)';\r
-               \r
-               case 'F': return 'DECIMAL(32,8)';\r
-               case 'N': return 'DECIMAL';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-\r
-       function AlterColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");\r
-               return array();\r
-       }\r
-       \r
-       \r
-       function DropColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");\r
-               return array();\r
-       }\r
-       \r
-}\r
-\r
-/*\r
-//db2\r
-       function ActualType($meta)\r
-       {\r
-               switch($meta) {\r
-               case 'C': return 'VARCHAR';\r
-               case 'X': return 'VARCHAR'; \r
-               \r
-               case 'C2': return 'VARCHAR'; // up to 32K\r
-               case 'X2': return 'VARCHAR';\r
-               \r
-               case 'B': return 'BLOB';\r
-                       \r
-               case 'D': return 'DATE';\r
-               case 'T': return 'TIMESTAMP';\r
-               \r
-               case 'L': return 'SMALLINT';\r
-               case 'I': return 'INTEGER';\r
-               case 'I1': return 'SMALLINT';\r
-               case 'I2': return 'SMALLINT';\r
-               case 'I4': return 'INTEGER';\r
-               case 'I8': return 'BIGINT';\r
-               \r
-               case 'F': return 'DOUBLE';\r
-               case 'N': return 'DECIMAL';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-       \r
-// ifx\r
-function ActualType($meta)\r
-       {\r
-               switch($meta) {\r
-               case 'C': return 'VARCHAR';// 255\r
-               case 'X': return 'TEXT'; \r
-               \r
-               case 'C2': return 'NVARCHAR';\r
-               case 'X2': return 'TEXT';\r
-               \r
-               case 'B': return 'BLOB';\r
-                       \r
-               case 'D': return 'DATE';\r
-               case 'T': return 'DATETIME';\r
-               \r
-               case 'L': return 'SMALLINT';\r
-               case 'I': return 'INTEGER';\r
-               case 'I1': return 'SMALLINT';\r
-               case 'I2': return 'SMALLINT';\r
-               case 'I4': return 'INTEGER';\r
-               case 'I8': return 'DECIMAL(20)';\r
-               \r
-               case 'F': return 'FLOAT';\r
-               case 'N': return 'DECIMAL';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-*/\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+*/
+
+class ADODB2_generic extends ADODB_DataDict {
+       
+       var $databaseType = 'generic';
+       var $seqField = false;
+       
+       
+       function ActualType($meta)
+       {
+               switch($meta) {
+               case 'C': return 'VARCHAR';
+               case 'XL':
+               case 'X': return 'VARCHAR(250)';
+               
+               case 'C2': return 'VARCHAR';
+               case 'X2': return 'VARCHAR(250)';
+               
+               case 'B': return 'VARCHAR';
+                       
+               case 'D': return 'DATE';
+               case 'T': return 'DATE';
+               
+               case 'L': return 'DECIMAL(1)';
+               case 'I': return 'DECIMAL(10)';
+               case 'I1': return 'DECIMAL(3)';
+               case 'I2': return 'DECIMAL(5)';
+               case 'I4': return 'DECIMAL(10)';
+               case 'I8': return 'DECIMAL(20)';
+               
+               case 'F': return 'DECIMAL(32,8)';
+               case 'N': return 'DECIMAL';
+               default:
+                       return $meta;
+               }
+       }
+
+       function AlterColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
+               return array();
+       }
+       
+       
+       function DropColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
+               return array();
+       }
+       
+}
+
+/*
+//db2
+       function ActualType($meta)
+       {
+               switch($meta) {
+               case 'C': return 'VARCHAR';
+               case 'X': return 'VARCHAR'; 
+               
+               case 'C2': return 'VARCHAR'; // up to 32K
+               case 'X2': return 'VARCHAR';
+               
+               case 'B': return 'BLOB';
+                       
+               case 'D': return 'DATE';
+               case 'T': return 'TIMESTAMP';
+               
+               case 'L': return 'SMALLINT';
+               case 'I': return 'INTEGER';
+               case 'I1': return 'SMALLINT';
+               case 'I2': return 'SMALLINT';
+               case 'I4': return 'INTEGER';
+               case 'I8': return 'BIGINT';
+               
+               case 'F': return 'DOUBLE';
+               case 'N': return 'DECIMAL';
+               default:
+                       return $meta;
+               }
+       }
+       
+// ifx
+function ActualType($meta)
+       {
+               switch($meta) {
+               case 'C': return 'VARCHAR';// 255
+               case 'X': return 'TEXT'; 
+               
+               case 'C2': return 'NVARCHAR';
+               case 'X2': return 'TEXT';
+               
+               case 'B': return 'BLOB';
+                       
+               case 'D': return 'DATE';
+               case 'T': return 'DATETIME';
+               
+               case 'L': return 'SMALLINT';
+               case 'I': return 'INTEGER';
+               case 'I1': return 'SMALLINT';
+               case 'I2': return 'SMALLINT';
+               case 'I4': return 'INTEGER';
+               case 'I8': return 'DECIMAL(20)';
+               
+               case 'F': return 'FLOAT';
+               case 'N': return 'DECIMAL';
+               default:
+                       return $meta;
+               }
+       }
+*/
 ?>
\ No newline at end of file
index 6feb613eef07b9e1e6cdd752d406385ff065f9e0..0583b962a2a3fe4e7dc87341ca563d1cb4c47470 100644 (file)
@@ -1,64 +1,64 @@
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-*/\r
-\r
-class ADODB2_ibase extends ADODB_DataDict {\r
-       \r
-       var $databaseType = 'ibase';\r
-       var $seqField = false;\r
-       \r
-       \r
-       function ActualType($meta)\r
-       {\r
-               switch($meta) {\r
-               case 'C': return 'VARCHAR';\r
-               case 'XL':\r
-               case 'X': return 'VARCHAR(4000)'; \r
-               \r
-               case 'C2': return 'VARCHAR'; // up to 32K\r
-               case 'X2': return 'VARCHAR(4000)';\r
-               \r
-               case 'B': return 'BLOB';\r
-                       \r
-               case 'D': return 'DATE';\r
-               case 'T': return 'TIMESTAMP';\r
-               \r
-               case 'L': return 'SMALLINT';\r
-               case 'I': return 'INTEGER';\r
-               case 'I1': return 'SMALLINT';\r
-               case 'I2': return 'SMALLINT';\r
-               case 'I4': return 'INTEGER';\r
-               case 'I8': return 'INTEGER';\r
-               \r
-               case 'F': return 'DOUBLE PRECISION';\r
-               case 'N': return 'DECIMAL';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-\r
-       function AlterColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");\r
-               return array();\r
-       }\r
-       \r
-       \r
-       function DropColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");\r
-               return array();\r
-       }\r
-       \r
-}\r
-\r
-\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+*/
+
+class ADODB2_ibase extends ADODB_DataDict {
+       
+       var $databaseType = 'ibase';
+       var $seqField = false;
+       
+       
+       function ActualType($meta)
+       {
+               switch($meta) {
+               case 'C': return 'VARCHAR';
+               case 'XL':
+               case 'X': return 'VARCHAR(4000)'; 
+               
+               case 'C2': return 'VARCHAR'; // up to 32K
+               case 'X2': return 'VARCHAR(4000)';
+               
+               case 'B': return 'BLOB';
+                       
+               case 'D': return 'DATE';
+               case 'T': return 'TIMESTAMP';
+               
+               case 'L': return 'SMALLINT';
+               case 'I': return 'INTEGER';
+               case 'I1': return 'SMALLINT';
+               case 'I2': return 'SMALLINT';
+               case 'I4': return 'INTEGER';
+               case 'I8': return 'INTEGER';
+               
+               case 'F': return 'DOUBLE PRECISION';
+               case 'N': return 'DECIMAL';
+               default:
+                       return $meta;
+               }
+       }
+
+       function AlterColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
+               return array();
+       }
+       
+       
+       function DropColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
+               return array();
+       }
+       
+}
+
+
 ?>
\ No newline at end of file
index 2fcaf922f2dfd632455c402d27bc3c26703b033d..0064c9a43adb16ea1615f97447170bfaf7cd9348 100644 (file)
@@ -1,77 +1,77 @@
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-*/\r
-\r
-class ADODB2_informix extends ADODB_DataDict {\r
-       \r
-       var $databaseType = 'informix';\r
-       var $seqField = false;\r
-       \r
-       \r
-       function ActualType($meta)\r
-       {\r
-               switch($meta) {\r
-               case 'C': return 'VARCHAR';// 255\r
-               case 'XL':\r
-               case 'X': return 'TEXT'; \r
-               \r
-               case 'C2': return 'NVARCHAR';\r
-               case 'X2': return 'TEXT';\r
-               \r
-               case 'B': return 'BLOB';\r
-                       \r
-               case 'D': return 'DATE';\r
-               case 'T': return 'DATETIME';\r
-               \r
-               case 'L': return 'SMALLINT';\r
-               case 'I': return 'INTEGER';\r
-               case 'I1': return 'SMALLINT';\r
-               case 'I2': return 'SMALLINT';\r
-               case 'I4': return 'INTEGER';\r
-               case 'I8': return 'DECIMAL(20)';\r
-               \r
-               case 'F': return 'FLOAT';\r
-               case 'N': return 'DECIMAL';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-\r
-       function AlterColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");\r
-               return array();\r
-       }\r
-       \r
-       \r
-       function DropColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");\r
-               return array();\r
-       }\r
-       \r
-       // return string must begin with space\r
-       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)\r
-       {\r
-               if ($fautoinc) {\r
-                       $ftype = 'SERIAL';\r
-                       return '';\r
-               }\r
-               $suffix = '';\r
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
-               if ($fnotnull) $suffix .= ' NOT NULL';\r
-               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
-               return $suffix;\r
-       }\r
-       \r
-}\r
-\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+*/
+
+class ADODB2_informix extends ADODB_DataDict {
+       
+       var $databaseType = 'informix';
+       var $seqField = false;
+       
+       
+       function ActualType($meta)
+       {
+               switch($meta) {
+               case 'C': return 'VARCHAR';// 255
+               case 'XL':
+               case 'X': return 'TEXT'; 
+               
+               case 'C2': return 'NVARCHAR';
+               case 'X2': return 'TEXT';
+               
+               case 'B': return 'BLOB';
+                       
+               case 'D': return 'DATE';
+               case 'T': return 'DATETIME';
+               
+               case 'L': return 'SMALLINT';
+               case 'I': return 'INTEGER';
+               case 'I1': return 'SMALLINT';
+               case 'I2': return 'SMALLINT';
+               case 'I4': return 'INTEGER';
+               case 'I8': return 'DECIMAL(20)';
+               
+               case 'F': return 'FLOAT';
+               case 'N': return 'DECIMAL';
+               default:
+                       return $meta;
+               }
+       }
+
+       function AlterColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
+               return array();
+       }
+       
+       
+       function DropColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
+               return array();
+       }
+       
+       // return string must begin with space
+       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
+       {
+               if ($fautoinc) {
+                       $ftype = 'SERIAL';
+                       return '';
+               }
+               $suffix = '';
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+               if ($fnotnull) $suffix .= ' NOT NULL';
+               if ($fconstraint) $suffix .= ' '.$fconstraint;
+               return $suffix;
+       }
+       
+}
+
 ?>
\ No newline at end of file
index bddb6c8421de8a1aa046aeab7b795664d7104e6d..a3fdc9e3ecc52af318c25c330dd8f129d767bd1f 100644 (file)
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-*/\r
-\r
-class ADODB2_mssql extends ADODB_DataDict {\r
-       var $databaseType = 'mssql';\r
-       \r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               \r
-               $len = -1; // mysql max_length is not accurate\r
-               switch (strtoupper($t)) {\r
-\r
-               case 'INT': \r
-               case 'INTEGER': return  'I';\r
-               case 'BIT':\r
-               case 'TINYINT': return  'I1';\r
-               case 'SMALLINT': return 'I2';\r
-               case 'BIGINT':  return  'I8';\r
-               \r
-               case 'REAL':\r
-               case 'FLOAT': return 'F';\r
-               default: return parent::MetaType($t,$len,$fieldobj);\r
-               }\r
-       }\r
-       \r
-       function ActualType($meta)\r
-       {\r
-               switch(strtoupper($meta)) {\r
-               case 'C': return 'VARCHAR';\r
-               case 'XL':\r
-               case 'X': return 'TEXT';\r
-               \r
-               case 'C2': return 'NVARCHAR';\r
-               case 'X2': return 'NTEXT';\r
-               \r
-               case 'B': return 'IMAGE';\r
-                       \r
-               case 'D': return 'DATETIME';\r
-               case 'T': return 'DATETIME';\r
-               case 'L': return 'BIT';\r
-               \r
-               case 'I': return 'INT'; \r
-               case 'I1': return 'TINYINT';\r
-               case 'I2': return 'SMALLINT';\r
-               case 'I4': return 'INT';\r
-               case 'I8': return 'BIGINT';\r
-               \r
-               case 'F': return 'REAL';\r
-               case 'N': return 'NUMERIC';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-       \r
-       \r
-       function AddColumnSQL($tabname, $flds)\r
-       {\r
-               $tabname = $this->TableName ($tabname);\r
-               $f = array();\r
-               list($lines,$pkey) = $this->_GenFields($flds);\r
-               $s = "ALTER TABLE $tabname $this->addCol";\r
-               foreach($lines as $v) {\r
-                       $f[] = "\n $v";\r
-               }\r
-               $s .= implode(',',$f);\r
-               $sql[] = $s;\r
-               return $sql;\r
-       }\r
-       \r
-       /*\r
-       function AlterColumnSQL($tabname, $flds)\r
-       {\r
-               $tabname = $this->TableName ($tabname);\r
-               $sql = array();\r
-               list($lines,$pkey) = $this->_GenFields($flds);\r
-               foreach($lines as $v) {\r
-                       $sql[] = "ALTER TABLE $tabname $this->alterCol $v";\r
-               }\r
-\r
-               return $sql;\r
-       }\r
-       */\r
-       \r
-       function DropColumnSQL($tabname, $flds)\r
-       {\r
-               $tabname = $this->TableName ($tabname);\r
-               if (!is_array($flds))\r
-                       $flds = explode(',',$flds);\r
-               $f = array();\r
-               $s = 'ALTER TABLE ' . $tabname;\r
-               foreach($flds as $v) {\r
-                       $f[] = "\n$this->dropCol $v";\r
-               }\r
-               $s .= implode(',',$f);\r
-               $sql[] = $s;\r
-               return $sql;\r
-       }\r
-       \r
-       // return string must begin with space\r
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)\r
-       {       \r
-               $suffix = '';\r
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
-               if ($fautoinc) $suffix .= ' IDENTITY(1,1)';\r
-               if ($fnotnull) $suffix .= ' NOT NULL';\r
-               else if ($suffix == '') $suffix .= ' NULL';\r
-               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
-               return $suffix;\r
-       }\r
-       \r
-       /*\r
-CREATE TABLE \r
-    [ database_name.[ owner ] . | owner. ] table_name \r
-    ( { < column_definition > \r
-        | column_name AS computed_column_expression \r
-        | < table_constraint > ::= [ CONSTRAINT constraint_name ] }\r
-\r
-            | [ { PRIMARY KEY | UNIQUE } [ ,...n ] \r
-    ) \r
-\r
-[ ON { filegroup | DEFAULT } ] \r
-[ TEXTIMAGE_ON { filegroup | DEFAULT } ] \r
-\r
-< column_definition > ::= { column_name data_type } \r
-    [ COLLATE < collation_name > ] \r
-    [ [ DEFAULT constant_expression ] \r
-        | [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]\r
-    ] \r
-    [ ROWGUIDCOL] \r
-    [ < column_constraint > ] [ ...n ] \r
-\r
-< column_constraint > ::= [ CONSTRAINT constraint_name ] \r
-    { [ NULL | NOT NULL ] \r
-        | [ { PRIMARY KEY | UNIQUE } \r
-            [ CLUSTERED | NONCLUSTERED ] \r
-            [ WITH FILLFACTOR = fillfactor ] \r
-            [ON {filegroup | DEFAULT} ] ] \r
-        ] \r
-        | [ [ FOREIGN KEY ] \r
-            REFERENCES ref_table [ ( ref_column ) ] \r
-            [ ON DELETE { CASCADE | NO ACTION } ] \r
-            [ ON UPDATE { CASCADE | NO ACTION } ] \r
-            [ NOT FOR REPLICATION ] \r
-        ] \r
-        | CHECK [ NOT FOR REPLICATION ] \r
-        ( logical_expression ) \r
-    } \r
-\r
-< table_constraint > ::= [ CONSTRAINT constraint_name ] \r
-    { [ { PRIMARY KEY | UNIQUE } \r
-        [ CLUSTERED | NONCLUSTERED ] \r
-        { ( column [ ASC | DESC ] [ ,...n ] ) } \r
-        [ WITH FILLFACTOR = fillfactor ] \r
-        [ ON { filegroup | DEFAULT } ] \r
-    ] \r
-    | FOREIGN KEY \r
-        [ ( column [ ,...n ] ) ] \r
-        REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] \r
-        [ ON DELETE { CASCADE | NO ACTION } ] \r
-        [ ON UPDATE { CASCADE | NO ACTION } ] \r
-        [ NOT FOR REPLICATION ] \r
-    | CHECK [ NOT FOR REPLICATION ] \r
-        ( search_conditions ) \r
-    } \r
-\r
-\r
-       */\r
-       \r
-       /*\r
-       CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name \r
-    ON { table | view } ( column [ ASC | DESC ] [ ,...n ] ) \r
-               [ WITH < index_option > [ ,...n] ] \r
-               [ ON filegroup ]\r
-               < index_option > :: = \r
-                   { PAD_INDEX | \r
-                       FILLFACTOR = fillfactor | \r
-                       IGNORE_DUP_KEY | \r
-                       DROP_EXISTING | \r
-                   STATISTICS_NORECOMPUTE | \r
-                   SORT_IN_TEMPDB  \r
-               }\r
-*/\r
-       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)\r
-       {\r
-               $sql = array();\r
-               \r
-               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
-                       $sql[] = sprintf ($this->dropIndex, $tabname . '.' . $idxname);\r
-                       if ( isset($idxoptions['DROP']) )\r
-                               return $sql;\r
-               }\r
-               \r
-               if ( empty ($flds) ) {\r
-                       return $sql;\r
-               }\r
-               \r
-               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';\r
-               $clustered = isset($idxoptions['CLUSTERED']) ? ' CLUSTERED' : '';\r
-               \r
-               if ( is_array($flds) )\r
-                       $flds = implode(', ',$flds);\r
-               $s = 'CREATE' . $unique . $clustered . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';\r
-               \r
-               if ( isset($idxoptions[$this->upperName]) )\r
-                       $s .= $idxoptions[$this->upperName];\r
-               \r
-\r
-               $sql[] = $s;\r
-               \r
-               return $sql;\r
-       }\r
-}\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+*/
+
+class ADODB2_mssql extends ADODB_DataDict {
+       var $databaseType = 'mssql';
+       
+       var $dropIndex = 'DROP INDEX %2$s.%1$s';
+       
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               
+               $len = -1; // mysql max_length is not accurate
+               switch (strtoupper($t)) {
+
+               case 'INT': 
+               case 'INTEGER': return  'I';
+               case 'BIT':
+               case 'TINYINT': return  'I1';
+               case 'SMALLINT': return 'I2';
+               case 'BIGINT':  return  'I8';
+               
+               case 'REAL':
+               case 'FLOAT': return 'F';
+               default: return parent::MetaType($t,$len,$fieldobj);
+               }
+       }
+       
+       function ActualType($meta)
+       {
+               switch(strtoupper($meta)) {
+               case 'C': return 'VARCHAR';
+               case 'XL':
+               case 'X': return 'TEXT';
+               
+               case 'C2': return 'NVARCHAR';
+               case 'X2': return 'NTEXT';
+               
+               case 'B': return 'IMAGE';
+                       
+               case 'D': return 'DATETIME';
+               case 'T': return 'DATETIME';
+               case 'L': return 'BIT';
+               
+               case 'I': return 'INT'; 
+               case 'I1': return 'TINYINT';
+               case 'I2': return 'SMALLINT';
+               case 'I4': return 'INT';
+               case 'I8': return 'BIGINT';
+               
+               case 'F': return 'REAL';
+               case 'N': return 'NUMERIC';
+               default:
+                       return $meta;
+               }
+       }
+       
+       
+       function AddColumnSQL($tabname, $flds)
+       {
+               $tabname = $this->TableName ($tabname);
+               $f = array();
+               list($lines,$pkey) = $this->_GenFields($flds);
+               $s = "ALTER TABLE $tabname $this->addCol";
+               foreach($lines as $v) {
+                       $f[] = "\n $v";
+               }
+               $s .= implode(',',$f);
+               $sql[] = $s;
+               return $sql;
+       }
+       
+       /*
+       function AlterColumnSQL($tabname, $flds)
+       {
+               $tabname = $this->TableName ($tabname);
+               $sql = array();
+               list($lines,$pkey) = $this->_GenFields($flds);
+               foreach($lines as $v) {
+                       $sql[] = "ALTER TABLE $tabname $this->alterCol $v";
+               }
+
+               return $sql;
+       }
+       */
+       
+       function DropColumnSQL($tabname, $flds)
+       {
+               $tabname = $this->TableName ($tabname);
+               if (!is_array($flds))
+                       $flds = explode(',',$flds);
+               $f = array();
+               $s = 'ALTER TABLE ' . $tabname;
+               foreach($flds as $v) {
+                       $f[] = "\n$this->dropCol $v";
+               }
+               $s .= implode(',',$f);
+               $sql[] = $s;
+               return $sql;
+       }
+       
+       // return string must begin with space
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
+       {       
+               $suffix = '';
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+               if ($fautoinc) $suffix .= ' IDENTITY(1,1)';
+               if ($fnotnull) $suffix .= ' NOT NULL';
+               else if ($suffix == '') $suffix .= ' NULL';
+               if ($fconstraint) $suffix .= ' '.$fconstraint;
+               return $suffix;
+       }
+       
+       /*
+CREATE TABLE 
+    [ database_name.[ owner ] . | owner. ] table_name 
+    ( { < column_definition > 
+        | column_name AS computed_column_expression 
+        | < table_constraint > ::= [ CONSTRAINT constraint_name ] }
+
+            | [ { PRIMARY KEY | UNIQUE } [ ,...n ] 
+    ) 
+
+[ ON { filegroup | DEFAULT } ] 
+[ TEXTIMAGE_ON { filegroup | DEFAULT } ] 
+
+< column_definition > ::= { column_name data_type } 
+    [ COLLATE < collation_name > ] 
+    [ [ DEFAULT constant_expression ] 
+        | [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]
+    ] 
+    [ ROWGUIDCOL] 
+    [ < column_constraint > ] [ ...n ] 
+
+< column_constraint > ::= [ CONSTRAINT constraint_name ] 
+    { [ NULL | NOT NULL ] 
+        | [ { PRIMARY KEY | UNIQUE } 
+            [ CLUSTERED | NONCLUSTERED ] 
+            [ WITH FILLFACTOR = fillfactor ] 
+            [ON {filegroup | DEFAULT} ] ] 
+        ] 
+        | [ [ FOREIGN KEY ] 
+            REFERENCES ref_table [ ( ref_column ) ] 
+            [ ON DELETE { CASCADE | NO ACTION } ] 
+            [ ON UPDATE { CASCADE | NO ACTION } ] 
+            [ NOT FOR REPLICATION ] 
+        ] 
+        | CHECK [ NOT FOR REPLICATION ] 
+        ( logical_expression ) 
+    } 
+
+< table_constraint > ::= [ CONSTRAINT constraint_name ] 
+    { [ { PRIMARY KEY | UNIQUE } 
+        [ CLUSTERED | NONCLUSTERED ] 
+        { ( column [ ASC | DESC ] [ ,...n ] ) } 
+        [ WITH FILLFACTOR = fillfactor ] 
+        [ ON { filegroup | DEFAULT } ] 
+    ] 
+    | FOREIGN KEY 
+        [ ( column [ ,...n ] ) ] 
+        REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] 
+        [ ON DELETE { CASCADE | NO ACTION } ] 
+        [ ON UPDATE { CASCADE | NO ACTION } ] 
+        [ NOT FOR REPLICATION ] 
+    | CHECK [ NOT FOR REPLICATION ] 
+        ( search_conditions ) 
+    } 
+
+
+       */
+       
+       /*
+       CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name 
+    ON { table | view } ( column [ ASC | DESC ] [ ,...n ] ) 
+               [ WITH < index_option > [ ,...n] ] 
+               [ ON filegroup ]
+               < index_option > :: = 
+                   { PAD_INDEX | 
+                       FILLFACTOR = fillfactor | 
+                       IGNORE_DUP_KEY | 
+                       DROP_EXISTING | 
+                   STATISTICS_NORECOMPUTE | 
+                   SORT_IN_TEMPDB  
+               }
+*/
+       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+       {
+               $sql = array();
+               
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+                       $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
+                       if ( isset($idxoptions['DROP']) )
+                               return $sql;
+               }
+               
+               if ( empty ($flds) ) {
+                       return $sql;
+               }
+               
+               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
+               $clustered = isset($idxoptions['CLUSTERED']) ? ' CLUSTERED' : '';
+               
+               if ( is_array($flds) )
+                       $flds = implode(', ',$flds);
+               $s = 'CREATE' . $unique . $clustered . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';
+               
+               if ( isset($idxoptions[$this->upperName]) )
+                       $s .= $idxoptions[$this->upperName];
+               
+
+               $sql[] = $s;
+               
+               return $sql;
+       }
+}
 ?>
\ No newline at end of file
index 2eed142e664bda19c5281d331b10796c903a83cf..8990fcf883b5ad1ed26b5555f44071fd9788ddeb 100644 (file)
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-*/\r
-\r
-class ADODB2_mysql extends ADODB_DataDict {\r
-       var $databaseType = 'mysql';\r
-       var $alterCol = ' MODIFY COLUMN';\r
-       \r
-       var $dropIndex = 'DROP INDEX %s ON %s';\r
-       \r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               \r
-               $len = -1; // mysql max_length is not accurate\r
-               switch (strtoupper($t)) {\r
-               case 'STRING': \r
-               case 'CHAR':\r
-               case 'VARCHAR': \r
-               case 'TINYBLOB': \r
-               case 'TINYTEXT': \r
-               case 'ENUM': \r
-               case 'SET':\r
-                       if ($len <= $this->blobSize) return 'C';\r
-                       \r
-               case 'TEXT':\r
-               case 'LONGTEXT': \r
-               case 'MEDIUMTEXT':\r
-                       return 'X';\r
-                       \r
-               // php_mysql extension always returns 'blob' even if 'text'\r
-               // so we have to check whether binary...\r
-               case 'IMAGE':\r
-               case 'LONGBLOB': \r
-               case 'BLOB':\r
-               case 'MEDIUMBLOB':\r
-                       return !empty($fieldobj->binary) ? 'B' : 'X';\r
-                       \r
-               case 'YEAR':\r
-               case 'DATE': return 'D';\r
-               \r
-               case 'TIME':\r
-               case 'DATETIME':\r
-               case 'TIMESTAMP': return 'T';\r
-               \r
-               case 'FLOAT':\r
-               case 'DOUBLE':\r
-                       return 'F';\r
-                       \r
-               case 'INT': \r
-               case 'INTEGER': return (!empty($fieldobj->primary_key)) ? 'R' : 'I';\r
-               case 'TINYINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I1';\r
-               case 'SMALLINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I2';\r
-               case 'MEDIUMINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I4';\r
-               case 'BIGINT':  return (!empty($fieldobj->primary_key)) ? 'R' : 'I8';\r
-               default: return 'N';\r
-               }\r
-       }\r
-\r
-       function ActualType($meta)\r
-       {\r
-               switch(strtoupper($meta)) {\r
-               case 'C': return 'VARCHAR';\r
-               case 'XL':\r
-               case 'X': return 'LONGTEXT';\r
-               \r
-               case 'C2': return 'VARCHAR';\r
-               case 'X2': return 'LONGTEXT';\r
-               \r
-               case 'B': return 'LONGBLOB';\r
-                       \r
-               case 'D': return 'DATE';\r
-               case 'T': return 'DATETIME';\r
-               case 'L': return 'TINYINT';\r
-               \r
-               case 'R':\r
-               case 'I': return 'INTEGER';\r
-               case 'I1': return 'TINYINT';\r
-               case 'I2': return 'SMALLINT';\r
-               case 'I4': return 'MEDIUMINT';\r
-               case 'I8': return 'BIGINT';\r
-               \r
-               case 'F': return 'DOUBLE';\r
-               case 'N': return 'NUMERIC';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-       \r
-       // return string must begin with space\r
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)\r
-       {       \r
-               $suffix = '';\r
-               if ($funsigned) $suffix .= ' UNSIGNED';\r
-               if ($fnotnull) $suffix .= ' NOT NULL';\r
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
-               if ($fautoinc) $suffix .= ' AUTO_INCREMENT';\r
-               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
-               return $suffix;\r
-       }\r
-       \r
-       /*\r
-       CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]\r
-               [table_options] [select_statement]\r
-               create_definition:\r
-               col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]\r
-               [PRIMARY KEY] [reference_definition]\r
-               or PRIMARY KEY (index_col_name,...)\r
-               or KEY [index_name] (index_col_name,...)\r
-               or INDEX [index_name] (index_col_name,...)\r
-               or UNIQUE [INDEX] [index_name] (index_col_name,...)\r
-               or FULLTEXT [INDEX] [index_name] (index_col_name,...)\r
-               or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)\r
-               [reference_definition]\r
-               or CHECK (expr)\r
-       */\r
-       \r
-       /*\r
-       CREATE [UNIQUE|FULLTEXT] INDEX index_name\r
-               ON tbl_name (col_name[(length)],... )\r
-       */\r
-       \r
-       function DropIndexSQL ($idxname, $tabname)\r
-       {\r
-               return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));\r
-       }\r
-       \r
-       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)\r
-       {\r
-               $sql = array();\r
-               \r
-               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
-                       $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);\r
-                       if ( isset($idxoptions['DROP']) )\r
-                               return $sql;\r
-               }\r
-               \r
-               if ( empty ($flds) ) {\r
-                       return $sql;\r
-               }\r
-               \r
-               if (isset($idxoptions['FULLTEXT'])) {\r
-                       $unique = ' FULLTEXT';\r
-               } elseif (isset($idxoptions['UNIQUE'])) {\r
-                       $unique = ' UNIQUE';\r
-               } else {\r
-                       $unique = '';\r
-               }\r
-               \r
-               if ( is_array($flds) )\r
-                       $flds = implode(', ',$flds);\r
-               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';\r
-               \r
-               if ( isset($idxoptions[$this->upperName]) )\r
-                       $s .= $idxoptions[$this->upperName];\r
-               \r
-               $sql[] = $s;\r
-               \r
-               return $sql;\r
-       }\r
-}\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+*/
+
+class ADODB2_mysql extends ADODB_DataDict {
+       var $databaseType = 'mysql';
+       var $alterCol = ' MODIFY COLUMN';
+       var $alterTableAddIndex = true;
+       var $dropTable = 'DROP TABLE IF EXISTS %s'; // requires mysql 3.22 or later
+       
+       var $dropIndex = 'DROP INDEX %s ON %s';
+       
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               
+               $len = -1; // mysql max_length is not accurate
+               switch (strtoupper($t)) {
+               case 'STRING': 
+               case 'CHAR':
+               case 'VARCHAR': 
+               case 'TINYBLOB': 
+               case 'TINYTEXT': 
+               case 'ENUM': 
+               case 'SET':
+                       if ($len <= $this->blobSize) return 'C';
+                       
+               case 'TEXT':
+               case 'LONGTEXT': 
+               case 'MEDIUMTEXT':
+                       return 'X';
+                       
+               // php_mysql extension always returns 'blob' even if 'text'
+               // so we have to check whether binary...
+               case 'IMAGE':
+               case 'LONGBLOB': 
+               case 'BLOB':
+               case 'MEDIUMBLOB':
+                       return !empty($fieldobj->binary) ? 'B' : 'X';
+                       
+               case 'YEAR':
+               case 'DATE': return 'D';
+               
+               case 'TIME':
+               case 'DATETIME':
+               case 'TIMESTAMP': return 'T';
+               
+               case 'FLOAT':
+               case 'DOUBLE':
+                       return 'F';
+                       
+               case 'INT': 
+               case 'INTEGER': return (!empty($fieldobj->primary_key)) ? 'R' : 'I';
+               case 'TINYINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I1';
+               case 'SMALLINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I2';
+               case 'MEDIUMINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I4';
+               case 'BIGINT':  return (!empty($fieldobj->primary_key)) ? 'R' : 'I8';
+               default: return 'N';
+               }
+       }
+
+       function ActualType($meta)
+       {
+               switch(strtoupper($meta)) {
+               case 'C': return 'VARCHAR';
+               case 'XL':
+               case 'X': return 'LONGTEXT';
+               
+               case 'C2': return 'VARCHAR';
+               case 'X2': return 'LONGTEXT';
+               
+               case 'B': return 'LONGBLOB';
+                       
+               case 'D': return 'DATE';
+               case 'T': return 'DATETIME';
+               case 'L': return 'TINYINT';
+               
+               case 'R':
+               case 'I': return 'INTEGER';
+               case 'I1': return 'TINYINT';
+               case 'I2': return 'SMALLINT';
+               case 'I4': return 'MEDIUMINT';
+               case 'I8': return 'BIGINT';
+               
+               case 'F': return 'DOUBLE';
+               case 'N': return 'NUMERIC';
+               default:
+                       return $meta;
+               }
+       }
+       
+       // return string must begin with space
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
+       {       
+               $suffix = '';
+               if ($funsigned) $suffix .= ' UNSIGNED';
+               if ($fnotnull) $suffix .= ' NOT NULL';
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+               if ($fautoinc) $suffix .= ' AUTO_INCREMENT';
+               if ($fconstraint) $suffix .= ' '.$fconstraint;
+               return $suffix;
+       }
+       
+       /*
+       CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
+               [table_options] [select_statement]
+               create_definition:
+               col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
+               [PRIMARY KEY] [reference_definition]
+               or PRIMARY KEY (index_col_name,...)
+               or KEY [index_name] (index_col_name,...)
+               or INDEX [index_name] (index_col_name,...)
+               or UNIQUE [INDEX] [index_name] (index_col_name,...)
+               or FULLTEXT [INDEX] [index_name] (index_col_name,...)
+               or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
+               [reference_definition]
+               or CHECK (expr)
+       */
+       
+       /*
+       CREATE [UNIQUE|FULLTEXT] INDEX index_name
+               ON tbl_name (col_name[(length)],... )
+       */
+       
+       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+       {
+               $sql = array();
+               
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+                       if ($this->alterTableAddIndex) $sql[] = "ALTER TABLE $tabname DROP INDEX $idxname";
+                       else $sql[] = sprintf($this->dropIndex, $idxname, $tabname);
+
+                       if ( isset($idxoptions['DROP']) )
+                               return $sql;
+               }
+               
+               if ( empty ($flds) ) {
+                       return $sql;
+               }
+               
+               if (isset($idxoptions['FULLTEXT'])) {
+                       $unique = ' FULLTEXT';
+               } elseif (isset($idxoptions['UNIQUE'])) {
+                       $unique = ' UNIQUE';
+               } else {
+                       $unique = '';
+               }
+               
+               if ( is_array($flds) ) $flds = implode(', ',$flds);
+               
+               if ($this->alterTableAddIndex) $s = "ALTER TABLE $tabname ADD $unique INDEX $idxname ";
+               else $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname;
+               
+               $s .= ' (' . $flds . ')';
+               
+               if ( isset($idxoptions[$this->upperName]) )
+                       $s .= $idxoptions[$this->upperName];
+               
+               $sql[] = $s;
+               
+               return $sql;
+       }
+}
 ?>
\ No newline at end of file
index e3afdd8067ffcbc614bf782fcc7602d4089a262a..cd038f7931d2e9ce0544537c8d531c4cc176b4d4 100644 (file)
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-*/\r
-\r
-class ADODB2_oci8 extends ADODB_DataDict {\r
-       \r
-       var $databaseType = 'oci8';\r
-       var $seqField = false;\r
-       var $seqPrefix = 'SEQ_';\r
-       var $dropTable = "DROP TABLE %s CASCADE CONSTRAINTS";\r
-       \r
-       function MetaType($t,$len=-1)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               switch (strtoupper($t)) {\r
-               case 'VARCHAR':\r
-               case 'VARCHAR2':\r
-               case 'CHAR':\r
-               case 'VARBINARY':\r
-               case 'BINARY':\r
-                       if (isset($this) && $len <= $this->blobSize) return 'C';\r
-                       return 'X';\r
-               \r
-               case 'NCHAR':\r
-               case 'NVARCHAR2':\r
-               case 'NVARCHAR':\r
-                       if (isset($this) && $len <= $this->blobSize) return 'C2';\r
-                       return 'X2';\r
-                       \r
-               case 'NCLOB':\r
-               case 'CLOB':\r
-                       return 'XL';\r
-               \r
-               case 'LONG RAW':\r
-               case 'LONG VARBINARY':\r
-               case 'BLOB':\r
-                       return 'B';\r
-               \r
-               case 'DATE': \r
-                       return 'T';\r
-               \r
-               case 'INT': \r
-               case 'SMALLINT':\r
-               case 'INTEGER': \r
-                       return 'I';\r
-                       \r
-               default:\r
-                       return 'N';\r
-               }\r
-       }\r
-       \r
-       function ActualType($meta)\r
-       {\r
-               switch($meta) {\r
-               case 'C': return 'VARCHAR';\r
-               case 'X': return 'VARCHAR(4000)';\r
-               case 'XL': return 'CLOB';\r
-               \r
-               case 'C2': return 'NVARCHAR';\r
-               case 'X2': return 'NVARCHAR(2000)';\r
-               \r
-               case 'B': return 'BLOB';\r
-                       \r
-               case 'D': \r
-               case 'T': return 'DATE';\r
-               case 'L': return 'DECIMAL(1)';\r
-               case 'I1': return 'DECIMAL(3)';\r
-               case 'I2': return 'DECIMAL(5)';\r
-               case 'I':\r
-               case 'I4': return 'DECIMAL(10)';\r
-               \r
-               case 'I8': return 'DECIMAL(20)';\r
-               case 'F': return 'DECIMAL';\r
-               case 'N': return 'DECIMAL';\r
-               default:\r
-                       return $meta;\r
-               }       \r
-       }\r
-       \r
-       function CreateDatabase($dbname, $options=false)\r
-       {\r
-               $options = $this->_Options($options);\r
-               $password = isset($options['PASSWORD']) ? $options['PASSWORD'] : 'tiger';\r
-               $tablespace = isset($options["TABLESPACE"]) ? " DEFAULT TABLESPACE ".$options["TABLESPACE"] : '';\r
-               $sql[] = "CREATE USER ".$dbname." IDENTIFIED BY ".$password.$tablespace;\r
-               $sql[] = "GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO $dbname";\r
-               \r
-               return $sql;\r
-       }\r
-       \r
-       function AddColumnSQL($tabname, $flds)\r
-       {\r
-               $f = array();\r
-               list($lines,$pkey) = $this->_GenFields($flds);\r
-               $s = "ALTER TABLE $tabname ADD (";\r
-               foreach($lines as $v) {\r
-                       $f[] = "\n $v";\r
-               }\r
-               \r
-               $s .= implode(',',$f).')';\r
-               $sql[] = $s;\r
-               return $sql;\r
-       }\r
-       \r
-       function AlterColumnSQL($tabname, $flds)\r
-       {\r
-               $f = array();\r
-               list($lines,$pkey) = $this->_GenFields($flds);\r
-               $s = "ALTER TABLE $tabname MODIFY(";\r
-               foreach($lines as $v) {\r
-                       $f[] = "\n $v";\r
-               }\r
-               $s .= implode(',',$f).')';\r
-               $sql[] = $s;\r
-               return $sql;\r
-       }\r
-       \r
-       function DropColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported for Oracle");\r
-               return array();\r
-       }\r
-       \r
-       function _DropAutoIncrement($t)\r
-       {\r
-               if (strpos($t,'.') !== false) {\r
-                       $tarr = explode('.',$t);\r
-                       return "drop sequence ".$tarr[0].".seq_".$tarr[1];\r
-               }\r
-               return "drop sequence seq_".$t;\r
-       }\r
-       \r
-       // return string must begin with space\r
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)\r
-       {\r
-               $suffix = '';\r
-               \r
-               if ($fdefault == "''" && $fnotnull) {// this is null in oracle\r
-                       $fnotnull = false;\r
-                       if ($this->debug) ADOConnection::outp("NOT NULL and DEFAULT='' illegal in Oracle");\r
-               }\r
-               \r
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
-               if ($fnotnull) $suffix .= ' NOT NULL';\r
-               \r
-               if ($fautoinc) $this->seqField = $fname;\r
-               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
-               \r
-               return $suffix;\r
-       }\r
-       \r
-/*\r
-CREATE or replace TRIGGER jaddress_insert\r
-before insert on jaddress\r
-for each row\r
-begin\r
-select seqaddress.nextval into :new.A_ID from dual;\r
-end;\r
-*/\r
-       function _Triggers($tabname,$tableoptions)\r
-       {\r
-               if (!$this->seqField) return array();\r
-               \r
-               if ($this->schema) {\r
-                       $t = strpos($tabname,'.');\r
-                       if ($t !== false) $tab = substr($tabname,$t+1);\r
-                       else $tab = $tabname;\r
-                       $seqname = $this->schema.'.'.$this->seqPrefix.$tab;\r
-                       $trigname = $this->schema.'.TRIG_'.$this->seqPrefix.$tab;\r
-               } else {\r
-                       $seqname = $this->seqPrefix.$tabname;\r
-                       $trigname = "TRIG_$seqname";\r
-               }\r
-               if (isset($tableoptions['REPLACE'])) $sql[] = "DROP SEQUENCE $seqname";\r
-               $sql[] = "CREATE SEQUENCE $seqname";\r
-               $sql[] = "CREATE OR REPLACE TRIGGER $trigname BEFORE insert ON $tabname FOR EACH ROW BEGIN select $seqname.nextval into :new.$this->seqField from dual; END;";\r
-               \r
-               $this->seqField = false;\r
-               return $sql;\r
-       }\r
-       \r
-       /*\r
-       CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]\r
-               [table_options] [select_statement]\r
-               create_definition:\r
-               col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]\r
-               [PRIMARY KEY] [reference_definition]\r
-               or PRIMARY KEY (index_col_name,...)\r
-               or KEY [index_name] (index_col_name,...)\r
-               or INDEX [index_name] (index_col_name,...)\r
-               or UNIQUE [INDEX] [index_name] (index_col_name,...)\r
-               or FULLTEXT [INDEX] [index_name] (index_col_name,...)\r
-               or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)\r
-               [reference_definition]\r
-               or CHECK (expr)\r
-       */\r
-       \r
-\r
-       \r
-       function _IndexSQL($idxname, $tabname, $flds,$idxoptions)\r
-       {\r
-               $sql = array();\r
-               \r
-               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
-                       $sql[] = sprintf ($this->dropIndex, $idxname);\r
-                       if ( isset($idxoptions['DROP']) )\r
-                               return $sql;\r
-               }\r
-               \r
-               if ( empty ($flds) ) {\r
-                       return $sql;\r
-               }\r
-               \r
-               if (isset($idxoptions['BITMAP'])) {\r
-                       $unique = ' BITMAP'; \r
-               } elseif (isset($idxoptions['UNIQUE'])) {\r
-                       $unique = ' UNIQUE';\r
-               } else {\r
-                       $unique = '';\r
-               }\r
-               \r
-               if ( is_array($flds) )\r
-                       $flds = implode(', ',$flds);\r
-               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';\r
-               \r
-               if ( isset($idxoptions[$this->upperName]) )\r
-                       $s .= $idxoptions[$this->upperName];\r
-               \r
-               if (isset($idxoptions['oci8']))\r
-                       $s .= $idxoptions['oci8'];\r
-               \r
-\r
-               $sql[] = $s;\r
-               \r
-               return $sql;\r
-       }\r
-       \r
-       function GetCommentSQL($table,$col)\r
-       {\r
-               $table = $this->connection->qstr($table);\r
-               $col = $this->connection->qstr($col);   \r
-               return "select comments from USER_COL_COMMENTS where TABLE_NAME=$table and COLUMN_NAME=$col";\r
-       }\r
-       \r
-       function SetCommentSQL($table,$col,$cmt)\r
-       {\r
-               $cmt = $this->connection->qstr($cmt);\r
-               return  "COMMENT ON COLUMN $table.$col IS $cmt";\r
-       }\r
-}\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+*/
+
+class ADODB2_oci8 extends ADODB_DataDict {
+       
+       var $databaseType = 'oci8';
+       var $seqField = false;
+       var $seqPrefix = 'SEQ_';
+       var $dropTable = "DROP TABLE %s CASCADE CONSTRAINTS";
+       
+       function MetaType($t,$len=-1)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               switch (strtoupper($t)) {
+               case 'VARCHAR':
+               case 'VARCHAR2':
+               case 'CHAR':
+               case 'VARBINARY':
+               case 'BINARY':
+                       if (isset($this) && $len <= $this->blobSize) return 'C';
+                       return 'X';
+               
+               case 'NCHAR':
+               case 'NVARCHAR2':
+               case 'NVARCHAR':
+                       if (isset($this) && $len <= $this->blobSize) return 'C2';
+                       return 'X2';
+                       
+               case 'NCLOB':
+               case 'CLOB':
+                       return 'XL';
+               
+               case 'LONG RAW':
+               case 'LONG VARBINARY':
+               case 'BLOB':
+                       return 'B';
+               
+               case 'DATE': 
+                       return 'T';
+               
+               case 'INT': 
+               case 'SMALLINT':
+               case 'INTEGER': 
+                       return 'I';
+                       
+               default:
+                       return 'N';
+               }
+       }
+       
+       function ActualType($meta)
+       {
+               switch($meta) {
+               case 'C': return 'VARCHAR';
+               case 'X': return 'VARCHAR(4000)';
+               case 'XL': return 'CLOB';
+               
+               case 'C2': return 'NVARCHAR';
+               case 'X2': return 'NVARCHAR(2000)';
+               
+               case 'B': return 'BLOB';
+                       
+               case 'D': 
+               case 'T': return 'DATE';
+               case 'L': return 'DECIMAL(1)';
+               case 'I1': return 'DECIMAL(3)';
+               case 'I2': return 'DECIMAL(5)';
+               case 'I':
+               case 'I4': return 'DECIMAL(10)';
+               
+               case 'I8': return 'DECIMAL(20)';
+               case 'F': return 'DECIMAL';
+               case 'N': return 'DECIMAL';
+               default:
+                       return $meta;
+               }       
+       }
+       
+       function CreateDatabase($dbname, $options=false)
+       {
+               $options = $this->_Options($options);
+               $password = isset($options['PASSWORD']) ? $options['PASSWORD'] : 'tiger';
+               $tablespace = isset($options["TABLESPACE"]) ? " DEFAULT TABLESPACE ".$options["TABLESPACE"] : '';
+               $sql[] = "CREATE USER ".$dbname." IDENTIFIED BY ".$password.$tablespace;
+               $sql[] = "GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO $dbname";
+               
+               return $sql;
+       }
+       
+       function AddColumnSQL($tabname, $flds)
+       {
+               $f = array();
+               list($lines,$pkey) = $this->_GenFields($flds);
+               $s = "ALTER TABLE $tabname ADD (";
+               foreach($lines as $v) {
+                       $f[] = "\n $v";
+               }
+               
+               $s .= implode(',',$f).')';
+               $sql[] = $s;
+               return $sql;
+       }
+       
+       function AlterColumnSQL($tabname, $flds)
+       {
+               $f = array();
+               list($lines,$pkey) = $this->_GenFields($flds);
+               $s = "ALTER TABLE $tabname MODIFY(";
+               foreach($lines as $v) {
+                       $f[] = "\n $v";
+               }
+               $s .= implode(',',$f).')';
+               $sql[] = $s;
+               return $sql;
+       }
+       
+       function DropColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("DropColumnSQL not supported for Oracle");
+               return array();
+       }
+       
+       function _DropAutoIncrement($t)
+       {
+               if (strpos($t,'.') !== false) {
+                       $tarr = explode('.',$t);
+                       return "drop sequence ".$tarr[0].".seq_".$tarr[1];
+               }
+               return "drop sequence seq_".$t;
+       }
+       
+       // return string must begin with space
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
+       {
+               $suffix = '';
+               
+               if ($fdefault == "''" && $fnotnull) {// this is null in oracle
+                       $fnotnull = false;
+                       if ($this->debug) ADOConnection::outp("NOT NULL and DEFAULT='' illegal in Oracle");
+               }
+               
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+               if ($fnotnull) $suffix .= ' NOT NULL';
+               
+               if ($fautoinc) $this->seqField = $fname;
+               if ($fconstraint) $suffix .= ' '.$fconstraint;
+               
+               return $suffix;
+       }
+       
+/*
+CREATE or replace TRIGGER jaddress_insert
+before insert on jaddress
+for each row
+begin
+select seqaddress.nextval into :new.A_ID from dual;
+end;
+*/
+       function _Triggers($tabname,$tableoptions)
+       {
+               if (!$this->seqField) return array();
+               
+               if ($this->schema) {
+                       $t = strpos($tabname,'.');
+                       if ($t !== false) $tab = substr($tabname,$t+1);
+                       else $tab = $tabname;
+                       $seqname = $this->schema.'.'.$this->seqPrefix.$tab;
+                       $trigname = $this->schema.'.TRIG_'.$this->seqPrefix.$tab;
+               } else {
+                       $seqname = $this->seqPrefix.$tabname;
+                       $trigname = "TRIG_$seqname";
+               }
+               if (isset($tableoptions['REPLACE'])) $sql[] = "DROP SEQUENCE $seqname";
+               $sql[] = "CREATE SEQUENCE $seqname";
+               $sql[] = "CREATE OR REPLACE TRIGGER $trigname BEFORE insert ON $tabname FOR EACH ROW BEGIN select $seqname.nextval into :new.$this->seqField from dual; END;";
+               
+               $this->seqField = false;
+               return $sql;
+       }
+       
+       /*
+       CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
+               [table_options] [select_statement]
+               create_definition:
+               col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
+               [PRIMARY KEY] [reference_definition]
+               or PRIMARY KEY (index_col_name,...)
+               or KEY [index_name] (index_col_name,...)
+               or INDEX [index_name] (index_col_name,...)
+               or UNIQUE [INDEX] [index_name] (index_col_name,...)
+               or FULLTEXT [INDEX] [index_name] (index_col_name,...)
+               or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
+               [reference_definition]
+               or CHECK (expr)
+       */
+       
+
+       
+       function _IndexSQL($idxname, $tabname, $flds,$idxoptions)
+       {
+               $sql = array();
+               
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+                       $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
+                       if ( isset($idxoptions['DROP']) )
+                               return $sql;
+               }
+               
+               if ( empty ($flds) ) {
+                       return $sql;
+               }
+               
+               if (isset($idxoptions['BITMAP'])) {
+                       $unique = ' BITMAP'; 
+               } elseif (isset($idxoptions['UNIQUE'])) {
+                       $unique = ' UNIQUE';
+               } else {
+                       $unique = '';
+               }
+               
+               if ( is_array($flds) )
+                       $flds = implode(', ',$flds);
+               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';
+               
+               if ( isset($idxoptions[$this->upperName]) )
+                       $s .= $idxoptions[$this->upperName];
+               
+               if (isset($idxoptions['oci8']))
+                       $s .= $idxoptions['oci8'];
+               
+
+               $sql[] = $s;
+               
+               return $sql;
+       }
+       
+       function GetCommentSQL($table,$col)
+       {
+               $table = $this->connection->qstr($table);
+               $col = $this->connection->qstr($col);   
+               return "select comments from USER_COL_COMMENTS where TABLE_NAME=$table and COLUMN_NAME=$col";
+       }
+       
+       function SetCommentSQL($table,$col,$cmt)
+       {
+               $cmt = $this->connection->qstr($cmt);
+               return  "COMMENT ON COLUMN $table.$col IS $cmt";
+       }
+}
 ?>
\ No newline at end of file
index 6279227fe05fad1c97d4d45b4cf61ea28a4637dc..9005ac55948413ce91cebaa9f2cff0dbfb47f2b0 100644 (file)
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-*/\r
-\r
-class ADODB2_postgres extends ADODB_DataDict {\r
-       \r
-       var $databaseType = 'postgres';\r
-       var $seqField = false;\r
-       var $seqPrefix = 'SEQ_';\r
-       var $addCol = ' ADD COLUMN';\r
-       var $quote = '"';\r
-       \r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               switch (strtoupper($t)) {\r
-                       case 'INTERVAL':\r
-                       case 'CHAR':\r
-                       case 'CHARACTER':\r
-                       case 'VARCHAR':\r
-                       case 'NAME':\r
-                       case 'BPCHAR':\r
-                               if ($len <= $this->blobSize) return 'C';\r
-                       \r
-                       case 'TEXT':\r
-                               return 'X';\r
-       \r
-                       case 'IMAGE': // user defined type\r
-                       case 'BLOB': // user defined type\r
-                       case 'BIT':     // This is a bit string, not a single bit, so don't return 'L'\r
-                       case 'VARBIT':\r
-                       case 'BYTEA':\r
-                               return 'B';\r
-                       \r
-                       case 'BOOL':\r
-                       case 'BOOLEAN':\r
-                               return 'L';\r
-                       \r
-                       case 'DATE':\r
-                               return 'D';\r
-                       \r
-                       case 'TIME':\r
-                       case 'DATETIME':\r
-                       case 'TIMESTAMP':\r
-                       case 'TIMESTAMPTZ':\r
-                               return 'T';\r
-                       \r
-                       case 'INTEGER': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I' : 'R';\r
-                       case 'SMALLINT': \r
-                       case 'INT2': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I2' : 'R';\r
-                       case 'INT4': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I4' : 'R';\r
-                       case 'BIGINT': \r
-                       case 'INT8': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I8' : 'R';\r
-                               \r
-                       case 'OID':\r
-                       case 'SERIAL':\r
-                               return 'R';\r
-                       \r
-                       case 'FLOAT4':\r
-                       case 'FLOAT8':\r
-                       case 'DOUBLE PRECISION':\r
-                       case 'REAL':\r
-                               return 'F';\r
-                               \r
-                        default:\r
-                               return 'N';\r
-               }\r
-       }\r
-       \r
-       function ActualType($meta)\r
-       {\r
-               switch($meta) {\r
-               case 'C': return 'VARCHAR';\r
-               case 'XL':\r
-               case 'X': return 'TEXT';\r
-               \r
-               case 'C2': return 'VARCHAR';\r
-               case 'X2': return 'TEXT';\r
-               \r
-               case 'B': return 'BYTEA';\r
-                       \r
-               case 'D': return 'DATE';\r
-               case 'T': return 'TIMESTAMP';\r
-               \r
-               case 'L': return 'SMALLINT';\r
-               case 'I': return 'INTEGER';\r
-               case 'I1': return 'SMALLINT';\r
-               case 'I2': return 'INT2';\r
-               case 'I4': return 'INT4';\r
-               case 'I8': return 'INT8';\r
-               \r
-               case 'F': return 'FLOAT8';\r
-               case 'N': return 'NUMERIC';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-       \r
-       /* The following does not work in Pg 6.0 - does anyone want to contribute code? \r
-       \r
-       //"ALTER TABLE table ALTER COLUMN column SET DEFAULT mydef" and\r
-       //"ALTER TABLE table ALTER COLUMN column DROP DEFAULT mydef"\r
-       //"ALTER TABLE table ALTER COLUMN column SET NOT NULL" and\r
-       //"ALTER TABLE table ALTER COLUMN column DROP NOT NULL"*/\r
-       function AlterColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported for PostgreSQL");\r
-               return array();\r
-       }\r
-       \r
-       \r
-       function DropColumnSQL($tabname, $flds)\r
-       {\r
-               if ($this->debug) ADOConnection::outp("DropColumnSQL only works with PostgreSQL 7.3+");\r
-               return ADODB_DataDict::DropColumnSQL($tabname, $flds)."/* only works for PostgreSQL 7.3+ */";\r
-       }\r
-\r
-       // return string must begin with space\r
-       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)\r
-       {\r
-               if ($fautoinc) {\r
-                       $ftype = 'SERIAL';\r
-                       return '';\r
-               }\r
-               $suffix = '';\r
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
-               if ($fnotnull) $suffix .= ' NOT NULL';\r
-               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
-               return $suffix;\r
-       }\r
-       \r
-       function _DropAutoIncrement($t)\r
-       {\r
-               return "drop sequence ".$t."_m_id_seq";\r
-       }\r
-       \r
-       /*\r
-       CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (\r
-       { column_name data_type [ DEFAULT default_expr ] [ column_constraint [, ... ] ]\r
-       | table_constraint } [, ... ]\r
-       )\r
-       [ INHERITS ( parent_table [, ... ] ) ]\r
-       [ WITH OIDS | WITHOUT OIDS ]\r
-       where column_constraint is:\r
-       [ CONSTRAINT constraint_name ]\r
-       { NOT NULL | NULL | UNIQUE | PRIMARY KEY |\r
-       CHECK (expression) |\r
-       REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]\r
-       [ ON DELETE action ] [ ON UPDATE action ] }\r
-       [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\r
-       and table_constraint is:\r
-       [ CONSTRAINT constraint_name ]\r
-       { UNIQUE ( column_name [, ... ] ) |\r
-       PRIMARY KEY ( column_name [, ... ] ) |\r
-       CHECK ( expression ) |\r
-       FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]\r
-       [ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ] }\r
-       [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]\r
-       */\r
-       \r
-       \r
-       /*\r
-       CREATE [ UNIQUE ] INDEX index_name ON table\r
-[ USING acc_method ] ( column [ ops_name ] [, ...] )\r
-[ WHERE predicate ]\r
-CREATE [ UNIQUE ] INDEX index_name ON table\r
-[ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )\r
-[ WHERE predicate ]\r
-       */\r
-       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)\r
-       {\r
-               $sql = array();\r
-               \r
-               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
-                       $sql[] = sprintf ($this->dropIndex, $idxname);\r
-                       if ( isset($idxoptions['DROP']) )\r
-                               return $sql;\r
-               }\r
-               \r
-               if ( empty ($flds) ) {\r
-                       return $sql;\r
-               }\r
-               \r
-               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';\r
-               \r
-               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';\r
-               \r
-               if (isset($idxoptions['HASH']))\r
-                       $s .= 'USING HASH ';\r
-               \r
-               if ( isset($idxoptions[$this->upperName]) )\r
-                       $s .= $idxoptions[$this->upperName];\r
-               \r
-               if ( is_array($flds) )\r
-                       $flds = implode(', ',$flds);\r
-               $s .= '(' . $flds . ')';\r
-               $sql[] = $s;\r
-               \r
-               return $sql;\r
-       }\r
-}\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+*/
+
+class ADODB2_postgres extends ADODB_DataDict {
+       
+       var $databaseType = 'postgres';
+       var $seqField = false;
+       var $seqPrefix = 'SEQ_';
+       var $addCol = ' ADD COLUMN';
+       var $quote = '"';
+       
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               switch (strtoupper($t)) {
+                       case 'INTERVAL':
+                       case 'CHAR':
+                       case 'CHARACTER':
+                       case 'VARCHAR':
+                       case 'NAME':
+                       case 'BPCHAR':
+                               if ($len <= $this->blobSize) return 'C';
+                       
+                       case 'TEXT':
+                               return 'X';
+       
+                       case 'IMAGE': // user defined type
+                       case 'BLOB': // user defined type
+                       case 'BIT':     // This is a bit string, not a single bit, so don't return 'L'
+                       case 'VARBIT':
+                       case 'BYTEA':
+                               return 'B';
+                       
+                       case 'BOOL':
+                       case 'BOOLEAN':
+                               return 'L';
+                       
+                       case 'DATE':
+                               return 'D';
+                       
+                       case 'TIME':
+                       case 'DATETIME':
+                       case 'TIMESTAMP':
+                       case 'TIMESTAMPTZ':
+                               return 'T';
+                       
+                       case 'INTEGER': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I' : 'R';
+                       case 'SMALLINT': 
+                       case 'INT2': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I2' : 'R';
+                       case 'INT4': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I4' : 'R';
+                       case 'BIGINT': 
+                       case 'INT8': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I8' : 'R';
+                               
+                       case 'OID':
+                       case 'SERIAL':
+                               return 'R';
+                       
+                       case 'FLOAT4':
+                       case 'FLOAT8':
+                       case 'DOUBLE PRECISION':
+                       case 'REAL':
+                               return 'F';
+                               
+                        default:
+                               return 'N';
+               }
+       }
+       
+       function ActualType($meta)
+       {
+               switch($meta) {
+               case 'C': return 'VARCHAR';
+               case 'XL':
+               case 'X': return 'TEXT';
+               
+               case 'C2': return 'VARCHAR';
+               case 'X2': return 'TEXT';
+               
+               case 'B': return 'BYTEA';
+                       
+               case 'D': return 'DATE';
+               case 'T': return 'TIMESTAMP';
+               
+               case 'L': return 'SMALLINT';
+               case 'I': return 'INTEGER';
+               case 'I1': return 'SMALLINT';
+               case 'I2': return 'INT2';
+               case 'I4': return 'INT4';
+               case 'I8': return 'INT8';
+               
+               case 'F': return 'FLOAT8';
+               case 'N': return 'NUMERIC';
+               default:
+                       return $meta;
+               }
+       }
+       
+       /* The following does not work in Pg 6.0 - does anyone want to contribute code? 
+       
+       //"ALTER TABLE table ALTER COLUMN column SET DEFAULT mydef" and
+       //"ALTER TABLE table ALTER COLUMN column DROP DEFAULT mydef"
+       //"ALTER TABLE table ALTER COLUMN column SET NOT NULL" and
+       //"ALTER TABLE table ALTER COLUMN column DROP NOT NULL"*/
+       function AlterColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported for PostgreSQL");
+               return array();
+       }
+       
+       
+       function DropColumnSQL($tabname, $flds)
+       {
+               if ($this->debug) ADOConnection::outp("DropColumnSQL only works with PostgreSQL 7.3+");
+               return ADODB_DataDict::DropColumnSQL($tabname, $flds)."/* only works for PostgreSQL 7.3+ */";
+       }
+
+       // return string must begin with space
+       function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
+       {
+               if ($fautoinc) {
+                       $ftype = 'SERIAL';
+                       return '';
+               }
+               $suffix = '';
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+               if ($fnotnull) $suffix .= ' NOT NULL';
+               if ($fconstraint) $suffix .= ' '.$fconstraint;
+               return $suffix;
+       }
+       
+       function _DropAutoIncrement($t)
+       {
+               return "drop sequence ".$t."_m_id_seq";
+       }
+       
+       /*
+       CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
+       { column_name data_type [ DEFAULT default_expr ] [ column_constraint [, ... ] ]
+       | table_constraint } [, ... ]
+       )
+       [ INHERITS ( parent_table [, ... ] ) ]
+       [ WITH OIDS | WITHOUT OIDS ]
+       where column_constraint is:
+       [ CONSTRAINT constraint_name ]
+       { NOT NULL | NULL | UNIQUE | PRIMARY KEY |
+       CHECK (expression) |
+       REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
+       [ ON DELETE action ] [ ON UPDATE action ] }
+       [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
+       and table_constraint is:
+       [ CONSTRAINT constraint_name ]
+       { UNIQUE ( column_name [, ... ] ) |
+       PRIMARY KEY ( column_name [, ... ] ) |
+       CHECK ( expression ) |
+       FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
+       [ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ] }
+       [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
+       */
+       
+       
+       /*
+       CREATE [ UNIQUE ] INDEX index_name ON table
+[ USING acc_method ] ( column [ ops_name ] [, ...] )
+[ WHERE predicate ]
+CREATE [ UNIQUE ] INDEX index_name ON table
+[ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
+[ WHERE predicate ]
+       */
+       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+       {
+               $sql = array();
+               
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+                       $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
+                       if ( isset($idxoptions['DROP']) )
+                               return $sql;
+               }
+               
+               if ( empty ($flds) ) {
+                       return $sql;
+               }
+               
+               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
+               
+               $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
+               
+               if (isset($idxoptions['HASH']))
+                       $s .= 'USING HASH ';
+               
+               if ( isset($idxoptions[$this->upperName]) )
+                       $s .= $idxoptions[$this->upperName];
+               
+               if ( is_array($flds) )
+                       $flds = implode(', ',$flds);
+               $s .= '(' . $flds . ')';
+               $sql[] = $s;
+               
+               return $sql;
+       }
+}
 ?>
\ No newline at end of file
index 37d1874b90432ccb1f001a4d3620b8c2fec4b362..50c7494dd73c90892948428d0b506ab3bedc0b23 100644 (file)
-<?php\r
-\r
-/**\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
\r
-*/\r
-\r
-class ADODB2_sybase extends ADODB_DataDict {\r
-       var $databaseType = 'sybase';\r
-       \r
-       \r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               \r
-               $len = -1; // mysql max_length is not accurate\r
-               switch (strtoupper($t)) {\r
-\r
-               case 'INT': \r
-               case 'INTEGER': return  'I';\r
-               case 'BIT':\r
-               case 'TINYINT': return  'I1';\r
-               case 'SMALLINT': return 'I2';\r
-               case 'BIGINT':  return  'I8';\r
-               \r
-               case 'REAL':\r
-               case 'FLOAT': return 'F';\r
-               default: return parent::MetaType($t,$len,$fieldobj);\r
-               }\r
-       }\r
-       \r
-       function ActualType($meta)\r
-       {\r
-               switch(strtoupper($meta)) {\r
-               case 'C': return 'VARCHAR';\r
-               case 'XL':\r
-               case 'X': return 'TEXT';\r
-               \r
-               case 'C2': return 'NVARCHAR';\r
-               case 'X2': return 'NTEXT';\r
-               \r
-               case 'B': return 'IMAGE';\r
-                       \r
-               case 'D': return 'DATETIME';\r
-               case 'T': return 'DATETIME';\r
-               case 'L': return 'BIT';\r
-               \r
-               case 'I': return 'INT'; \r
-               case 'I1': return 'TINYINT';\r
-               case 'I2': return 'SMALLINT';\r
-               case 'I4': return 'INT';\r
-               case 'I8': return 'BIGINT';\r
-               \r
-               case 'F': return 'REAL';\r
-               case 'N': return 'NUMERIC';\r
-               default:\r
-                       return $meta;\r
-               }\r
-       }\r
-       \r
-       \r
-       function AddColumnSQL($tabname, $flds)\r
-       {\r
-               $tabname = $this->TableName ($tabname);\r
-               $f = array();\r
-               list($lines,$pkey) = $this->_GenFields($flds);\r
-               $s = "ALTER TABLE $tabname $this->addCol";\r
-               foreach($lines as $v) {\r
-                       $f[] = "\n $v";\r
-               }\r
-               $s .= implode(',',$f);\r
-               $sql[] = $s;\r
-               return $sql;\r
-       }\r
-       \r
-       function AlterColumnSQL($tabname, $flds)\r
-       {\r
-               $tabname = $this->TableName ($tabname);\r
-               $sql = array();\r
-               list($lines,$pkey) = $this->_GenFields($flds);\r
-               foreach($lines as $v) {\r
-                       $sql[] = "ALTER TABLE $tabname $this->alterCol $v";\r
-               }\r
-\r
-               return $sql;\r
-       }\r
-       \r
-       function DropColumnSQL($tabname, $flds)\r
-       {\r
-               $tabname = $this->TableName ($tabname);\r
-               if (!is_array($flds)) $flds = explode(',',$flds);\r
-               $f = array();\r
-               $s = "ALTER TABLE $tabname";\r
-               foreach($flds as $v) {\r
-                       $f[] = "\n$this->dropCol $v";\r
-               }\r
-               $s .= implode(',',$f);\r
-               $sql[] = $s;\r
-               return $sql;\r
-       }\r
-       \r
-       // return string must begin with space\r
-       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)\r
-       {       \r
-               $suffix = '';\r
-               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";\r
-               if ($fautoinc) $suffix .= ' DEFAULT AUTOINCREMENT';\r
-               if ($fnotnull) $suffix .= ' NOT NULL';\r
-               else if ($suffix == '') $suffix .= ' NULL';\r
-               if ($fconstraint) $suffix .= ' '.$fconstraint;\r
-               return $suffix;\r
-       }\r
-       \r
-       /*\r
-CREATE TABLE \r
-    [ database_name.[ owner ] . | owner. ] table_name \r
-    ( { < column_definition > \r
-        | column_name AS computed_column_expression \r
-        | < table_constraint > ::= [ CONSTRAINT constraint_name ] }\r
-\r
-            | [ { PRIMARY KEY | UNIQUE } [ ,...n ] \r
-    ) \r
-\r
-[ ON { filegroup | DEFAULT } ] \r
-[ TEXTIMAGE_ON { filegroup | DEFAULT } ] \r
-\r
-< column_definition > ::= { column_name data_type } \r
-    [ COLLATE < collation_name > ] \r
-    [ [ DEFAULT constant_expression ] \r
-        | [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]\r
-    ] \r
-    [ ROWGUIDCOL] \r
-    [ < column_constraint > ] [ ...n ] \r
-\r
-< column_constraint > ::= [ CONSTRAINT constraint_name ] \r
-    { [ NULL | NOT NULL ] \r
-        | [ { PRIMARY KEY | UNIQUE } \r
-            [ CLUSTERED | NONCLUSTERED ] \r
-            [ WITH FILLFACTOR = fillfactor ] \r
-            [ON {filegroup | DEFAULT} ] ] \r
-        ] \r
-        | [ [ FOREIGN KEY ] \r
-            REFERENCES ref_table [ ( ref_column ) ] \r
-            [ ON DELETE { CASCADE | NO ACTION } ] \r
-            [ ON UPDATE { CASCADE | NO ACTION } ] \r
-            [ NOT FOR REPLICATION ] \r
-        ] \r
-        | CHECK [ NOT FOR REPLICATION ] \r
-        ( logical_expression ) \r
-    } \r
-\r
-< table_constraint > ::= [ CONSTRAINT constraint_name ] \r
-    { [ { PRIMARY KEY | UNIQUE } \r
-        [ CLUSTERED | NONCLUSTERED ] \r
-        { ( column [ ASC | DESC ] [ ,...n ] ) } \r
-        [ WITH FILLFACTOR = fillfactor ] \r
-        [ ON { filegroup | DEFAULT } ] \r
-    ] \r
-    | FOREIGN KEY \r
-        [ ( column [ ,...n ] ) ] \r
-        REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] \r
-        [ ON DELETE { CASCADE | NO ACTION } ] \r
-        [ ON UPDATE { CASCADE | NO ACTION } ] \r
-        [ NOT FOR REPLICATION ] \r
-    | CHECK [ NOT FOR REPLICATION ] \r
-        ( search_conditions ) \r
-    } \r
-\r
-\r
-       */\r
-       \r
-       /*\r
-       CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name \r
-    ON { table | view } ( column [ ASC | DESC ] [ ,...n ] ) \r
-               [ WITH < index_option > [ ,...n] ] \r
-               [ ON filegroup ]\r
-               < index_option > :: = \r
-                   { PAD_INDEX | \r
-                       FILLFACTOR = fillfactor | \r
-                       IGNORE_DUP_KEY | \r
-                       DROP_EXISTING | \r
-                   STATISTICS_NORECOMPUTE | \r
-                   SORT_IN_TEMPDB  \r
-               }\r
-*/\r
-       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)\r
-       {\r
-               $sql = array();\r
-               \r
-               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {\r
-                       $sql[] = sprintf ($this->dropIndex, $tabname . '.' . $idxname);\r
-                       if ( isset($idxoptions['DROP']) )\r
-                               return $sql;\r
-               }\r
-               \r
-               if ( empty ($flds) ) {\r
-                       return $sql;\r
-               }\r
-               \r
-               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';\r
-               $clustered = isset($idxoptions['CLUSTERED']) ? ' CLUSTERED' : '';\r
-               \r
-               if ( is_array($flds) )\r
-                       $flds = implode(', ',$flds);\r
-               $s = 'CREATE' . $unique . $clustered . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';\r
-               \r
-               if ( isset($idxoptions[$this->upperName]) )\r
-                       $s .= $idxoptions[$this->upperName];\r
-\r
-               $sql[] = $s;\r
-               \r
-               return $sql;\r
-       }\r
-}\r
+<?php
+
+/**
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+*/
+
+class ADODB2_sybase extends ADODB_DataDict {
+       var $databaseType = 'sybase';
+       
+       var $dropIndex = 'DROP INDEX %2$s.%1$s';
+       
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               
+               $len = -1; // mysql max_length is not accurate
+               switch (strtoupper($t)) {
+
+               case 'INT': 
+               case 'INTEGER': return  'I';
+               case 'BIT':
+               case 'TINYINT': return  'I1';
+               case 'SMALLINT': return 'I2';
+               case 'BIGINT':  return  'I8';
+               
+               case 'REAL':
+               case 'FLOAT': return 'F';
+               default: return parent::MetaType($t,$len,$fieldobj);
+               }
+       }
+       
+       function ActualType($meta)
+       {
+               switch(strtoupper($meta)) {
+               case 'C': return 'VARCHAR';
+               case 'XL':
+               case 'X': return 'TEXT';
+               
+               case 'C2': return 'NVARCHAR';
+               case 'X2': return 'NTEXT';
+               
+               case 'B': return 'IMAGE';
+                       
+               case 'D': return 'DATETIME';
+               case 'T': return 'DATETIME';
+               case 'L': return 'BIT';
+               
+               case 'I': return 'INT'; 
+               case 'I1': return 'TINYINT';
+               case 'I2': return 'SMALLINT';
+               case 'I4': return 'INT';
+               case 'I8': return 'BIGINT';
+               
+               case 'F': return 'REAL';
+               case 'N': return 'NUMERIC';
+               default:
+                       return $meta;
+               }
+       }
+       
+       
+       function AddColumnSQL($tabname, $flds)
+       {
+               $tabname = $this->TableName ($tabname);
+               $f = array();
+               list($lines,$pkey) = $this->_GenFields($flds);
+               $s = "ALTER TABLE $tabname $this->addCol";
+               foreach($lines as $v) {
+                       $f[] = "\n $v";
+               }
+               $s .= implode(',',$f);
+               $sql[] = $s;
+               return $sql;
+       }
+       
+       function AlterColumnSQL($tabname, $flds)
+       {
+               $tabname = $this->TableName ($tabname);
+               $sql = array();
+               list($lines,$pkey) = $this->_GenFields($flds);
+               foreach($lines as $v) {
+                       $sql[] = "ALTER TABLE $tabname $this->alterCol $v";
+               }
+
+               return $sql;
+       }
+       
+       function DropColumnSQL($tabname, $flds)
+       {
+               $tabname = $this->TableName ($tabname);
+               if (!is_array($flds)) $flds = explode(',',$flds);
+               $f = array();
+               $s = "ALTER TABLE $tabname";
+               foreach($flds as $v) {
+                       $f[] = "\n$this->dropCol $v";
+               }
+               $s .= implode(',',$f);
+               $sql[] = $s;
+               return $sql;
+       }
+       
+       // return string must begin with space
+       function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
+       {       
+               $suffix = '';
+               if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
+               if ($fautoinc) $suffix .= ' DEFAULT AUTOINCREMENT';
+               if ($fnotnull) $suffix .= ' NOT NULL';
+               else if ($suffix == '') $suffix .= ' NULL';
+               if ($fconstraint) $suffix .= ' '.$fconstraint;
+               return $suffix;
+       }
+       
+       /*
+CREATE TABLE 
+    [ database_name.[ owner ] . | owner. ] table_name 
+    ( { < column_definition > 
+        | column_name AS computed_column_expression 
+        | < table_constraint > ::= [ CONSTRAINT constraint_name ] }
+
+            | [ { PRIMARY KEY | UNIQUE } [ ,...n ] 
+    ) 
+
+[ ON { filegroup | DEFAULT } ] 
+[ TEXTIMAGE_ON { filegroup | DEFAULT } ] 
+
+< column_definition > ::= { column_name data_type } 
+    [ COLLATE < collation_name > ] 
+    [ [ DEFAULT constant_expression ] 
+        | [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]
+    ] 
+    [ ROWGUIDCOL] 
+    [ < column_constraint > ] [ ...n ] 
+
+< column_constraint > ::= [ CONSTRAINT constraint_name ] 
+    { [ NULL | NOT NULL ] 
+        | [ { PRIMARY KEY | UNIQUE } 
+            [ CLUSTERED | NONCLUSTERED ] 
+            [ WITH FILLFACTOR = fillfactor ] 
+            [ON {filegroup | DEFAULT} ] ] 
+        ] 
+        | [ [ FOREIGN KEY ] 
+            REFERENCES ref_table [ ( ref_column ) ] 
+            [ ON DELETE { CASCADE | NO ACTION } ] 
+            [ ON UPDATE { CASCADE | NO ACTION } ] 
+            [ NOT FOR REPLICATION ] 
+        ] 
+        | CHECK [ NOT FOR REPLICATION ] 
+        ( logical_expression ) 
+    } 
+
+< table_constraint > ::= [ CONSTRAINT constraint_name ] 
+    { [ { PRIMARY KEY | UNIQUE } 
+        [ CLUSTERED | NONCLUSTERED ] 
+        { ( column [ ASC | DESC ] [ ,...n ] ) } 
+        [ WITH FILLFACTOR = fillfactor ] 
+        [ ON { filegroup | DEFAULT } ] 
+    ] 
+    | FOREIGN KEY 
+        [ ( column [ ,...n ] ) ] 
+        REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] 
+        [ ON DELETE { CASCADE | NO ACTION } ] 
+        [ ON UPDATE { CASCADE | NO ACTION } ] 
+        [ NOT FOR REPLICATION ] 
+    | CHECK [ NOT FOR REPLICATION ] 
+        ( search_conditions ) 
+    } 
+
+
+       */
+       
+       /*
+       CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name 
+    ON { table | view } ( column [ ASC | DESC ] [ ,...n ] ) 
+               [ WITH < index_option > [ ,...n] ] 
+               [ ON filegroup ]
+               < index_option > :: = 
+                   { PAD_INDEX | 
+                       FILLFACTOR = fillfactor | 
+                       IGNORE_DUP_KEY | 
+                       DROP_EXISTING | 
+                   STATISTICS_NORECOMPUTE | 
+                   SORT_IN_TEMPDB  
+               }
+*/
+       function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
+       {
+               $sql = array();
+               
+               if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
+                       $sql[] = sprintf ($this->dropIndex, $idxname, $tabname);
+                       if ( isset($idxoptions['DROP']) )
+                               return $sql;
+               }
+               
+               if ( empty ($flds) ) {
+                       return $sql;
+               }
+               
+               $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
+               $clustered = isset($idxoptions['CLUSTERED']) ? ' CLUSTERED' : '';
+               
+               if ( is_array($flds) )
+                       $flds = implode(', ',$flds);
+               $s = 'CREATE' . $unique . $clustered . ' INDEX ' . $idxname . ' ON ' . $tabname . ' (' . $flds . ')';
+               
+               if ( isset($idxoptions[$this->upperName]) )
+                       $s .= $idxoptions[$this->upperName];
+
+               $sql[] = $s;
+               
+               return $sql;
+       }
+}
 ?>
\ No newline at end of file
index 65b808eb25dbb1a0f4832a4c927b2c1882aca012..b2f2d69bfbf5a36f237a1a1d0ccfb8a2268eb696 100644 (file)
-<html>\r
-<head>\r
-<title>ADODB Manual</title>\r
-<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">\r
-<XSTYLE\r
-       body,td {font-family:Arial,Helvetica,sans-serif;font-size:11pt}\r
-       pre {font-size:9pt}\r
-       .toplink {font-size:8pt}\r
-       />\r
-</head>        \r
-<body bgcolor="#FFFFFF">\r
-\r
-<h2>ADOdb Library for PHP</h2>\r
-<p>V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim#natsoft.com)</p>\r
-<p><font size="1">This software is dual licensed using BSD-Style and LGPL. This \r
-  means you can use it in compiled proprietary and commercial products.</font></p>\r
-       <p>Useful ADOdb links:  <a href=http://php.weblogs.com/adodb>Download</a> &nbsp; <a href=http://php.weblogs.com/adodb_manual>Other Docs</a>\r
-\r
-<p><a href="#intro"><b>Introduction</b></a><b><br>\r
-       <a href="#features">Unique Features</a><br>\r
-       <a href="#users">How People are using ADOdb</a><br>\r
-       <a href="#bugs">Feature Requests and Bug Reports</a><br>\r
-       </b><b><a href="#install">Installation</a><br>\r
-       <a href="#mininstall">Minimum Install</a><br>\r
-       <a href="#coding">Initializing Code and Connection Examples</a><br>\r
-       <font size="2"><a href=#adonewconnection>ADONewConnection</a></font> \r
-       <font size="2"><a href=#adonewconnection>NewADOConnection</a></font><br>\r
-       <a href="#speed">High Speed ADOdb - tuning tips</a></b><br>\r
-       <b><a href="#hack">Hacking and Modifying ADOdb Safely</a><br>\r
-       <a href="#php5">PHP5 Features</a></b><br>\r
-       <font size="2"><a href=#php5iterators>foreach iterators</a> <a href=#php5exceptions>exceptions</a></font><br>\r
-       <b> <a href="#drivers">Supported Databases</a></b><br>\r
-       <b> <a href="#quickstart">Tutorials</a></b><br>\r
-       <a href="#ex1">Example 1: Select</a><br>\r
-       <a href="#ex2">Example 2: Advanced Select</a><br>\r
-       <a href="#ex3">Example 3: Insert</a><br>\r
-       <a href="#ex4">Example 4: Debugging</a> &nbsp;<a href="#exrs2html">rs2html \r
-       example</a><br>\r
-       <a href="#ex5">Example 5: MySQL and Menus</a><br>\r
-       <a href="#ex6">Example 6: Connecting to Multiple Databases at once</a> <br>\r
-       <a href="#ex7">Example 7: Generating Update and Insert SQL</a> <br>\r
-       <a href="#ex8">Example 8: Implementing Scrolling with Next and Previous</a><br>\r
-       <a href="#ex9">Example 9: Exporting in CSV or Tab-Delimited Format</a> <br>\r
-       <a href="#ex10">Example 10: Custom filters</a><br>\r
-       <a href="#ex11">Example 11: Smart Transactions</a><br>\r
-       <br>\r
-       <b> <a href="#errorhandling">Using Custom Error Handlers and PEAR_Error</a><br>\r
-       <a href="#DSN">Data Source Names</a><br>\r
-       <a href="#caching">Caching</a><br>\r
-       <a href="#pivot">Pivot Tables</a></b> \r
-<p><a href="#ref"><b>REFERENCE</b></a>\r
-<p> <font size="2">Variables: <a href="#adodb_countrecs">$ADODB_COUNTRECS</a> <a href=#adodb_ansi_padding_off>$ADODB_ANSI_PADDING_OFF</a>\r
-  <a href="#adodb_cache_dir">$ADODB_CACHE_DIR</a> </font><font size="2"><a href=#adodb_fetch_mode>$ADODB_FETCH_MODE</a> \r
-  <a href=#adodb_lang>$ADODB_LANG</a><br>\r
-  Constants: </font><font size="2"><a href=#adodb_assoc_case>ADODB_ASSOC_CASE</a> \r
-  </font><br>\r
-  <a href="#ADOConnection"><b> ADOConnection</b></a><br>\r
-  <font size="2">Connections: <a href="#connect">Connect</a> <a href="#pconnect">PConnect</a> \r
-  <a href="#nconnect">NConnect</a> <br>\r
-  Executing SQL: <a href="#execute">Execute</a> <a href="#cacheexecute"><i>CacheExecute</i></a> \r
-  <a href="#SelectLimit">SelectLimit</a> <a href="#cacheSelectLimit"><i>CacheSelectLimit</i></a> \r
-  <a href="#param">Param</a> <a href="#prepare">Prepare</a> <a href=#preparesp>PrepareSP</a> \r
-  <a href="#inparameter">InParameter</a> <a href="#outparameter">OutParameter</a>\r
-  <br>\r
-  &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="#getone">GetOne</a> \r
-  <a href="#cachegetone"><i>CacheGetOne</i></a> <a href="#getrow">GetRow</a> <a href="#cachegetrow"><i>CacheGetRow</i></a> \r
-  <a href="#getall">GetAll</a> <a href="#cachegetall"><i>CacheGetAll</i></a> <a href="#getcol">GetCol</a> \r
-  <a href="#cachegetcol"><i>CacheGetCol</i></a> <a href="#getassoc1">GetAssoc</a> <a href="#cachegetassoc"><i>CacheGetAssoc</i></a> <a href="#replace">Replace</a> \r
-  <br>\r
-  &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="#executecursor">ExecuteCursor</a> \r
-  (oci8 only)<br>\r
-  Generates SQL strings: <a href="#getupdatesql">GetUpdateSQL</a> <a href="#getinsertsql">GetInsertSQL</a> \r
-  <a href="#concat">Concat</a> <a href="#ifnull">IfNull</a> <a href="#length">length</a> <a href="#random">random</a> <a href="#substr">substr</a> \r
-  <a href="#qstr">qstr</a> <a href="#param">Param</a> \r
-  <a href="#prepare"></a><a href="#OffsetDate">OffsetDate</a> <a href="#SQLDate">SQLDate</a> \r
-  <a href="#dbdate">DBDate</a> <a href="#dbtimestamp"></a> <a href="#dbtimestamp">DBTimeStamp</a>\r
-  <br>\r
-  Blobs: <a href="#updateblob">UpdateBlob</a> <a href="#updateclob">UpdateClob</a> \r
-  <a href="#updateblobfile">UpdateBlobFile</a> <a href="#blobencode">BlobEncode</a> \r
-  <a href="#blobdecode">BlobDecode</a><br>\r
-  Paging/Scrolling: <a href="#pageexecute">PageExecute</a> <a href="#cachepageexecute">CachePageExecute</a><br>\r
-  Cleanup: <a href="#cacheflush">CacheFlush</a> <a href="#Close">Close</a><br>\r
-  Transactions: <a href="#starttrans">StartTrans</a> <a href="#completetrans">CompleteTrans</a> \r
-  <a href="#failtrans">FailTrans</a> <a href="#hasfailedtrans">HasFailedTrans</a> \r
-  <a href="#begintrans">BeginTrans</a> <a href="#committrans">CommitTrans</a> \r
-  <a href="#rollbacktrans">RollbackTrans</a> <br>\r
-  Fetching Data: </font> <font size="2"><a href="#setfetchmode">SetFetchMode</a><br>\r
-  Strings: <a href="#concat">concat</a> <a href="#length">length</a>  <a href="#qstr">qstr</a> <a href="#quote">quote</a> <a href="#substr">substr</a><br>\r
-  Dates: <a href="#dbdate">DBDate</a> <a href="#dbtimestamp">DBTimeStamp</a> <a href="#unixdate">UnixDate</a> \r
-  <a href="#unixtimestamp">UnixTimeStamp</a> <a href="#OffsetDate">OffsetDate</a> \r
-  <a href="#SQLDate">SQLDate</a> <br>\r
-  Row Management: <a href="#affected_rows">Affected_Rows</a> <a href="#inserted_id">Insert_ID</a>  <a href=#rowlock>RowLock</a>\r
-  <a href="#genid">GenID</a> <a href=#createseq>CreateSequence</a> <a href=#dropseq>DropSequence</a> \r
-  <br>\r
-  Error Handling: <a href="#errormsg">ErrorMsg</a> <a href="#errorno">ErrorNo</a> \r
-  <a href="#metaerror">MetaError</a> <a href="#metaerrormsg">MetaErrorMsg</a><br>\r
-  Data Dictionary (metadata): <a href="#metadatabases">MetaDatabases</a> <a href="#metatables">MetaTables</a> \r
-  <a href="#metacolumns">MetaColumns</a> <a href="#metacolumnames">MetaColumnNames</a> \r
-  <a href="#metaprimarykeys">MetaPrimaryKeys</a> <a href="#metaforeignkeys">MetaForeignKeys</a> \r
-  <a href="#serverinfo">ServerInfo</a> <br>\r
-  Statistics and Query-Rewriting: <a href="#logsql">LogSQL</a> <a href="#fnexecute">fnExecute \r
-  and fnCacheExecute</a><br>\r
-  </font><font size="2">Deprecated: <a href="#bind">Bind</a> <a href="#blankrecordset">BlankRecordSet</a>\r
-  <a href="#parameter">Parameter</a></font>\r
-  <a href="#adorecordSet"><b><br>\r
-  ADORecordSet</b></a><br>\r
-  <font size="2">\r
-  Returns one field: <a href="#fields">Fields</a><br>\r
- Returns one row:<a href="#fetchrow">FetchRow</a> <a href="#fetchinto">FetchInto</a> \r
-  <a href="#fetchobject">FetchObject</a> <a href="#fetchnextobject">FetchNextObject</a> \r
-  <a href="#fetchobj">FetchObj</a> <a href="#fetchnextobj">FetchNextObj</a>\r
- <a href="#getrowassoc">GetRowAssoc</a> <br>\r
-  Returns all rows:<a href="#getarray">GetArray</a> <a href="#getrows">GetRows</a> \r
-  <a href="#getassoc">GetAssoc</a><br>\r
-  Scrolling:<a href="#move">Move</a> <a href="#movenext">MoveNext</a> <a href="#movefirst">MoveFirst</a> \r
-  <a href="#movelast">MoveLast</a> <a href="#abspos">AbsolutePosition</a> <a href="#currentrow">CurrentRow</a> \r
-  <a href="#atfirstpage">AtFirstPage</a> <a href="#atlastpage">AtLastPage</a> \r
-  <a href="#absolutepage">AbsolutePage</a> </font> <font size="2"><br>\r
-  Menu generation:<a href="#getmenu">GetMenu</a> <a href="#getmenu2">GetMenu2</a><br>\r
-  Dates:<a href="#userdate">UserDate</a> <a href="#usertimestamp">UserTimeStamp</a> \r
-  <a href="#unixdate">UnixDate</a> <a href="#unixtimestamp">UnixTimeStamp<br>\r
-  </a>Recordset Info:<a href="#recordcount">RecordCount</a> <a href="#po_recordcount">PO_RecordSet</a> \r
-  <a href="#nextrecordset">NextRecordSet</a><br>\r
-  Field Info:<a href="#fieldcount">FieldCount</a> <a href="#fetchfield">FetchField</a> \r
-  <a href="#metatype">MetaType</a><br>\r
-  Cleanup: <a href="#rsclose">Close</a></font> <font size="2"></font> \r
-<p><font size="2"><a href="#rs2html"><b>rs2html</b></a>&nbsp; <a href="#exrs2html">example</a></font><br>\r
-  <a href="#adodiff">Differences between ADOdb and ADO</a><br>\r
-  <a href="#driverguide"><b>Database Driver Guide<br>\r
-  </b></a><b><a href="#changes">Change Log</a></b><br>\r
-</p>\r
-<h2>Introduction<a name="intro"></a></h2>\r
-<p>PHP's database access functions are not standardised. This creates a need for \r
-  a database class library to hide the differences between the different database \r
-  API's (encapsulate the differences) so we can easily switch databases. PHP 4.0.5 or later\r
-  is now required (because we use array-based str_replace).</p>\r
-<p>We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, Informix, \r
-  PostgreSQL, FrontBase,  SQLite, Interbase (Firebird and Borland variants), Foxpro, Access, ADO, DB2, SAP DB and ODBC. \r
-  We have had successful reports of connecting to Progress and CacheLite via ODBC. We hope more people \r
-  will contribute drivers to support other databases.</p>\r
-<p>PHP4 supports session variables. You can store your session information using \r
-  ADOdb for true portability and scalability. See adodb-session.php for more information.</p>\r
-<p>Also read <a href="http://php.weblogs.com/portable_sql">http://php.weblogs.com/portable_sql</a> \r
-  (also available as tips_portable_sql.htm in the release) for tips on writing \r
-  portable SQL.</p>\r
-<h2>Unique Features of ADOdb<a name="features"></a></h2>\r
-<ul>\r
-  <li><b>Easy for Windows programmers</b> to adapt to because many of the conventions \r
-       are similar to Microsoft's ADO.</li>\r
-  <li>Unlike other PHP database classes which focus only on select statements, \r
-       <b>we provide support code to handle inserts and updates which can be adapted \r
-       to multiple databases quickly.</b> Methods are provided for date handling, \r
-       string concatenation and string quoting characters for differing databases.</li>\r
-  <li>A<b> metatype system </b>is built in so that we can figure out that types \r
-       such as CHAR, TEXT and STRING are equivalent in different databases.</li>\r
-  <li><b>Easy to port</b> because all the database dependant code are stored in \r
-       stub functions. You do not need to port the core logic of the classes.</li>\r
-  <li><b>Portable table and index creation</b> with the <a href=docs-datadict.htm>datadict</a> classes.\r
-  <li><b>Database performance monitoring and SQL tuning</b> with the <a href=docs-perf.htm>performance monitoring</a> classes.\r
-  <li><b>Database-backed sessions</b> with the <a href=docs-session.htm>session management</a> classes. Supports session expiry notification.\r
-</ul>\r
-<h2>How People are using ADOdb<a name="users"></a></h2>\r
-Here are some examples of how people are using ADOdb (for a much longer list, \r
-visit <a href="http://php.weblogs.com/adodb-cool-applications">http://php.weblogs.com/adodb-cool-applications</a>): \r
-<ul>\r
-<li><a href="http://phplens.com/">PhpLens</a> is a commercial data grid component that allows both cool Web designers and serious unshaved programmers to develop and maintain databases on the Web easily. Developed by the author of ADOdb.<p>\r
-\r
-<li><a href="http://www.interakt.ro/phakt/">PHAkt: PHP Extension for DreamWeaver Ultradev</a> allows you to script PHP in the popular Web page editor. Database handling provided by ADOdb.<p>\r
-\r
-<li><a href="http://www.andrew.cmu.edu/~rdanyliw/snort/snortacid.html">Analysis Console for Intrusion Databases</a> (ACID): PHP-based analysis engine to search and process a database of security incidents generated by security-related software such as IDSes and firewalls (e.g. Snort, ipchains). By Roman Danyliw.<p>\r
-\r
-<li><a href="http://www.postnuke.com/">PostNuke</a> is a very popular free content management\r
- system and weblog system. It offers full CSS support, HTML 4.01 transitional compliance throughout, an advanced blocks system, and is fully multi-lingual enabled. <p>\r
-\r
-<li><a href=http://www.auto-net.no/easypublish.php?page=index&lang_id=2>EasyPublish CMS</a>  is another free content management system for managing information and integrated modules on your internet, intranet- and extranet-sites. From Norway.<p>\r
-\r
-<li><a href="http://nola.noguska.com/">NOLA</a> is a full featured accounting, inventory, and job tracking application. It is licensed under the GPL, and developed by Noguska.\r
-</ul><p>\r
-\r
-<h2>Feature Requests and Bug Reports<a name="bugs"></a></h2>\r
-<p>Feature requests and bug reports can be emailed to <a href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a> \r
-  or posted to the ADOdb Help forums at <a href="http://phplens.com/lens/lensforum/topics.php?id=4">http://phplens.com/lens/lensforum/topics.php?id=4</a>.</p>\r
-<h2>Installation Guide<a name="install"></a></h2>\r
-<p>Make sure you are running PHP 4.0.4 or later. \r
-  Unpack all the files into a directory accessible by your webserver.</p>\r
-<p>To test, try modifying some of the tutorial examples. Make sure you customize \r
-  the connection settings correctly. You can debug using <i>$db->debug = true</i> as shown below:</p>\r
-<pre>&lt;?php\r
-       include('adodb/adodb.inc.php');\r
-       $db = <a href="#adonewconnection">ADONewConnection</a>($dbdriver); # eg 'mysql' or 'postgres'\r
-       $db->debug = true;\r
-       $db-><a href="#connect">Connect</a>($server, $user, $password, $database);\r
-       $rs = $db-><a href="#execute">Execute</a>('select * from some_small_table');\r
-       print &quot;&lt;pre&gt;&quot;;\r
-       print_r($rs-><a href="#getrows">GetRows</a>());\r
-       print &quot;&lt;/pre&gt;&quot;;\r
-?&gt;</pre>\r
-\r
- <h3>Minimum Install<a name=mininstall></a></h3>\r
-<p>For developers who want to release a minimal install of ADOdb, you will need:\r
-<ul>\r
-<li>adodb.inc.php\r
-<li>adodb-lib.inc.php\r
-<li>adodb-time.inc.php\r
-<li>adodb-csvlib.inc.php (if you use cached recordsets - CacheExecute(), etc)\r
-<li>adodb-error.inc.php and lang/adodb-$lang.inc.php (if you use MetaError())\r
-<li>drivers/adodb-$database.inc.php\r
-<li>license.txt (for legal reasons)\r
-</ul>\r
-\r
-<h3>Code Initialization Examples<a name="coding"></a></h3>\r
-<p>When running ADOdb, at least two files are loaded. First is adodb/adodb.inc.php, \r
- which contains all functions used by all database classes. The code specific \r
- to a particular database is in the adodb/driver/adodb-????.inc.php file.</p>\r
- <a name="adonewconnection">\r
-<p>For example, to connect to a mysql database:</p>\r
-<pre>\r
-include('/path/to/set/here/adodb.inc.php');\r
-$conn = &amp;ADONewConnection('mysql');\r
-</pre>\r
-<p>Whenever you need to connect to a database, you create a Connection object \r
-  using the <b>ADONewConnection</b></a>($driver) function. \r
-  <b>NewADOConnection</b>($driver) is an alternative name for the same function.</p>\r
-\r
-<p>At this point, you are not connected to the database. You will first need to decide\r
-whether to use <i>persistent</i> or <i>non-persistent</i> connections. The advantage of <i>persistent</i>\r
-connections is that they are faster, as the database connection is never closed (even \r
-when you call Close()). <i>Non-persistent </i>connections take up much fewer resources though,\r
-reducing the risk of your database and your web-server becoming overloaded. \r
-<p>For persistent connections,\r
-use $conn-&gt;<a href="reference.functions.pconnect.html">PConnect()</a>,\r
- or $conn-&gt;<a href="reference.functions.connect.html">Connect()</a> for non-persistent connections.\r
-Some database drivers also support <a href="reference.functions.nconnect.html">NConnect()</a>, which forces \r
-the creation of a new connection. \r
-<a name=connection_gotcha></a>\r
-<p><i>Connection Gotcha</i>:  If you create two connections, but both use the same userid and password,\r
-PHP will share the same connection. This can cause problems if the connections are meant to \r
-different databases. The solution is to always use different userid's for different databases,\r
- or use NConnect().\r
-\r
-<h3>Examples of Connecting to Databases</h3>\r
-<h4>MySQL and Most Other Database Drivers</h4>\r
-<p>MySQL connections are very straightforward, and the parameters are identical \r
-  to mysql_connect:</p>\r
-<pre>\r
-       $conn = &amp;ADONewConnection('mysql'); \r
-       $conn-&gt;PConnect('localhost','userid','password','database');\r
- </pre>\r
-<p> Most other database drivers use a similar convention: Connect($server, $user, $password, $database). Exceptions are listed below.\r
-<h4>PostgreSQL</h4>\r
-<p>PostgreSQL accepts connections using: </p>\r
-<p>a. the standard connection string:</p>\r
-<pre>\r
-       $conn = &amp;ADONewConnection('postgres7'); \r
-       $conn-&gt;PConnect('host=localhost port=5432 dbname=mary');</pre>\r
-<p> b. the classical 4 parameters:</p>\r
- <pre>\r
-       $conn-&gt;PConnect('localhost','userid','password','database');\r
- </pre>\r
-<h4>Interbase/Firebird</h4>\r
-You define the database in the $host parameter:\r
-<pre>\r
-       $conn = &ADONewConnection('ibase'); \r
-       $conn->PConnect('localhost:c:\ibase\employee.gdb','sysdba','masterkey');\r
-</pre>\r
-<h4>SQLite</h4>\r
-Sqlite will create database if it does not exist.\r
-<pre>\r
-       $conn = &ADONewConnection('sqlite'); \r
-       $conn->PConnect('c:\path\to\sqlite.db'); # sqlite will create if does not exist\r
-</pre>\r
-<h4>Oracle</h4>\r
-<p>With Oracle, you can connect in multiple ways.</p>\r
-<p>a. PHP and Oracle reside on the same machine, use default SID.</p>\r
-<pre>  $conn-&gt;Connect(false, 'scott', 'tiger');</pre>\r
-<p>b. TNS Name defined, eg. 'myTNS'</p>\r
-<pre>  $conn-&gt;PConnect(false, 'scott', 'tiger', 'myTNS');\r
-</pre>\r
-<p>or</p>\r
-<pre>  $conn-&gt;PConnect('myTNS', 'scott', 'tiger');</pre>\r
-<p>c. Host Address and SID</p>\r
-<pre>  $conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'SID');</pre>\r
-<p>d. Host Address and Service Name</p>\r
-<pre>  $conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'servicename');</pre>\r
-<a name=dsnless></a>\r
-<h4>DSN-less ODBC (access and mssql examples)</h4>\r
-<p>ODBC DSN's can be created in the ODBC control panel, or you can use a DSN-less \r
-  connection.To use DSN-less connections with ODBC you need PHP 4.3 or later. \r
-</p>\r
-<p>For Microsoft Access:</a></p>\r
-<pre>\r
-       $db =& ADONewConnection('access');\r
-       $dsn = <strong>"Driver=&#123;Microsoft Access Driver (*.mdb)&#125;;Dbq=d:\\northwind.mdb;Uid=Admin;Pwd=;";</strong>\r
-       $db->Connect($dsn);\r
-</pre>\r
-For Microsoft SQL Server: \r
-<pre>\r
-       $db =& ADONewConnection('odbc_mssql');\r
-       $dsn = <strong>"Driver=&#123;SQL Server&#125;;Server=localhost;Database=northwind;"</strong>;\r
-       $db->Connect($dsn,'userid','password');\r
-</pre>\r
-<b>DSN-less Connections with ADO</b><br>\r
-If you are using versions of PHP earlier than PHP 4.3.0, DSN-less connections \r
-only work with Microsoft's ADO, which is Microsoft's COM based API. An example \r
-using the ADOdb library and Microsoft's ADO: \r
-<pre>\r
-&lt;?php\r
-       include('adodb.inc.php'); \r
-       $db = &ADONewConnection("ado_mssql");\r
-       print "&lt;h1>Connecting DSN-less $db->databaseType...&lt;/h1>";\r
-               \r
-       <b>$myDSN="PROVIDER=MSDASQL;DRIVER=&#123;SQL Server&#125;;"\r
-               . "SERVER=flipper;DATABASE=ai;UID=sa;PWD=;"  ;</b>\r
-       $db->Connect($myDSN);\r
-       \r
-       $rs = $db->Execute("select * from table");\r
-       $arr = $rs->GetArray();\r
-       print_r($arr);\r
-?>\r
-</pre><a name=speed></a>\r
-<h2>High Speed ADOdb - tuning tips</h2>\r
-<p>ADOdb is a big class library, yet it <a href=http://phplens.com/lens/adodb/>consistently beats</a> all other PHP class \r
-  libraries in performance. This is because it is designed in a layered fashion, \r
-  like an onion, with the fastest functions in the innermost layer. Stick to the \r
-  following functions for best performance:</p>\r
-<table width="40%" border="1" align="center">\r
-  <tr>\r
-    <td><div align="center"><b>Innermost Layer</b></div></td>\r
-  </tr>\r
-  <tr> \r
-    <td><p align="center">Connect, PConnect, NConnect<br>\r
-        Execute, CacheExecute<br>\r
-        SelectLimit, SelectLimit<br>\r
-        MoveNext, Close <br>\r
-               qstr, Affected_Rows, Insert_ID</p></td>\r
-  </tr>\r
-</table>\r
-<p>The fastest way to access the fields is by accessing the array $recordset->fields \r
-  directly. Also set the global variables <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a> \r
-  = ADODB_FETCH_NUM, and (for oci8, ibase/firebird and odbc) <a href="#adodb_countrecs">$ADODB_COUNTRECS</a> = false \r
-  before you connect to your database. At the time of writing (Dec 2003).</p>\r
-<p>Consider using bind parameters if your database supports it, as it improves \r
-  query plan reuse. Use ADOdb's performance tuning system to identify bottlenecks \r
-  quickly. At the time of writing (Dec 2003), this means oci8 and odbc drivers.</p>\r
-<p>Lastly make sure you have a PHP accelerator cache installed such as APC, Turck \r
-  MMCache, Zend Accelerator or ionCube.</p>\r
- <p>Informix tips: Disable scrollable cursors with $db->cursorType = 0.\r
-<p><a name=hack></a> </p>\r
-<h2>Hacking ADOdb Safely</h2>\r
-<p>You might want to modify ADOdb for your own purposes. Luckily you can\r
-still maintain backward compatibility by sub-classing ADOdb and using the $ADODB_NEWCONNECTION\r
-variable. $ADODB_NEWCONNECTION allows you to override the behaviour of ADONewConnection().\r
-ADOConnection() checks for this variable and will call\r
-the function-name stored in this variable if it is defined.\r
-<p>In the following example, new functionality for the connection object \r
-is placed in the <i>hack_mysql</i> and <i>hack_postgres7</i> classes. The recordset class naming convention\r
-can be controlled using $rsPrefix. Here we set it to 'hack_rs_', which will make ADOdb use\r
-<i>hack_rs_mysql</i> and <i>hack_rs_postgres7</i> as the recordset classes.\r
-If you want to use the default ADOdb drivers return false.\r
-\r
-<pre>\r
-class hack_mysql extends adodb_mysql {\r
-var $rsPrefix = 'hack_rs_';\r
-  /* Your mods here */\r
-}\r
-\r
-class hack_rs_mysql extends ADORecordSet_mysql {\r
- /* Your mods here */\r
-}\r
-\r
-class hack_postgres7 extends adodb_postgres7 {\r
-var $rsPrefix = 'hack_rs_';\r
-  /* Your mods here */\r
-}\r
-\r
-class hack_rs_postgres7 extends ADORecordSet_postgres7 {\r
- /* Your mods here */\r
-}\r
-\r
-$ADODB_NEWCONNECTION = 'hack_factory';\r
-\r
-function& hack_factory($driver)\r
-{\r
-       if ($driver !== 'mysql' && $driver !== 'postgres7') return false;\r
-       \r
-       $driver = 'hack_'.$driver;\r
-       $obj = new $driver();\r
-       return $obj;\r
-}\r
-\r
-include_once('adodb.inc.php');\r
-\r
-</pre>\r
-<p>Don't forget to call the constructor of the parent class.\r
-<a name="php5">\r
-<h2>PHP5 Features</h2>\r
- ADOdb 4.02 or later will transparently determine which version of PHP you are using.\r
-If PHP5 is detected, the following features become available:\r
-<ul>\r
-<a name="php5iterators">\r
-<li><b>Foreach iterators</b>: This is a very natural way of going through a recordset:\r
-<pre>\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-       $rs = $db->Execute($sql);\r
-       foreach($rs as $k => $row) {\r
-               echo "r1=".$row[0]." r2=".$row[1]."&lt;br>";\r
-       }\r
-</pre>\r
-<p>\r
-<a name="php5exceptions">\r
-<li><b>Exceptions</b>: Just include <i>adodb-exceptions.inc.php</i> and you can now \r
-catch exceptions on errors as they occur.\r
-<pre>\r
-       <b>include("../adodb-exceptions.inc.php");</b> \r
-       include("../adodb.inc.php");     \r
-       try { \r
-               $db = NewADOConnection("oci8"); \r
-               $db->Connect('','scott','bad-password'); \r
-       } catch (exception $e) { \r
-               var_dump($e); \r
-       } \r
-</pre>\r
-</ul> \r
-<h3><a name="drivers"></a>Databases Supported</h3>\r
-<table width="100%" border="1">\r
-  <tr valign="top"> \r
-    <td><b>Name</b></td>\r
-    <td><b>Tested</b></td>\r
-    <td><b>Database</b></td>\r
-    <td><b><font size="2">RecordCount() usable</font></b></td>\r
-    <td><b>Prerequisites</b></td>\r
-    <td><b>Operating Systems</b></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">access</font></b></td>\r
-    <td><font size="2">B</font></td>\r
-    <td><font size="2">Microsoft Access/Jet. You need to create an ODBC DSN.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">ODBC </font></td>\r
-    <td><font size="2">Windows only</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">ado</font></b></td>\r
-    <td><font size="2">B</font></td>\r
-    <td><p><font size="2">Generic ADO, not tuned for specific databases. Allows \r
-        DSN-less connections. For best performance, use an OLEDB provider. This \r
-        is the base class for all ado drivers.</font></p>\r
-      <p><font size="2">You can set $db-&gt;codePage before connecting.</font></p></td>\r
-    <td><font size="2">? depends on database</font></td>\r
-    <td><font size="2">ADO or OLEDB provider</font></td>\r
-    <td><font size="2">Windows only</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">ado_access</font></b></td>\r
-    <td><font size="2">B</font></td>\r
-    <td><font size="2">Microsoft Access/Jet using ADO. Allows DSN-less connections. \r
-      For best performance, use an OLEDB provider.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">ADO or OLEDB provider</font></td>\r
-    <td><font size="2">Windows only</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">ado_mssql</font></b></td>\r
-    <td><font size="2">B</font></td>\r
-    <td><font size="2">Microsoft SQL Server using ADO. Allows DSN-less connections. \r
-      For best performance, use an OLEDB provider.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">ADO or OLEDB provider</font></td>\r
-    <td><font size="2">Windows only</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td height="54"><b><font size="2">db2</font></b></td>\r
-    <td height="54"><font size="2">A</font></td>\r
-    <td height="54"><font size="2">DB2. Should work reliably as based on ODBC \r
-      driver.</font></td>\r
-    <td height="54"><font size="2">Y/N</font></td>\r
-    <td height="54"><font size="2">DB2 CLI/ODBC interface</font></td>\r
-    <td height="54"> <p><font size="2">Unix and Windows. <a href="http://www.faqts.com/knowledge_base/view.phtml/aid/6283/fid/14">Unix \r
-        install hints</a>.</font></p></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">vfp</font></b></td>\r
-    <td><font size="2">A</font></td>\r
-    <td><font size="2">Microsoft Visual FoxPro. You need to create an ODBC DSN.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">ODBC</font></td>\r
-    <td><font size="2">Windows only</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">fbsql</font></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2">FrontBase. </font></td>\r
-    <td><font size="2">Y</font></td>\r
-    <td><font size="2">?</font></td>\r
-    <td> <p><font size="2">Unix and Windows</font></p></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">ibase</font></b></td>\r
-    <td><font size="2">B</font></td>\r
-    <td><font size="2">Interbase 6 or earlier. Some users report you might need \r
-      to use this<br>\r
-      $db->PConnect('localhost:c:/ibase/employee.gdb', "sysdba", "masterkey") \r
-      to connect. Lacks Affected_Rows currently.<br>\r
-      <br>\r
-      You can set $db->dialect, $db-&gt;buffers and $db->charSet before connecting.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">Interbase client</font></td>\r
-    <td><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><i><font size="2">firebird</font></i></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2">Firebird version of interbase.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">Interbase client</font></td>\r
-    <td><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><i><font size="2">borland_ibase</font></i></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2">Borland version of Interbase 6.5 or later. Very sad that \r
-      the forks differ.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">Interbase client</font></td>\r
-    <td><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">informix72</font></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2"> Informix databases before Informix 7.3 that do no support \r
-      SELECT FIRST.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">Informix client</font></td>\r
-    <td><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">informix</font></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2">Generic informix driver.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">Informix client</font></td>\r
-    <td><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td height="73"><b><font size="2">mssql</font></b></td>\r
-    <td height="73"><font size="2">A</font></td>\r
-    <td height="73"> <p><font size="2">Microsoft SQL Server 7 and later. Works \r
-        with Microsoft SQL Server 2000 also. Note that date formating is problematic \r
-        with this driver. For example, the PHP mssql extension does not return \r
-        the seconds for datetime!</font></p></td>\r
-    <td height="73"><font size="2">Y/N</font></td>\r
-    <td height="73"><font size="2">Mssql client</font></td>\r
-    <td height="73"> <p><font size="2">Unix and Windows. <br>\r
-        <a href="http://phpbuilder.com/columns/alberto20000919.php3">Unix install \r
-        howto</a> and <a href=http://linuxjournal.com/article.php?sid=6636&mode=thread&order=0>another \r
-        one</a>. </font></p></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td height="73"><b><font size="2">mssqlpo</font></b></td>\r
-    <td height="73"><font size="2">A</font></td>\r
-    <td height="73"> <p><font size="2">Portable mssql driver. Identical to above \r
-        mssql driver, except that '||', the concatenation operator, is converted \r
-        to '+'. Useful for porting scripts from most other sql variants that use \r
-        ||.</font></p></td>\r
-    <td height="73"><font size="2">Y/N</font></td>\r
-    <td height="73"><font size="2">Mssql client</font></td>\r
-    <td height="73"> <p><font size="2">Unix and Windows. <a href="http://phpbuilder.com/columns/alberto20000919.php3"><br>\r
-        Unix install howto</a>.</font></p></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">mysql</font></b></td>\r
-    <td><font size="2">A</font></td>\r
-    <td><font size="2">MySQL without transaction support. You can also set $db-&gt;clientFlags \r
-      before connecting.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">MySQL client</font></td>\r
-    <td><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><font size="2"><b>mysqlt</b> or <b>maxsql</b></font></td>\r
-    <td><font size="2">A</font></td>\r
-    <td> <p><font size="2">MySQL with transaction support. We recommend using \r
-        || as the concat operator for best portability. This can be done by running \r
-        MySQL using: <br>\r
-        <i>mysqld --ansi</i> or <i>mysqld --sql-mode=PIPES_AS_CONCAT</i></font></p></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">MySQL client</font></td>\r
-    <td><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">oci8</font></b></td>\r
-    <td><font size="2">A</font></td>\r
-    <td><font size="2">Oracle 8/9. Has more functionality than <i>oracle</i> driver \r
-      (eg. Affected_Rows). You might have to putenv('ORACLE_HOME=...') before \r
-      Connect/PConnect. </font> <p><font size="2"> There are 2 ways of connecting \r
-        - with server IP and service name: <br>\r
-        <i>PConnect('serverip:1521','scott','tiger','service'</i>)<br>\r
-        or using an entry in TNSNAMES.ORA or ONAMES or HOSTNAMES: <br>\r
-        <i>PConnect(false, 'scott', 'tiger', $oraname)</i>. </font> \r
-      <p><font size="2">Since 2.31, we support Oracle REF cursor variables directly \r
-        (see <a href="#executecursor">ExecuteCursor</a>).</font> </td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">Oracle client</font></td>\r
-    <td><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">oci805</font></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2">Supports reduced Oracle functionality for Oracle 8.0.5. \r
-      SelectLimit is not as efficient as in the oci8 or oci8po drivers.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">Oracle client</font></td>\r
-    <td><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">oci8po</font></b></td>\r
-    <td><font size="2">A</font></td>\r
-    <td><font size="2">Oracle 8/9 portable driver. This is nearly identical with \r
-      the oci8 driver except (a) bind variables in Prepare() use the ? convention, \r
-      instead of :bindvar, (b) field names use the more common PHP convention \r
-      of lowercase names. </font> <p><font size="2">Use this driver if porting \r
-        from other databases is important. Otherwise the oci8 driver offers better \r
-        performance. </font> </td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">Oracle client</font></td>\r
-    <td><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">odbc</font></b></td>\r
-    <td><font size="2">A</font></td>\r
-    <td><font size="2">Generic ODBC, not tuned for specific databases. To connect, \r
-      use <br>\r
-      PConnect('DSN','user','pwd'). This is the base class for all odbc derived \r
-      drivers.</font></td>\r
-    <td><font size="2">? depends on database</font></td>\r
-    <td><font size="2">ODBC</font></td>\r
-    <td><font size="2">Unix and Windows. <a href="http://phpbuilder.com/columns/alberto20000919.php3?page=4">Unix \r
-      hints.</a></font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">odbc_mssql</font></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2">Uses ODBC to connect to MSSQL</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">ODBC</font></td>\r
-    <td><font size="2">Unix and Windows. </font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">odbc_oracle</font></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2">Uses ODBC to connect to Oracle</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">ODBC</font></td>\r
-    <td><font size="2">Unix and Windows. </font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td height="34"><b><font size="2">oracle</font></b></td>\r
-    <td height="34"><font size="2">C</font></td>\r
-    <td height="34"><font size="2">Implements old Oracle 7 client API. Use oci8 \r
-      driver if possible for better performance.</font></td>\r
-    <td height="34"><font size="2">Y/N</font></td>\r
-    <td height="34"><font size="2">Oracle client</font></td>\r
-    <td height="34"><font size="2">Unix and Windows</font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">postgres</font></b></td>\r
-    <td><font size="2">A</font></td>\r
-    <td><font size="2">Generic PostgreSQL driver. Currently identical to postgres7 \r
-      driver. </font></td>\r
-    <td><font size="2">Y</font></td>\r
-    <td><font size="2">PostgreSQL client</font></td>\r
-    <td><font size="2">Unix and Windows. </font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">postgres64</font></b></td>\r
-    <td><font size="2">A</font></td>\r
-    <td><font size="2">For PostgreSQL 6.4 and earlier which does not support LIMIT \r
-      internally.</font></td>\r
-    <td><font size="2">Y</font></td>\r
-    <td><font size="2">PostgreSQL client</font></td>\r
-    <td><font size="2">Unix and Windows. </font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">postgres7</font></b></td>\r
-    <td><font size="2">A</font></td>\r
-    <td><font size="2">PostgreSQL which supports LIMIT and other version 7 functionality.</font></td>\r
-    <td><font size="2">Y</font></td>\r
-    <td><font size="2">PostgreSQL client</font></td>\r
-    <td><font size="2">Unix and Windows. </font></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">sapdb</font></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2">SAP DB. Should work reliably as based on ODBC driver.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">SAP ODBC client</font></td>\r
-    <td> <p><font size="2">?</font></p></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">sqlanywhere</font></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2">Sybase SQL Anywhere. Should work reliably as based on ODBC \r
-      driver.</font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">SQL Anywhere ODBC client</font></td>\r
-    <td> <p><font size="2">?</font></p></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td height="54"><b><font size="2">sqlite</font></b></td>\r
-    <td height="54"><font size="2">B</font></td>\r
-    <td height="54"><font size="2">SQLite. Only tested on PHP5.</font></td>\r
-    <td height="54"><font size="2">Y</font></td>\r
-    <td height="54"><font size="2">-</font></td>\r
-    <td height="54"> <p><font size="2">Unix and Windows.</font></p></td>\r
-  </tr>\r
-  <tr valign="top"> \r
-    <td><b><font size="2">sybase</font></b></td>\r
-    <td><font size="2">C</font></td>\r
-    <td><font size="2">Sybase. </font></td>\r
-    <td><font size="2">Y/N</font></td>\r
-    <td><font size="2">Sybase client</font></td>\r
-    <td> <p><font size="2">Unix and Windows.</font></p></td>\r
-  </tr>\r
-  <p> \r
-</table>\r
-\r
-<p>The &quot;Tested&quot; column indicates how extensively the code has been tested \r
-  and used. <br>\r
-  A = well tested and used by many people<br>\r
-  B = tested and usable, but some features might not be implemented<br>\r
-  C = user contributed or experimental driver. Might not fully support all of \r
-  the latest features of ADOdb. </p>\r
-<p>The column &quot;RecordCount() usable&quot; indicates whether RecordCount() \r
-  return the number of rows, or returns -1 when a SELECT statement is executed. \r
-  If this column displays Y/N then the RecordCount() is emulated when the global \r
-  variable $ADODB_COUNTRECS=true (this is the default). Note that for large recordsets, \r
-  it might be better to disable RecordCount() emulation because substantial amounts \r
-  of memory are required to cache the recordset for counting. Also there is a \r
-  speed penalty of 40-50% if emulation is required. This is emulated in most databases \r
-  except for PostgreSQL and MySQL. This variable is checked every time a query \r
-  is executed, so you can selectively choose which recordsets to count.</p>\r
-<p> \r
-<hr>\r
-<h1>Tutorials<a name="quickstart"></a></h1>\r
-<h3>Example 1: Select Statement<a name="ex1"></a></h3>\r
-<p>Task: Connect to the Access Northwind DSN, display the first 2 columns of each \r
-  row.</p>\r
-<p>In this example, we create a ADOConnection object, which represents the connection \r
-  to the database. The connection is initiated with <a href="#pconnect"><font face="Courier New, Courier, mono">PConnect</font></a>, \r
-  which is a persistent connection. Whenever we want to query the database, we \r
-  call the <font face="Courier New, Courier, mono">ADOConnection.<a href="#execute">Execute</a>()</font> \r
-  function. This returns an ADORecordSet object which is actually a cursor that \r
-  holds the current row in the array <font face="Courier New, Courier, mono">fields[]</font>. \r
-  We use <font face="Courier New, Courier, mono"><a href="#movenext">MoveNext</a>()</font> \r
-  to move from row to row.</p>\r
-<p>NB: A useful function that is not used in this example is <font face="Courier New, Courier, mono"><a href="#selectlimit">SelectLimit</a></font>, \r
-  which allows us to limit the number of rows shown. \r
-<pre>\r
-&lt;?\r
-<font face="Courier New, Courier, mono"><b>include</b>('adodb.inc.php');          # load code common to ADOdb\r
-$<font color="#660000">conn</font> = &amp;ADONewConnection('access');  # create a connection\r
-$<font color="#660000">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind DSN\r
-$<font color="#660000">recordSet</font> = &amp;$<font color="#660000">conn</font>->Execute('select * from products');\r
-if (!$<font color="#660000">recordSet</font>) \r
-       print $<font color="#660000">conn</font>-&gt;ErrorMsg();\r
-else\r
-<b>while</b> (!$<font color="#660000">recordSet</font>-&gt;EOF) &#123;\r
-       <b>print</b> $<font color="#660000">recordSet</font>->fields[0].' '.$<font color="#660000">recordSet</font>->fields[1].'&lt;BR&gt;';\r
-       $<font color="#660000">recordSet</font>-&gt;MoveNext();\r
-&#125;</font><font face="Courier New, Courier, mono">\r
-\r
-$<font color="#660000">recordSet</font>->Close(); # optional\r
-$<font color="#660000">conn</font>->Close(); # optional\r
-</font>\r
-?>\r
-</pre>\r
-<p>The $<font face="Courier New, Courier, mono">recordSet</font> returned stores \r
-  the current row in the <font face="Courier New, Courier, mono">$recordSet-&gt;fields</font> \r
-  array, indexed by column number (starting from zero). We use the <font face="Courier New, Courier, mono"><a href="#movenext">MoveNext</a>()</font> \r
-  function to move to the next row. The <font face="Courier New, Courier, mono">EOF</font> \r
-  property is set to true when end-of-file is reached. If an error occurs in Execute(), \r
-  we return false instead of a recordset.</p>\r
-<p>The <code>$recordSet-&gt;fields[]</code> array is generated by the PHP database \r
-  extension. Some database extensions only index by number and do not index the \r
-  array by field name. To force indexing by name - that is associative arrays \r
-  - use the SetFetchMode function. Each recordset saves and uses whatever fetch \r
-  mode was set when the recordset was created in Execute() or SelectLimit(). \r
-<pre>\r
-       $db->SetFetchMode(ADODB_FETCH_NUM);\r
-       $rs1 = $db->Execute('select * from table');\r
-       $db->SetFetchMode(ADODB_FETCH_ASSOC);\r
-       $rs2 = $db->Execute('select * from table');\r
-       print_r($rs1->fields); # shows <i>array([0]=>'v0',[1] =>'v1')</i>\r
-       print_r($rs2->fields); # shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i>\r
-</pre>\r
-<p> </p>\r
-<p>To get the number of rows in the select statement, you can use <font face="Courier New, Courier, mono">$recordSet-&gt;<a href="#recordcount">RecordCount</a>()</font>. \r
-  Note that it can return -1 if the number of rows returned cannot be determined.</p>\r
-<h3>Example 2: Advanced Select with Field Objects<a name="ex2"></a></h3>\r
-<p>Select a table, display the first two columns. If the second column is a date \r
-  or timestamp, reformat the date to US format.</p>\r
-<pre>\r
-&lt;?\r
-<font face="Courier New, Courier, mono"><b>include</b>('adodb.inc.php');          # load code common to ADOdb\r
-$<font color="#660000">conn</font> = &amp;ADONewConnection('access');  # create a connection\r
-$<font color="#660000">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind dsn\r
-$<font color="#660000">recordSet</font> = &amp;$<font color="#660000">conn</font>->Execute('select CustomerID,OrderDate from Orders');\r
-if (!$<font color="#660000">recordSet</font>) \r
-       print $<font color="#660000">conn</font>-&gt;ErrorMsg();\r
-else\r
-<b>while</b> (!$<font color="#660000">recordSet</font>-&gt;EOF) &#123;\r
-       $<font color="#660000">fld</font> = <font color="#336600"><b>$</b><font color="#660000">recordSet</font><b>-&gt;FetchField</b></font><font color="#006600">(</font>1<font color="#006600">);</font>\r
-       $<font color="#660000">type</font> = <font color="#336600"><b>$</b><font color="#660000">recordSet</font><b>-&gt;MetaType</b></font>($fld-&gt;type);\r
-\r
-       <b>if</b> ( $<font color="#660000">type</font> == 'D' || $<font color="#660000">type</font> == 'T') \r
-               <b>print</b> $<font color="#660000">recordSet</font>-&gt;fields[0].' '.\r
-                       <b><font color="#336600">$</font></b><font color="#660000">recordSet</font><b><font color="#336600">-&gt;UserDate</font></b>($<font color="#660000">recordSet</font>-&gt;fields[1],'<b>m/d/Y</b>').'&lt;BR&gt;';\r
-       <b>else </b>\r
-               <b>print</b> $<font color="#660000">recordSet</font>->fields[0].' '.$<font color="#660000">recordSet</font>->fields[1].'&lt;BR&gt;';\r
-\r
-       $<font color="#660000">recordSet</font>-&gt;MoveNext();\r
-&#125;</font><font face="Courier New, Courier, mono">\r
-$<font color="#660000">recordSet</font>->Close(); # optional\r
-$<font color="#660000">conn</font>->Close(); # optional\r
-</font>\r
-?>\r
-</pre>\r
-<p>In this example, we check the field type of the second column using <font face="Courier New, Courier, mono"><a href="#fetchfield">FetchField</a>().</font> \r
-  This returns an object with at least 3 fields.</p>\r
-<ul>\r
-  <li><b>name</b>: name of column</li>\r
-  <li> <b>type</b>: native field type of column</li>\r
-  <li> <b>max_length</b>: maximum length of field. Some databases such as MySQL \r
-    do not return the maximum length of the field correctly. In these cases max_length \r
-    will be set to -1.</li>\r
-</ul>\r
-<p>We then use <font face="Courier New, Courier, mono"><a href="#metatype">MetaType</a>()</font> \r
-  to translate the native type to a <i>generic</i> type. Currently the following \r
-  <i>generic</i> types are defined:</p>\r
-<ul>\r
-  <li><b>C</b>: character fields that should be shown in a &lt;input type=&quot;text&quot;&gt; \r
-    tag.</li>\r
-  <li><b>X</b>: TeXt, large text fields that should be shown in a &lt;textarea&gt;</li>\r
-  <li><b>B</b>: Blobs, or Binary Large Objects. Typically images. \r
-  <li><b>D</b>: Date field</li>\r
-  <li><b>T</b>: Timestamp field</li>\r
-  <li><b>L</b>: Logical field (boolean or bit-field)</li>\r
-  <li><b>I</b>:&nbsp; Integer field</li>\r
-  <li><b>N</b>: Numeric field. Includes autoincrement, numeric, floating point, \r
-    real and integer. </li>\r
-  <li><b>R</b>: Serial field. Includes serial, autoincrement integers. This works \r
-    for selected databases. </li>\r
-</ul>\r
-<p>If the metatype is of type date or timestamp, then we print it using the user \r
-  defined date format with <font face="Courier New, Courier, mono"><a href="#userdate">UserDate</a>(),</font> \r
-  which converts the PHP SQL date string format to a user defined one. Another \r
-  use for <font face="Courier New, Courier, mono"><a href="#metatype">MetaType</a>()</font> \r
-  is data validation before doing an SQL insert or update.</p>\r
-<h3>Example 3: Inserting<a name="ex3"></a></h3>\r
-<p>Insert a row to the Orders table containing dates and strings that need to \r
-  be quoted before they can be accepted by the database, eg: the single-quote \r
-  in the word <i>John's</i>.</p>\r
-<pre>\r
-&lt;?\r
-<b>include</b>('adodb.inc.php');          # load code common to ADOdb\r
-$<font color="#660000">conn</font> = &amp;ADONewConnection('access');  # create a connection\r
-\r
-$<font color="#660000">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind dsn\r
-$<font color="#660000">shipto</font> = <font color="#006600"><b>$conn-&gt;qstr</b></font>(&quot;<i>John's Old Shoppe</i>&quot;);\r
-\r
-$<font color="#660000">sql</font> = &quot;insert into orders (customerID,EmployeeID,OrderDate,ShipName) &quot;;\r
-$<font color="#660000">sql</font> .= &quot;values ('ANATR',2,&quot;.<b><font color="#006600">$conn-&gt;DBDate(</font>time()<font color="#006600">)</font></b><font color="#006600">.</font>&quot;,$<font color="#660000">shipto</font>)&quot;;\r
-\r
-<b>if</b> ($<font color="#660000">conn</font>->Execute($<font color="#660000">sql</font>) <font color="#336600"><b>=== false</b></font>) &#123;\r
-       <b>print</b> 'error inserting: '.<font color="#336600"><b>$conn-&gt;ErrorMsg()</b></font>.'&lt;BR&gt;';\r
-&#125;\r
-?>\r
-</pre>\r
-<p>In this example, we see the advanced date and quote handling facilities of \r
-  ADOdb. The unix timestamp (which is a long integer) is appropriately formated \r
-  for Access with <font face="Courier New, Courier, mono"><a href="#dbdate">DBDate</a>()</font>, \r
-  and the right escape character is used for quoting the <i>John's Old Shoppe</i>, \r
-  which is<b> </b><i>John'<b>'</b>s Old Shoppe</i> and not PHP's default <i>John<b>'</b>s \r
-  Old Shoppe</i> with <font face="Courier New, Courier, mono"><a href="#qstr">qstr</a>()</font>. \r
-</p>\r
-<p>Observe the error-handling of the Execute statement. False is returned by<font face="Courier New, Courier, mono"> \r
-  <a href="#execute">Execute</a>() </font>if an error occured. The error message \r
-  for the last error that occurred is displayed in <font face="Courier New, Courier, mono"><a href="#errormsg">ErrorMsg</a>()</font>. \r
-  Note: <i>php_track_errors</i> might have to be enabled for error messages to \r
-  be saved.</p>\r
-<h3> Example 4: Debugging<a name="ex4"></a></h3>\r
-<pre>&lt;?\r
-<b>include</b>('adodb.inc.php');          # load code common to ADOdb\r
-$<font color="#663300">conn</font> = &amp;ADONewConnection('access');  # create a connection\r
-$<font color="#663300">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind dsn\r
-<font color="#000000">$<font color="#663300">shipto</font> = <b>$conn-&gt;qstr</b>(&quot;John's Old Shoppe&quot;);\r
-$<font color="#663300">sql</font> = &quot;insert into orders (customerID,EmployeeID,OrderDate,ShipName) &quot;;\r
-$<font color="#663300">sql</font> .= &quot;values ('ANATR',2,&quot;.$<font color="#663300">conn</font>-&gt;FormatDate(time()).&quot;,$shipto)&quot;;\r
-<b><font color="#336600">$<font color="#663300">conn</font>-&gt;debug = true;</font></b>\r
-<b>if</b> ($<font color="#663300">conn</font>->Execute($sql) <b>=== false</b>) <b>print</b> 'error inserting';</font>\r
-?&gt;\r
-</pre>\r
-<p>In the above example, we have turned on debugging by setting <b>debug = true</b>. \r
-  This will display the SQL statement before execution, and also show any error \r
-  messages. There is no need to call <font face="Courier New, Courier, mono"><a href="#errormsg">ErrorMsg</a>()</font> \r
-  in this case. For displaying the recordset, see the <font face="Courier New, Courier, mono"><a href="#exrs2html">rs2html</a>() \r
-  </font>example.</p>\r
-<p>Also see the section on <a href=#errorhandling>Custom Error Handlers</a>.</p>\r
-<h3>Example 5: MySQL and Menus<a name="ex5"></a></h3>\r
-<p>Connect to MySQL database <i>agora</i>, and generate a &lt;select&gt; menu \r
-  from an SQL statement where the &lt;option&gt; captions are in the 1st column, \r
-  and the value to send back to the server is in the 2nd column.</p>\r
-<pre>&lt;?\r
-<b>include</b>('adodb.inc.php'); # load code common to ADOdb\r
-$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');  # create a connection\r
-$<font color="#663300">conn</font>->PConnect('localhost','userid','','agora');# connect to MySQL, agora db\r
-<font color="#000000">$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers';\r
-$<font color="#663300">rs</font> = $<font color="#663300">conn</font>->Execute($sql);\r
-<b>print</b> <b><font color="#336600">$<font color="#663300">rs</font>-&gt;GetMenu('GetCust','Mary Rosli');\r
-?&gt;</font></b></font></pre>\r
-<p>Here we define a menu named GetCust, with the menu option 'Mary Rosli' selected. \r
-  See <a href="#getmenu"><font face="Courier New, Courier, mono">GetMenu</font></a><font face="Courier New, Courier, mono">()</font>. \r
-  We also have functions that return the recordset as an array: <font face="Courier New, Courier, mono"><a href="#getarray">GetArray</a>()</font>, \r
-  and as an associative array with the key being the first column: <a href="#getassoc1">GetAssoc</a>().</p>\r
-<h3>Example 6: Connecting to 2 Databases At Once<a name="ex6"></a></h3>\r
-<pre>&lt;?\r
-<b>include</b>('adodb.inc.php');        # load code common to ADOdb\r
-$<font color="#663300">conn1</font> = &amp;ADONewConnection('mysql');  # create a mysql connection\r
-$<font color="#663300">conn2</font> = &amp;ADONewConnection('oracle');  # create a oracle connection\r
-\r
-$conn1-&gt;PConnect($server, $userid, $password, $database);\r
-$conn2-&gt;PConnect(false, $ora_userid, $ora_pwd, $oraname);\r
-\r
-$conn1-&gt;Execute('insert ...');\r
-$conn2-&gt;Execute('update ...');\r
-?&gt;</pre>\r
-<p> \r
-<h3>Example 7: Generating Update and Insert SQL<a name="ex7"></a></h3>\r
-ADOdb 1.31 and later supports two new recordset functions: GetUpdateSQL( ) and \r
-GetInsertSQL( ). This allow you to perform a "SELECT * FROM table query WHERE...", \r
-make a copy of the $rs->fields, modify the fields, and then generate the SQL to \r
-update or insert into the table automatically. \r
-<p> We show how the functions can be used when accessing a table with the following \r
-  fields: (ID, FirstName, LastName, Created). \r
-<p> Before these functions can be called, you need to initialize the recordset \r
-  by performing a select on the table. Idea and code by Jonathan Younger jyounger#unilab.com. \r
-<p> \r
-<pre>&lt;?\r
-#==============================================\r
-# SAMPLE GetUpdateSQL() and GetInsertSQL() code\r
-#==============================================\r
-include('adodb.inc.php');\r
-include('tohtml.inc.php');\r
-\r
-#==========================\r
-# This code tests an insert\r
-\r
-$sql = "SELECT * FROM ADOXYZ WHERE id = -1"; \r
-# Select an empty record from the database\r
-\r
-$conn = &ADONewConnection("mysql");  # create a connection\r
-$conn->debug=1;\r
-$conn->PConnect("localhost", "admin", "", "test"); # connect to MySQL, testdb\r
-$rs = $conn->Execute($sql); # Execute the query and get the empty recordset\r
-\r
-$record = array(); # Initialize an array to hold the record data to insert\r
-\r
-# Set the values for the fields in the record\r
-# Note that field names are case-insensitive\r
-$record["firstname"] = "Bob";\r
-$record["lastNamE"] = "Smith";\r
-$record["creaTed"] = time();\r
-\r
-# Pass the empty recordset and the array containing the data to insert\r
-# into the GetInsertSQL function. The function will process the data and return\r
-# a fully formatted insert sql statement.\r
-$insertSQL = $conn->GetInsertSQL($rs, $record);\r
-\r
-$conn->Execute($insertSQL); # Insert the record into the database\r
-\r
-#==========================\r
-# This code tests an update\r
-\r
-$sql = "SELECT * FROM ADOXYZ WHERE id = 1"; \r
-# Select a record to update\r
-\r
-$rs = $conn->Execute($sql); # Execute the query and get the existing record to update\r
-\r
-$record = array(); # Initialize an array to hold the record data to update\r
-\r
-# Set the values for the fields in the record\r
-# Note that field names are case-insensitive\r
-$record["firstname"] = "Caroline";\r
-$record["LasTnAme"] = "Smith"; # Update Caroline's lastname from Miranda to Smith\r
-\r
-# Pass the single record recordset and the array containing the data to update\r
-# into the GetUpdateSQL function. The function will process the data and return\r
-# a fully formatted update sql statement with the correct WHERE clause.\r
-# If the data has not changed, no recordset is returned\r
-$updateSQL = $conn->GetUpdateSQL($rs, $record);\r
-\r
-$conn->Execute($updateSQL); # Update the record in the database\r
-$conn->Close();\r
-?>\r
-</pre>\r
-<h3>Example 8: Implementing Scrolling with Next and Previous<a name="ex8"></a></h3>\r
-<p> The following code creates a very simple recordset pager, where you can scroll \r
-  from page to page of a recordset.</p>\r
-<pre>\r
-include_once('../adodb.inc.php');\r
-include_once('../adodb-pager.inc.php');\r
-session_start();\r
-\r
-$db = NewADOConnection('mysql');\r
-\r
-$db->Connect('localhost','root','','xphplens');\r
-\r
-$sql = "select * from adoxyz ";\r
-\r
-$pager = new ADODB_Pager($db,$sql);\r
-$pager->Render($rows_per_page=5);</pre>\r
-<p>This will create a basic record pager that looks like this: <a name="scr"></a> \r
-<p> \r
-<table border=1 bgcolor=beige>\r
-  <tr> \r
-    <td> <a href="#scr"><code>|&lt;</code></a> &nbsp; <a href="#scr"><code>&lt;&lt;</code></a> \r
-      &nbsp; <a href="#scr"><code>>></code></a> &nbsp; <a href="#scr"><code>>|</code></a> \r
-      &nbsp; </td>\r
-  </tr>\r
-  <tr>\r
-    <td><TABLE COLS=4 width=100% border=1 bgcolor=white>\r
-        <TH>ID</TH>\r
-        <TH>First Name</TH>\r
-        <TH>Last Name</TH>\r
-        <TH>Date Created</TH>\r
-        <TR> \r
-          <TD align=right>36&nbsp;</TD>\r
-          <TD>Alan&nbsp;</TD>\r
-          <TD>Turing&nbsp;</TD>\r
-          <TD>Sat 06, Oct 2001&nbsp;</TD>\r
-        </TR>\r
-        <TR> \r
-          <TD align=right>37&nbsp;</TD>\r
-          <TD>Serena&nbsp;</TD>\r
-          <TD>Williams&nbsp;</TD>\r
-          <TD>Sat 06, Oct 2001&nbsp;</TD>\r
-        </TR>\r
-        <TR> \r
-          <TD align=right>38&nbsp;</TD>\r
-          <TD>Yat Sun&nbsp;</TD>\r
-          <TD>Sun&nbsp;</TD>\r
-          <TD>Sat 06, Oct 2001&nbsp;</TD>\r
-        </TR>\r
-        <TR> \r
-          <TD align=right>39&nbsp;</TD>\r
-          <TD>Wai Hun&nbsp;</TD>\r
-          <TD>See&nbsp;</TD>\r
-          <TD>Sat 06, Oct 2001&nbsp;</TD>\r
-        </TR>\r
-        <TR> \r
-          <TD align=right>40&nbsp;</TD>\r
-          <TD>Steven&nbsp;</TD>\r
-          <TD>Oey&nbsp;</TD>\r
-          <TD>Sat 06, Oct 2001&nbsp;</TD>\r
-        </TR>\r
-      </TABLE></td>\r
-  </tr>\r
-  <tr>\r
-    <td><font size=-1>Page 8/10</font></td>\r
-  </tr>\r
-</table>\r
-<p>The number of rows to display at one time is controled by the Render($rows) \r
-  method. If you do not pass any value to Render(), ADODB_Pager will default to \r
-  10 records per page. \r
-<p>You can control the column titles by modifying your SQL (supported by most \r
-  databases): \r
-<pre>$sql = 'select id as &quot;ID&quot;, firstname as &quot;First Name&quot;, \r
-                 lastname as &quot;Last Name&quot;, created as &quot;Date Created&quot; <br>           from adoxyz';</pre>\r
-<p>The above code can be found in the <i>adodb/tests/testpaging.php</i> example \r
-  included with this release, and the class ADODB_Pager in <i>adodb/adodb-pager.inc.php</i>. \r
-  The ADODB_Pager code can be adapted by a programmer so that the text links can \r
-  be replaced by images, and the dull white background be replaced with more interesting \r
-  colors. \r
-<p>You can also allow display of html by setting $pager->htmlSpecialChars = false. \r
-<p>Some of the code used here was contributed by Iv&aacute;n Oliva and Cornel \r
-  G. </p>\r
-<h3><a name="ex9"></a>Example 9: Exporting in CSV or Tab-Delimited Format</h3>\r
-<p>We provide some helper functions to export in comma-separated-value (CSV) and \r
-  tab-delimited formats:</p>\r
-<pre><b>include_once('/path/to/adodb/toexport.inc.php');</b><br>include_once('/path/to/adodb/adodb.inc.php');<br>\r
-$db = &amp;NewADOConnection('mysql');<br>$db-&gt;Connect($server, $userid, $password, $database);<br><br>$rs = $db-&gt;Execute('select fname as &quot;First Name&quot;, surname as &quot;Surname&quot; from table');\r
-\r
-print &quot;&lt;pre&gt;&quot;;<br>print <b>rs2csv</b>($rs); # return a string, CSV format<p>print '&lt;hr&gt;';\r
-<br>$rs-&gt;MoveFirst(); # note, some databases do not support MoveFirst<br>print <b>rs2tab</b>($rs,<i>false</i>); # return a string, tab-delimited\r
-                                                # false == suppress field names in first line</p>print '&lt;hr&gt;';<br>$rs-&gt;MoveFirst();<br><b>rs2tabout</b>($rs); # send to stdout directly (there is also an rs2csvout function)\r
-print &quot;&lt;/pre&gt;&quot;;\r
-\r
-$rs-&gt;MoveFirst();<br><b></b>$fp = fopen($path, &quot;w&quot;);\r
-if ($fp) {<br>  <b>rs2csvfile</b>($rs, $fp); # write to file (there is also an rs2tabfile function)\r
-  fclose($fp);<br>}\r
-</pre>\r
-<p> Carriage-returns or newlines are converted to spaces. Field names are returned \r
-  in the first line of text. Strings containing the delimiter character are quoted \r
-  with double-quotes. Double-quotes are double-quoted again. This conforms to \r
-  Excel import and export guide-lines. \r
-<p>All the above functions take as an optional last parameter, $addtitles which \r
-  defaults to <i>true</i>. When set to <i>false</i> field names in the first line \r
-  are suppressed. <br>\r
-<h3>Example 10: Recordset Filters<a name="ex10"></a></h3>\r
-<p>Sometimes we want to pre-process all rows in a recordset before we use it. \r
-  For example, we want to ucwords all text in recordset. \r
-<pre>\r
-include_once('adodb/rsfilter.inc.php');\r
-include_once('adodb/adodb.inc.php');\r
-\r
-// ucwords() every element in the recordset\r
-function do_ucwords(&$arr,$rs)\r
-&#123;\r
-       foreach($arr as $k => $v) &#123;\r
-               $arr[$k] = ucwords($v);\r
-       &#125;\r
-&#125;\r
-\r
-$db = NewADOConnection('mysql');\r
-$db->PConnect('server','user','pwd','db');\r
-\r
-$rs = $db->Execute('select ... from table');\r
-$rs = <b>RSFilter</b>($rs,'do_ucwords');\r
-</pre>\r
-<p>The <i>RSFilter</i> function takes 2 parameters, the recordset, and the name \r
-  of the <i>filter</i> function. It returns the processed recordset scrolled to \r
-  the first record. The <i>filter</i> function takes two parameters, the current \r
-  row as an array, and the recordset object. For future compatibility, you should \r
-  not use the original recordset object. </p>\r
-<h3>Example 11:<a name="ex11"></a> Smart Transactions</h3>\r
-The old way of doing transactions required you to use \r
-<pre>\r
-$conn-><b>BeginTrans</b>();\r
-$ok = $conn->Execute($sql);\r
-if ($ok) $ok = $conn->Execute($sql2);\r
-if (!$ok) $conn-><b>RollbackTrans</b>();\r
-else $conn-><b>CommitTrans</b>();\r
-</pre>\r
-This is very complicated for large projects because you have to track the error \r
-status. Smart Transactions is much simpler. You start a smart transaction by calling \r
-StartTrans(): \r
-<pre>\r
-$conn-><b>StartTrans</b>();\r
-$conn->Execute($sql);\r
-$conn->Execute($Sql2);\r
-$conn-><b>CompleteTrans</b>();\r
-</pre>\r
-CompleteTrans() detects when an SQL error occurs, and will Rollback/Commit as \r
-appropriate. To specificly force a rollback even if no error occured, use FailTrans(). \r
-Note that the rollback is done in CompleteTrans(), and not in FailTrans(). \r
-<pre>\r
-$conn-><b>StartTrans</b>();\r
-$conn->Execute($sql);\r
-if (!CheckRecords()) $conn-><strong>FailTrans</strong>();\r
-$conn->Execute($Sql2);\r
-$conn-><b>CompleteTrans</b>();\r
-</pre>\r
-<p>You can also check if a transaction has failed, using HasFailedTrans(), which \r
-  returns true if FailTrans() was called, or there was an error in the SQL execution. \r
-  Make sure you call HasFailedTrans() before you call CompleteTrans(), as it is \r
-  only works between StartTrans/CompleteTrans.\r
-<p>Lastly, StartTrans/CompleteTrans is nestable, and only the outermost block \r
-  is executed. In contrast, BeginTrans/CommitTrans/RollbackTrans is NOT nestable. \r
-<pre>\r
-$conn-><strong>StartTrans</strong>();\r
-$conn->Execute($sql);\r
-  $conn-><strong>StartTrans</strong>();    <font color="#006600"># ignored</font>\r
-  if (!CheckRecords()) $conn->FailTrans();\r
-  $conn-><strong>CompleteTrans</strong>(); <font color="#006600"># ignored</font>\r
-$conn->Execute($Sql2);\r
-$conn-><strong>CompleteTrans</strong>();\r
-</pre>\r
-<p>Note: Savepoints are currently not supported. \r
-<h2><a name="errorhandling"></a>Using Custom Error Handlers and PEAR_Error</h2>\r
-Apart from the old $con->debug = true; way of debugging, ADOdb 1.50 onwards provides \r
-another way of handling errors using ADOdb's custom error handlers. \r
-<p> ADOdb provides two custom handlers which you can modify for your needs. The \r
-  first one is in the <b>adodb-errorhandler.inc.php</b> file. This makes use of \r
-  the standard PHP functions <a href=http://php.net/error_reporting>error_reporting</a> \r
-  to control what error messages types to display, and <a href=http://php.net/trigger_error>trigger_error</a> \r
-  which invokes the default PHP error handler. \r
-<p> Including the above file will cause <i>trigger_error($errorstring,E_USER_ERROR)</i> \r
-  to be called when<br>\r
-  (a) Connect() or PConnect() fails, or <br>\r
-  (b) a function that executes SQL statements such as Execute() or SelectLimit() \r
-  has an error.<br>\r
-  (c) GenID() appears to go into an infinite loop. \r
-<p> The $errorstring is generated by ADOdb and will contain useful debugging information \r
-  similar to the error.log data generated below. This file adodb-errorhandler.inc.php \r
-  should be included before you create any ADOConnection objects. \r
-<p> If you define error_reporting(0), no errors will be passed to the error handler. \r
-  If you set error_reporting(E_ALL), all errors will be passed to the error handler. \r
-  You still need to use <b>ini_set("display_errors", "0" or "1")</b> to control \r
-  the display of errors. \r
-<pre>\r
-&lt;?php\r
-<b>error_reporting(E_ALL); # pass any error messages triggered to error handler\r
-include('adodb-errorhandler.inc.php');</b>\r
-include('adodb.inc.php');\r
-include('tohtml.inc.php');\r
-$c = NewADOConnection('mysql');\r
-$c->PConnect('localhost','root','','northwind');\r
-$rs=$c->Execute('select * from productsz'); #invalid table productsz');\r
-if ($rs) rs2html($rs);\r
-?>\r
-</pre>\r
-<p> If you want to log the error message, you can do so by defining the following \r
-  optional constants ADODB_ERROR_LOG_TYPE and ADODB_ERROR_LOG_DEST. ADODB_ERROR_LOG_TYPE \r
-  is the error log message type (see <a href=http://php.net/error_log>error_log</a> \r
-  in the PHP manual). In this case we set it to 3, which means log to the file \r
-  defined by the constant ADODB_ERROR_LOG_DEST. \r
-<pre>\r
-&lt;?php\r
-<b>error_reporting(E_ALL); # report all errors\r
-ini_set("display_errors", "0"); # but do not echo the errors\r
-define('ADODB_ERROR_LOG_TYPE',3);\r
-define('ADODB_ERROR_LOG_DEST','C:/errors.log');\r
-include('adodb-errorhandler.inc.php');</b>\r
-include('adodb.inc.php');\r
-include('tohtml.inc.php');\r
-\r
-$c = NewADOConnection('mysql');\r
-$c->PConnect('localhost','root','','northwind');\r
-$rs=$c->Execute('select * from productsz'); ## invalid table productsz\r
-if ($rs) rs2html($rs);\r
-?>\r
-</pre>\r
-The following message will be logged in the error.log file: \r
-<pre>\r
-(2001-10-28 14:20:38) mysql error: [1146: Table 'northwind.productsz' doesn't exist] in\r
- EXECUTE("select * from productsz")\r
-</pre>\r
-The second error handler is <b>adodb-errorpear.inc.php</b>. This will create a \r
-PEAR_Error derived object whenever an error occurs. The last PEAR_Error object \r
-created can be retrieved using ADODB_Pear_Error(). \r
-<pre>\r
-&lt;?php\r
-<b>include('adodb-errorpear.inc.php');</b>\r
-include('adodb.inc.php');\r
-include('tohtml.inc.php');\r
-$c = NewADOConnection('mysql');\r
-$c->PConnect('localhost','root','','northwind');\r
-$rs=$c->Execute('select * from productsz'); #invalid table productsz');\r
-if ($rs) rs2html($rs);\r
-else &#123;\r
-       <b>$e = ADODB_Pear_Error();\r
-       echo '&lt;p>',$e->message,'&lt;/p>';</b>\r
-&#125;\r
-?>\r
-</pre>\r
-<p> You can use a PEAR_Error derived class by defining the constant ADODB_PEAR_ERROR_CLASS \r
-  before the adodb-errorpear.inc.php file is included. For easy debugging, you \r
-  can set the default error handler in the beginning of the PHP script to PEAR_ERROR_DIE, \r
-  which will cause an error message to be printed, then halt script execution: \r
-<pre>\r
-include('PEAR.php');\r
-PEAR::setErrorHandling('PEAR_ERROR_DIE');\r
-</pre>\r
-<p> Note that we do not explicitly return a PEAR_Error object to you when an error \r
-  occurs. We return false instead. You have to call ADODB_Pear_Error() to get \r
-  the last error or use the PEAR_ERROR_DIE technique. \r
-<h4>Error Messages</h4>\r
-<p>Error messages are outputted using the static method ADOConnnection::outp($msg,$newline=true). \r
-  By default, it sends the messages to the client. You can override this to perform \r
-  error-logging. \r
-<h2><a name="dsn"></a> Data Source Names</h2>\r
-<p>We now support connecting using PEAR style DSN's. A DSN is a connection string \r
-  of the form:</p>\r
-<p>$dsn = <i>&quot;$driver://$username:$password@$hostname/$databasename&quot;</i>;</p>\r
-<p>You pass the DSN to the static class function DB::Connect. An example:</p>\r
-<pre>   include_once('../adodb/adodb-pear.inc.php');\r
-   $username = 'root';\r
-   $password = '';\r
-   $hostname = 'localhost';\r
-   $databasename = 'xphplens';\r
-   $driver = 'mysql';\r
-   $dsn = &quot;$driver://$username:$password@$hostname/$databasename&quot;;</pre>\r
-<pre>   $db = DB::Connect($dsn);<br>   $rs = $db-&gt;Execute('select firstname,lastname from adoxyz');\r
-   $cnt = 0;\r
-   while ($arr = $rs-&gt;FetchRow()) {\r
-               print_r($arr); print &quot;&lt;br&gt;&quot;;\r
-   }</pre>\r
-<p>This requires PEAR to be installed and in the default include path in php.ini.</p>\r
-<h2><a name="caching"></a>Caching of Recordsets</h2>\r
-<p>ADOdb now supports caching of recordsets using the CacheExecute( ), CachePageExecute( \r
-  ) and CacheSelectLimit( ) functions. There are similar to the non-cache functions, \r
-  except that they take a new first parameter, $secs2cache. \r
-<p> An example: \r
-<pre>\r
-<b>include</b>('adodb.inc.php'); # load code common to ADOdb\r
-$ADODB_CACHE_DIR = '/usr/ADODB_cache';\r
-$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');  # create a connection\r
-$<font color="#663300">conn</font>->PConnect('localhost','userid','','agora');# connect to MySQL, agora db\r
-<font color="#000000">$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers';\r
-$<font color="#663300">rs</font> = $<font color="#663300">conn</font>->CacheExecute(15,$sql);</font></pre>\r
-<p><font color="#000000"> The first parameter is the number of seconds to cache \r
-  the query. Subsequent calls to that query will used the cached version stored \r
-  in $ADODB_CACHE_DIR. To force a query to execute and flush the cache, call CacheExecute() \r
-  with the first parameter set to zero. Alternatively, use the CacheFlush($sql) \r
-  call. </font></p>\r
-<p><font color="#000000">For the sake of security, we recommend you set <i>register_globals=off</i> \r
-  in php.ini if you are using $ADODB_CACHE_DIR.</font></p>\r
-<p>In ADOdb 1.80 onwards, the secs2cache parameter is optional in CacheSelectLimit() \r
-  and CacheExecute(). If you leave it out, it will use the $connection->cacheSecs \r
-  parameter, which defaults to 60 minutes. \r
-<pre>\r
-       $conn->Connect(...);\r
-       $conn->cacheSecs = 3600*24; # cache 24 hours\r
-       $rs = $conn->CacheExecute('select * from table');\r
-</pre>\r
-<p>Please note that magic_quotes_runtime should be turned off. <a href=http://phplens.com/lens/lensforum/msgs.php?LeNs#LensBM_forummsg>More \r
-  info</a>. <font color="#000000"> \r
-<h2><a name="pivot"></a>Pivot Tables</h2>\r
-</font> <p><font color="#000000">Since ADOdb 2.30, we support the generation of \r
-SQL to create pivot tables, also known as cross-tabulations. For further explanation \r
-read this DevShed <a href=http://www.devshed.com/Server_Side/MySQL/MySQLWiz/>Cross-Tabulation \r
-tutorial. We assume that your database supports the SQL case-when expression. </font></p> \r
-<font color="#000000"> \r
-<p>In this example, we will use the Northwind database from Microsoft. In the \r
-  database, we have a products table, and we want to analyze this table by <i>suppliers \r
-  versus product categories</i>. We will place the suppliers on each row, and \r
-  pivot on categories. So from the table on the left, we generate the pivot-table \r
-  on the right:</p>\r
-</font> \r
-<table border="0" cellspacing="2" cellpadding="2" align="center">\r
-  <tr>\r
-       <td>\r
-         <table border="1" cellspacing="2" cellpadding="2" align="center" width="142">\r
-               <tr> \r
-                 <td><i>Supplier</i></td>\r
-                 <td><i>Category</i></td>\r
-               </tr>\r
-               <tr> \r
-                 <td>supplier1</td>\r
-                 <td>category1</td>\r
-               </tr>\r
-               <tr> \r
-                 <td>supplier2</td>\r
-                                       <td>category1</td>\r
-               </tr>\r
-               <tr> \r
-                                       <td>supplier2</td>\r
-                 <td>category2</td>\r
-               </tr>\r
-         </table>\r
-       </td>\r
-       <td> <font face="Courier New, Courier, mono">--&gt;</font></td>\r
-       <td>\r
-         <table border="1" cellspacing="2" cellpadding="2" align="center">\r
-               <tr> \r
-                 <td>&nbsp;</td>\r
-                 <td><i>category1</i></td>\r
-                 <td><i>category2</i></td>\r
-                 <td><i>total</i></td>\r
-               </tr>\r
-               <tr> \r
-                 <td><i>supplier1</i></td>\r
-                 <td align="right">1</td>\r
-                 <td align="right">0</td>\r
-                 <td align="right">1</td>\r
-               </tr>\r
-               <tr> \r
-                 <td><i>supplier2</i></td>\r
-                 <td align="right">1</td>\r
-                 <td align="right">1</td>\r
-                 <td align="right">2</td>\r
-               </tr>\r
-         </table>\r
-       </td>\r
-  </tr>\r
-</table>\r
-<font color="#000000"> \r
-<p>The following code will generate the SQL for a cross-tabulation: \r
-<pre>\r
-# Query the main "product" table\r
-# Set the rows to CompanyName\r
-# and the columns to the values of Categories\r
-# and define the joins to link to lookup tables \r
-# "categories" and "suppliers"\r
-#\r
- include &quot;adodb/pivottable.php&quot;;\r
- $sql = PivotTableSQL(\r
-       $gDB,                                      # adodb connection\r
-       'products p ,categories c ,suppliers s',   # tables\r
-       'CompanyName',                             # rows (multiple fields allowed)\r
-       'CategoryName',                            # column to pivot on \r
-       'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where\r
-);\r
-</pre>\r
-</font> \r
-<p><font color="#000000"> This will generate the following SQL:</font></p>\r
-<p><code><font size="2">SELECT CompanyName, <br>\r
-  SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS &quot;Beverages&quot;, \r
-  <br>\r
-  SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS &quot;Condiments&quot;, \r
-  <br>\r
-  SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS &quot;Confections&quot;, \r
-  <br>\r
-  SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS &quot;Dairy \r
-  Products&quot;, <br>\r
-  SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS &quot;Grains/Cereals&quot;, \r
-  <br>\r
-  SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS &quot;Meat/Poultry&quot;, \r
-  <br>\r
-  SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS &quot;Produce&quot;, \r
-  <br>\r
-  SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS &quot;Seafood&quot;, \r
-  <br>\r
-  SUM(1) as Total <br>\r
-  FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID \r
-  and s.SupplierID= p.SupplierID <br>\r
-  GROUP BY CompanyName</font></code></p>\r
-<p> You can also pivot on <i>numerical columns</i> and <i>generate totals</i> \r
-       by using ranges. <font color="#000000">This code was revised in ADODB 2.41 \r
-       and is not backward compatible.</font> The second example shows this:</p>\r
-<pre>\r
- $sql = PivotTableSQL(\r
-       $gDB,                                       # adodb connection\r
-       'products p ,categories c ,suppliers s',    # tables\r
-       'CompanyName',                              #<font color="#000000"> rows (multiple fields allowed)</font>\r
-   array(                                       # column ranges\r
-       ' 0 '      => 'UnitsInStock <= 0',\r
-       "1 to 5"   => '0 < UnitsInStock and UnitsInStock <= 5',\r
-       "6 to 10"  => '5 < UnitsInStock and UnitsInStock <= 10',\r
-       "11 to 15" => '10 < UnitsInStock and UnitsInStock <= 15',\r
-       "16+"      => '15 < UnitsInStock'\r
-       ),\r
-       ' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where\r
-       'UnitsInStock',                             # sum this field\r
-       'Sum '                                      # sum label prefix\r
-);\r
-</pre> \r
-<p>Which generates: </p>\r
-<p> <code> <font size="2">SELECT CompanyName, <br>\r
-       SUM(CASE WHEN UnitsInStock &lt;= 0 THEN UnitsInStock ELSE 0 END) AS &quot;Sum \r
-       0 &quot;, <br>\r
-       SUM(CASE WHEN 0 &lt; UnitsInStock and UnitsInStock &lt;= 5 THEN UnitsInStock \r
-       ELSE 0 END) AS &quot;Sum 1 to 5&quot;,<br>\r
-       SUM(CASE WHEN 5 &lt; UnitsInStock and UnitsInStock &lt;= 10 THEN UnitsInStock \r
-       ELSE 0 END) AS &quot;Sum 6 to 10&quot;,<br>\r
-       SUM(CASE WHEN 10 &lt; UnitsInStock and UnitsInStock &lt;= 15 THEN UnitsInStock \r
-       ELSE 0 END) AS &quot;Sum 11 to 15&quot;, <br>\r
-       SUM(CASE WHEN 15 &lt; UnitsInStock THEN UnitsInStock ELSE 0 END) AS &quot;Sum \r
-       16+&quot;, <br>\r
-       SUM(UnitsInStock) AS "Sum UnitsInStock", <br>\r
-       SUM(1) as Total,<br>\r
-       FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID \r
-       and s.SupplierID= p.SupplierID <br>\r
-       GROUP BY CompanyName</font></code><font size="2"><br>\r
-       </font> </p>\r
-<font color="#000000"><hr>\r
-<h1>Class Reference<a name="ref"></a></h1>\r
-<p>Function parameters with [ ] around them are optional.</p>\r
-</font> \r
-<h2>Global Variables</h2>\r
-<h3><font color="#000000"><a name="adodb_countrecs"></a></font>$ADODB_COUNTRECS</h3>\r
-<p>If the database driver API does not support counting the number of records \r
-       returned in a SELECT statement, the function RecordCount() is emulated when \r
-       the global variable $ADODB_COUNTRECS is set to true, which is the default. \r
-       We emulate this by buffering the records, which can take up large amounts \r
-       of memory for big recordsets. Set this variable to false for the best performance. \r
-       This variable is checked every time a query is executed, so you can selectively \r
-       choose which recordsets to count.</p>\r
-<h3><font color="#000000"><a name="adodb_cache_dir"></a>$ADODB_CACHE_DIR</font></h3>\r
-<font color="#000000"> \r
-<p>If you are using recordset caching, this is the directory to save your recordsets \r
-  in. Define this before you call any caching functions such as CacheExecute( \r
-  ). We recommend setting <i>register_globals=off</i> in php.ini if you use this \r
-  feature for security reasons.</p>\r
-<p>If you are using Unix and apache, you might need to set your cache directory \r
-  permissions to something similar to the following:</p>\r
-</font> \r
-<p>chown -R apache /path/to/adodb/cache<br>\r
-  chgrp -R apache /path/to/adodb/cache </p>\r
-<font color="#000000">\r
-<h3><a name="adodb_ansi_padding_off"></a>$ADODB_ANSI_PADDING_OFF</h3>\r
-<p>Determines whether to right trim CHAR fields (and also VARCHAR for ibase/firebird).\r
-Set to true to trim. Default is false. Currently works for oci8po, ibase and firebird \r
-drivers. Added in ADOdb 4.01.\r
-<h3><font color="#000000"><a name="adodb_lang"></a></font>$ADODB_LANG</h3>\r
-<p>Determines the language used in MetaErrorMsg(). The default is 'en', for English. \r
-To find out what languages are supported, see the files \r
-in adodb/lang/adodb-$lang.inc.php, where $lang is the supported langauge.\r
-<h3><a name="adodb_fetch_mode"></a>$ADODB_FETCH_MODE</h3>\r
-<p>This is a global variable that determines how arrays are retrieved by recordsets. \r
-  The recordset saves this value on creation (eg. in Execute( ) or SelectLimit( \r
-  )), and any subsequent changes to $ADODB_FETCH_MODE have no affect on existing \r
-  recordsets, only on recordsets created in the future.</p>\r
-<p>The following constants are defined:</p>\r
-</font> \r
-<p><font color="#000000">define('ADODB_FETCH_DEFAULT',0);<br>\r
-  define('ADODB_FETCH_NUM',1);<br>\r
-  define('ADODB_FETCH_ASSOC',2);<br>\r
-  define('ADODB_FETCH_BOTH',3); </font></p>\r
-<font color="#000000"> \r
-<p> An example: \r
-<pre>\r
-       $ADODB_<b>FETCH_MODE</b> = ADODB_FETCH_NUM;\r
-       $rs1 = $db->Execute('select * from table');\r
-       $ADODB_<b>FETCH_MODE</b> = ADODB_FETCH_ASSOC;\r
-       $rs2 = $db->Execute('select * from table');\r
-       print_r($rs1->fields); # shows <i>array([0]=>'v0',[1] =>'v1')</i>\r
-       print_r($rs2->fields); # shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i>\r
-</pre>\r
-<p> As you can see in the above example, both recordsets store and use different \r
-       fetch modes based on the $ADODB_FETCH_MODE setting when the recordset was \r
-       created by Execute().</p>\r
-<p>If no fetch mode is predefined, the fetch mode defaults to ADODB_FETCH_DEFAULT. \r
-       The behaviour of this default mode varies from driver to driver, so do not \r
-       rely on ADODB_FETCH_DEFAULT. For portability, we recommend sticking to ADODB_FETCH_NUM \r
-       or ADODB_FETCH_ASSOC. Many drivers do not support ADODB_FETCH_BOTH.</p>\r
-<p><strong>SetFetchMode Function</strong></p>\r
-<p>Some programmers prefer to use a more object-oriented solution, where the fetch \r
-       mode is set by a object function, <a href="#setfetchmode">SetFetchMode</a>. \r
-       Once this function is called for a connection object, that connection object \r
-       will ignore the global variable $ADODB_FETCH_MODE and will use the internal \r
-       fetchMode property exclusively.</p>\r
-<pre>\r
-       $db->SetFetchMode(ADODB_FETCH_NUM);\r
-       $rs1 = $db->Execute('select * from table');\r
-       $db->SetFetchMode(ADODB_FETCH_ASSOC);\r
-       $rs2 = $db->Execute('select * from table');\r
-       print_r($rs1->fields); # shows <i>array([0]=>'v0',[1] =>'v1')</i>\r
-       print_r($rs2->fields); # shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i></pre>\r
-<p>To retrieve the previous fetch mode, you can use check the $db-&gt;fetchMode \r
-       property, or use the return value of SetFetchMode( ). \r
-<p><strong><a name="adodb_assoc_case"></a>ADODB_ASSOC_CASE</strong></p>\r
-<p>You can control the associative fetch case for certain drivers which behave \r
-       differently. For the sybase, oci8po, mssql, odbc and ibase drivers and all \r
-       drivers derived from them, ADODB_ASSOC_CASE will by default generate recordsets \r
-       where the field name keys are lower-cased. Use the constant ADODB_ASSOC_CASE \r
-       to change the case of the keys. There are 3 possible values:</p>\r
-<p>0 = assoc lowercase field names. $rs-&gt;fields['orderid']<br>\r
-       1 = assoc uppercase field names. $rs-&gt;fields['ORDERID']<br>\r
-       2 = use native-case field names. $rs-&gt;fields['OrderID'] -- this is the \r
-       default since ADOdb 2.90</p>\r
-<p>To use it, declare it before you incldue adodb.inc.php.</p>\r
-<p>define('ADODB_ASSOC_CASE', 2); # use native-case for ADODB_FETCH_ASSOC<br>\r
-       include('adodb.inc.php'); </p>\r
-<hr>\r
-<h2>ADOConnection<a name="adoconnection"></a></h2>\r
-<p>Object that performs the connection to the database, executes SQL statements \r
-       and has a set of utility functions for standardising the format of SQL statements \r
-       for issues such as concatenation and date formats.</p>\r
-<h3>ADOConnection Fields</h3>\r
-<p><b>databaseType</b>: Name of the database system we are connecting to. Eg. \r
-       <b>odbc</b> or <b>mssql</b> or <b>mysql</b>.</p>\r
-<p><b>dataProvider</b>: The underlying mechanism used to connect to the database. \r
-       Normally set to <b>native</b>, unless using <b>odbc</b> or <b>ado</b>.</p>\r
-<p><b>host: </b>Name of server or data source name (DSN) to connect to.</p>\r
-<p><b>database</b>: Name of the database or to connect to. If ado is used, it \r
-       will hold the ado data provider.</p>\r
-<p><b>user</b>: Login id to connect to database. Password is not saved for security \r
-       reasons.</p>\r
-<p><b>raiseErrorFn</b>: Allows you to define an error handling function. See adodb-errorhandler.inc.php \r
-       for an example.</p>\r
-<p><b>debug</b>: Set to <i>true</i> to make debug statements to appear.</p>\r
-<p><b>concat_operator</b>: Set to '+' or '||' normally. The operator used to concatenate \r
-       strings in SQL. Used by the <b><a href="#concat">Concat</a></b> function.</p>\r
-<p><b>fmtDate</b>: The format used by the <b><a href="#dbdate">DBDate</a></b> \r
-       function to send dates to the database. is '#Y-m-d#' for Microsoft Access, \r
-       and ''Y-m-d'' for MySQL.</p>\r
-<p><b>fmtTimeStamp: </b>The format used by the <b><a href="#dbtimestamp">DBTimeStamp</a></b> \r
-       function to send timestamps to the database. </p>\r
-<p><b>true</b>: The value used to represent true.Eg. '.T.'. for Foxpro, '1' for \r
-       Microsoft SQL.</p>\r
-<p><b>false: </b> The value used to represent false. Eg. '.F.'. for Foxpro, '0' \r
-       for Microsoft SQL.</p>\r
-<p><b>replaceQuote</b>: The string used to escape quotes. Eg. double single-quotes \r
-       for Microsoft SQL, and backslash-quote for MySQL. Used by <a href="#qstr">qstr</a>.</p>\r
-<p><b>autoCommit</b>: indicates whether automatic commit is enabled. Default is \r
-       true.</p>\r
-<p><b>charSet</b>: set the default charset to use. Currently only interbase supports \r
-       this.</p>\r
-<p><b>dialect</b>: set the default sql dialect to use. Currently only interbase \r
-       supports this.</p>\r
-<p><b>metaTablesSQL</b>: SQL statement to return a list of available tables. Eg. \r
-       <i>SHOW TABLES</i> in MySQL.</p>\r
-<p><b>genID</b>: The latest id generated by GenID() if supported by the database.</p>\r
-<p><b>cacheSecs</b>: The number of seconds to cache recordsets if CacheExecute() \r
-       or CacheSelectLimit() omit the $secs2cache parameter. Defaults to 60 minutes.</p>\r
-<p><b>sysDate</b>: String that holds the name of the database function to call \r
-       to get the current date. Useful for inserts and updates.</p>\r
-<p><b>sysTimeStamp</b>: String that holds the name of the database function to \r
-       call to get the current timestamp/datetime value.</p>\r
-<p><b>leftOuter</b>: String that holds operator for left outer join, if known. \r
-       Otherwise set to false.</p>\r
-<p><b>rightOuter</b>: String that holds operator for left outer join, if known. \r
-       Otherwise set to false.</p>\r
-<p><b>ansiOuter</b>: Boolean that if true indicates that ANSI style outer joins \r
-       are permitted. Eg. <i>select * from table1 left join table2 on p1=p2.</i></p>\r
-<p><b>connectSID</b>: Boolean that indicates whether to treat the $database parameter \r
-       in connects as the SID for the oci8 driver. Defaults to false. Useful for \r
-       Oracle 8.0.5 and earlier.</p>\r
-<p><b>autoRollback</b>: Persistent connections are auto-rollbacked in PConnect( \r
-       ) if this is set to true. Default is false.</p>\r
-<hr>\r
-<h3>ADOConnection Main Functions</h3>\r
-<p><b>ADOConnection( )</b></p>\r
-<p>Constructor function. Do not call this directly. Use ADONewConnection( ) instead.</p>\r
-<p><b>Connect<a name="connect"></a>($host,[$user],[$password],[$database])</b></p>\r
-<p>Non-persistent connect to data source or server $<b>host</b>, using userid \r
-       $<b>user </b>and password $<b>password</b>. If the server supports multiple \r
-       databases, connect to database $<b>database</b>. </p>\r
-<p>Returns true/false depending on connection.</p>\r
-<p>ADO Note: If you are using a Microsoft ADO and not OLEDB, you can set the $database \r
-       parameter to the OLEDB data provider you are using.</p>\r
-<p>PostgreSQL: An alternative way of connecting to the database is to pass the \r
-       standard PostgreSQL connection string in the first parameter $host, and the \r
-       other parameters will be ignored.</p>\r
-<p>For Oracle and Oci8, there are two ways to connect. First is to use the TNS \r
-       name defined in your local tnsnames.ora (or ONAMES or HOSTNAMES). Place the \r
-       name in the $database field, and set the $host field to false. Alternatively, \r
-       set $host to the server, and $database to the database SID, this bypassed \r
-       tnsnames.ora. \r
-<p>Examples: \r
-<pre> # $oraname in tnsnames.ora/ONAMES/HOSTNAMES\r
- $conn->Connect(false, 'scott', 'tiger', $oraname); \r
- $conn->Connect('server:1521', 'scott', 'tiger', 'ServiceName'); # bypass tnsnames.ora</pre>\r
-<p>There are many examples of connecting to a database at <a href="http://php.weblogs.com/adodb">php.weblogs.com/ADOdb</a>, \r
-       and in the testdatabases.inc.php file included in the release.</p>\r
-<p><b>PConnect<a name="pconnect"></a>($host,[$user],[$password],[$database])</b></p>\r
-<p>Persistent connect to data source or server $<b>host</b>, using userid $<b>user</b> \r
-       and password $<b>password</b>. If the server supports multiple databases, \r
-       connect to database $<b>database</b>.</p>\r
-<p>We now perform a rollback on persistent connection for selected databases since \r
-       2.21, as advised in the PHP manual. See change log or source code for which \r
-       databases are affected. \r
-<p>Returns true/false depending on connection. See Connect( ) above for more info.</p>\r
-<p>Since ADOdb 2.21, we also support autoRollback. If you set:</p>\r
-</font> \r
-<pre> $conn = &amp;NewADOConnection('mysql');\r
- $conn-&gt;autoRollback = true; # default is false\r
- $conn-&gt;PConnect(...); # rollback here</pre>\r
-<p> Then when doing a persistent connection with PConnect( ), ADOdb will \r
-  perform a rollback first. This is because it is documented that PHP is \r
-  not guaranteed to rollback existing failed transactions when \r
-  persistent connections are used. This is implemented in Oracle, \r
-  MySQL, PgSQL, MSSQL, ODBC currently. \r
-<p>Since ADOdb 3.11, you can force non-persistent \r
-connections even if PConnect is called by defining the constant \r
-ADODB_NEVER_PERSIST  before you call PConnect.\r
-<p><b>NConnect<a name="nconnect"></a>($host,[$user],[$password],[$database])</b></p>\r
-<p>Always force a new connection. In contrast, PHP sometimes reuses connections \r
-       when you use Connect() or PConnect(). Currently works only on mysql (PHP 4.3.0 \r
-       or later), postgresql and oci8-derived drivers. For other drivers, NConnect() works like \r
-       Connect(). \r
-<font color="#000000"> \r
-<p><b>Execute<a name="execute"></a>($sql,$inputarr=false)</b></p>\r
-<p>Execute SQL statement $<b>sql</b> and return derived class of ADORecordSet \r
-       if successful. Note that a record set is always returned on success, even \r
-       if we are executing an insert or update statement. You can also pass in $sql a statement prepared \r
-       in <a href=#prepare>Prepare()</a>.</p>\r
-<p>Returns derived class of ADORecordSet. Eg. if connecting via mysql, then ADORecordSet_mysql \r
-       would be returned. False is returned if there was an error in executing the \r
-       sql.</p>\r
-<p>The $inputarr parameter can be used for binding variables to parameters. Below \r
-       is an Oracle example:</p>\r
-<pre>\r
- $conn->Execute("SELECT * FROM TABLE WHERE COND=:val", array('val'=> $val));\r
- </pre>\r
-<p>Another example, using ODBC,which uses the ? convention:</p>\r
-<pre>\r
-  $conn->Execute("SELECT * FROM TABLE WHERE COND=?", array($val));\r
-</pre>\r
-<a name="binding"></a>\r
-<i>Binding variables</i><p>\r
-Variable binding speeds the compilation and caching of SQL statements, leading \r
-to higher performance. Currently Oracle, Interbase and ODBC supports variable binding. \r
-Interbase/ODBC style ? binding is emulated in databases that do not support binding. \r
-Note that you do not have to quote strings if you use binding.\r
-<p> Variable binding in the odbc, interbase and oci8po drivers. \r
-<pre>\r
-$rs = $db->Execute('select * from table where val=?', array('10'));\r
-</pre>\r
-Variable binding in the oci8 driver: \r
-<pre>\r
-$rs = $db->Execute('select name from table where val=:key', \r
-  array('key' => 10));\r
-</pre>\r
-<a name="bulkbind"></a>\r
-<i>Bulk binding</i>\r
-<p>Since ADOdb 3.80, we support bulk binding in Execute(), in which you pass in a 2-dimensional array to\r
-be bound to an INSERT/UPDATE or DELETE statement.\r
-<pre>\r
-$arr = array(\r
-       array('Ahmad',32),\r
-       array('Zulkifli', 24),\r
-       array('Rosnah', 21)\r
-       );\r
-$ok = $db->Execute('insert into table (name,age) values (?,?)',$arr);\r
-</pre>\r
-<p>This provides very high performance as the SQL statement is prepared first. \r
-The prepared statement is executed repeatedly for each array row until all rows are completed, \r
-or until the first error. Very useful for importing data.\r
-\r
-<p><b>CacheExecute<a name="cacheexecute"></a>([$secs2cache,]$sql,$inputarr=false)</b></p>\r
-<p>Similar to Execute, except that the recordset is cached for $secs2cache seconds \r
-       in the $ADODB_CACHE_DIR directory, and $inputarr only accepts 1-dimensional arrays. \r
-       If CacheExecute() is called again with the same $sql, $inputarr, \r
-       and also the same database, same userid, and the cached recordset \r
-       has not expired, the cached recordset is returned. \r
-<pre>\r
-  include('adodb.inc.php'); \r
-  include('tohtml.inc.php');\r
-  $ADODB_<b>CACHE_DIR</b> = '/usr/local/ADOdbcache';\r
-  $conn = &ADONewConnection('mysql'); \r
-  $conn->PConnect('localhost','userid','password','database');\r
-  $rs = $conn-><b>CacheExecute</b>(15, 'select * from table'); # cache 15 secs\r
-  rs2html($rs); /* recordset to html table */  \r
-</pre>\r
-<p> Alternatively, since ADOdb 1.80, the $secs2cache parameter is optional:</p>\r
-<pre>  $conn-&gt;Connect(...);\r
-       $conn-&gt;cacheSecs = 3600*24; // cache 24 hours\r
-       $rs = $conn-&gt;CacheExecute('select * from table');\r
-</pre>\r
-If $secs2cache is omitted, we use the value \r
-in $connection-&gt;cacheSecs (default is 3600 seconds, or 1 hour). Use CacheExecute() \r
-only with SELECT statements. \r
-<p>Performance note: I have done some benchmarks and found that they vary so greatly \r
-       that it's better to talk about when caching is of benefit. When your database \r
-       server is <i>much slower </i>than your Web server or the database is <i>very \r
-       overloaded </i>then ADOdb's caching is good because it reduces the load on \r
-       your database server. If your database server is lightly loaded or much faster \r
-       than your Web server, then caching could actually reduce performance. </p>\r
-<p><b>ExecuteCursor<a name="executecursor"></a>($sql,$cursorName='rs',$parameters=false)</b></p>\r
-<p>Execute an Oracle stored procedure, and returns an Oracle REF cursor variable as \r
-       a regular ADOdb recordset. Does not work with any other database except oci8. \r
-       Thanks to Robert Tuttle for the design.\r
-<pre>\r
-    $db = ADONewConnection("oci8"); \r
-    $db->Connect("foo.com:1521", "uid", "pwd", "FOO"); \r
-    $rs = $db->ExecuteCursor("begin :cursorvar := getdata(:param1); end;", \r
-                                       'cursorvar',\r
-                                       array('param1'=>10)); \r
-    # $rs is now just like any other ADOdb recordset object<br>    rs2html($rs);</pre>\r
-<p>ExecuteCursor() is a helper function that does the following internally: \r
-<pre>\r
-       $stmt = $db->Prepare("BEGIN :RS := SP_FOO(); END;", true); \r
-       $db->Parameter($stmt, $cur, 'RS', false, -1, OCI_B_CURSOR);\r
-       $rs = $db->Execute($stmt);</pre>\r
-<p><b>SelectLimit<a name="selectlimit"></a>($sql,$numrows=-1,$offset=-1,$inputarr=false)</b></p>\r
-<p>Returns a recordset if successful. Returns false otherwise. Performs a select \r
-       statement, simulating PostgreSQL's SELECT statement, LIMIT $numrows OFFSET \r
-       $offset clause.</p>\r
-<p>In PostgreSQL, SELECT * FROM TABLE LIMIT 3 will return the first 3 records \r
-       only. The equivalent is <code>$connection->SelectLimit('SELECT * FROM TABLE',3)</code>. \r
-       This functionality is simulated for databases that do not possess this feature.</p>\r
-<p>And SELECT * FROM TABLE LIMIT 3 OFFSET 2 will return records 3, 4 and 5 (eg. \r
-       after record 2, return 3 rows). The equivalent in ADOdb is <code>$connection->SelectLimit('SELECT \r
-       * FROM TABLE',3,2)</code>.</p>\r
-<p>Note that this is the <i>opposite</i> of MySQL's LIMIT clause. You can also \r
-       set <code>$connection->SelectLimit('SELECT * FROM TABLE',-1,10)</code> to \r
-       get rows 11 to the last row.</p>\r
-<p>The last parameter $inputarr is for databases that support variable binding \r
-       such as Oracle oci8. This substantially reduces SQL compilation overhead. \r
-       Below is an Oracle example:</p>\r
-<pre>\r
- $conn->SelectLimit("SELECT * FROM TABLE WHERE COND=:val", 100,-1,array('val'=> $val));\r
- </pre>\r
-<p>The oci8po driver (oracle portable driver) uses the more standard bind variable \r
-       of ?: \r
-<pre>\r
- $conn->SelectLimit("SELECT * FROM TABLE WHERE COND=?", 100,-1,array('val'=> $val));\r
-</pre>\r
-<p> \r
-<p>Ron Wilson reports that SelectLimit does not work with UNIONs. \r
-<p><b>CacheSelectLimit<a name="cacheselectlimit"></a>([$secs2cache,] $sql, $numrows=-1,$offset=-1,$inputarr=false)</b></p>\r
-<p>Similar to SelectLimit, except that the recordset returned is cached for $secs2cache \r
-       seconds in the $ADODB_CACHE_DIR directory. </p>\r
-<p>Since 1.80, $secs2cache has been optional, and you can define the caching time \r
-       in $connection-&gt;cacheSecs.</p>\r
-</font> \r
-<pre><font color="#000000">    $conn-&gt;Connect(...);\r
-   $conn-&gt;cacheSecs = 3600*24; // cache 24 hours\r
-       $rs = $conn-&gt;CacheSelectLimit('select * from table',10);</font></pre>\r
-<font color="#000000"> \r
-<p><b>CacheFlush<a name="cacheflush"></a>($sql=false,$inputarr=false)</b></p>\r
-<p>Flush (delete) any cached recordsets for the SQL statement $sql in $ADODB_CACHE_DIR. \r
-<p>If no parameter is passed in, then all adodb_*.cache files are deleted. \r
-<p> If you want to flush all cached recordsets manually, execute the following \r
-       PHP code (works only under Unix): <br>\r
-       <code> &nbsp; system(&quot;rm -f `find &quot;.$ADODB_CACHE_DIR.&quot; -name \r
-       adodb_*.cache`&quot;);</code></p>\r
-<p>For general cleanup of all expired files, you should use <a href="http://www.superscripts.com/tutorial/crontab.html">crontab</a> \r
-       on Unix, or at.exe on Windows, and a shell script similar to the following:<font face="Courier New, Courier, mono"><br>\r
-       #------------------------------------------------------ <br>\r
-       # This particular example deletes files in the TMPPATH <br>\r
-       # directory with the string &quot;.cache&quot; in their name that <br>\r
-       # are more than 7 days old. <br>\r
-       #------------------------------------------------------ <br>\r
-       AGED=7 <br>\r
-       find ${TMPPATH} -mtime +$AGED | grep &quot;\.cache&quot; | xargs rm -f <br>\r
-       </font> </p>\r
-<p><b>MetaError<a name="metaerror"></a>($errno=false)</b></p>\r
-<p>Returns a virtualized error number, based on PEAR DB's error number system. You might\r
-need to include adodb-error.inc.php before you call this function. The parameter $errno\r
-is the native error number you want to convert. If you do not pass any parameter, MetaError\r
-will call ErrorNo() for you and convert it. If the error number cannot be virtualized, MetaError \r
-will return -1 (DB_ERROR).</p>\r
-\r
-<p><b>MetaErrorMsg<a name="metaerrormsg"></a>($errno)</b></p>\r
-<p>Pass the error number returned by MetaError() for the equivalent textual error message.</p>\r
-<p><b>ErrorMsg<a name="errormsg"></a>()</b></p>\r
-<p>Returns the last status or error message. This can return a string even if \r
-       no error occurs. In general you do not need to call this function unless an \r
-       ADOdb function returns false on an error. </p>\r
-<p>Note: If <b>debug</b> is enabled, the SQL error message is always displayed \r
-       when the <b>Execute</b> function is called.</p>\r
-<p><b>ErrorNo<a name="errorno"></a>()</b></p>\r
-<p>Returns the last error number. Note that old versions of PHP (pre 4.0.6) do \r
-       not support error number for ODBC. In general you do not need to call this \r
-       function unless an ADOdb function returns false on an error.</p>\r
-</font>\r
-<p><font color="#000000"><b>SetFetchMode<a name="setfetchmode"></a>($mode)</b></font></p>\r
-<p><font color="#000000">Sets the current fetch mode for the connection and stores \r
-       it in $db-&gt;fetchMode. Legal modes are ADODB_FETCH_ASSOC and ADODB_FETCH_NUM. \r
-       For more info, see <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a>.</font></p>\r
-<p><font color="#000000">Returns the previous fetch mode, which could be false \r
-       if SetFetchMode( ) has not been called before.</font></p>\r
-<font color="#000000"> \r
-<p><b>CreateSequence<a name="createseq"></a>($seqName = 'adodbseq',$startID=1)</b></p>\r
-<p>Create a sequence. The next time GenID( ) is called, the value returned will \r
-       be $startID. Added in 2.60. \r
-<p><b>DropSequenceD<a name="dropseq"></a>($seqName = 'adodbseq')</b></p>\r
-<p>Delete a sequence. Added in 2.60. \r
-<p><b>GenID<a name="genid"></a>($seqName = 'adodbseq',$startID=1)</b></p>\r
-<p>Generate a sequence number . Works for interbase, \r
-       mysql, postgresql, oci8, oci8po, mssql, ODBC based (access,vfp,db2,etc) drivers \r
-       currently. Uses $seqName as the name of the sequence. GenID() will automatically \r
-       create the sequence for you if it does not exist (provided the userid has \r
-       permission to do so). Otherwise you will have to create the sequence yourself. \r
-<p> If your database driver emulates sequences, the name of the table is the sequence \r
-       name. The table has one column, "id" which should be of type integer, or if \r
-       you need something larger - numeric(16). \r
-<p> For ODBC and databases that do not support sequences natively (eg mssql, mysql), \r
-       we create a table for each sequence. If the sequence has not been defined \r
-       earlier, it is created with the starting value set in $startID.</p>\r
-<p>Note that the mssql driver's GenID() before 1.90 used to generate 16 byte GUID's.</p>\r
-<p><b>UpdateBlob<a name="updateblob"></a>($table,$column,$val,$where)</b></p>\r
-Allows you to store a blob (in $val) into $table into $column in a row at $where. \r
-<p> Usage: \r
-<p> \r
-<pre>\r
-       # for oracle\r
-       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, empty_blob())');\r
-       $conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');\r
-       \r
-       # non oracle databases\r
-       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
-       $conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');\r
-</pre>\r
-<p> Returns true if succesful, false otherwise. Supported by MySQL, PostgreSQL, \r
-       Oci8, Oci8po and Interbase drivers. Other drivers might work, depending on \r
-       the state of development.</p>\r
-<p>Note that when an Interbase blob is retrieved using SELECT, it still needs \r
-       to be decoded using $connection->DecodeBlob($blob); to derive the original \r
-       value in versions of PHP before 4.1.0. \r
-<p>For PostgreSQL, you can store your blob using blob oid's or as a bytea field. \r
-       You can use bytea fields but not blob oid's currently with UpdateBlob( ). \r
-       Conversely UpdateBlobFile( ) supports oid's, but not bytea data.<br>\r
-       <br>\r
-       If you do not pass in an oid, then UpdateBlob() assumes that you are storing \r
-       in bytea fields.\r
-<p><b>UpdateClob<a name="updateclob"></a>($table,$column,$val,$where)</b></p>\r
-Allows you to store a clob (in $val) into $table into $column in a row at $where. \r
-Similar to UpdateBlob (see above), but for Character Large OBjects. \r
-<p> Usage:\r
-<pre>\r
-       # for oracle\r
-       $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, empty_clob())');\r
-       $conn->UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');\r
-       \r
-       # non oracle databases\r
-       $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');\r
-       $conn->UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');\r
-</pre>\r
-<p><b>UpdateBlobFile<a name="updateblobfile"></a>($table,$column,$path,$where,$blobtype='BLOB')</b></p>\r
-<p>Similar to UpdateBlob, except that we pass in a file path to where the blob \r
-       resides.\r
-<p>For PostgreSQL, if you are using blob oid's, use this interface. This interface \r
-       does not support bytea fields.\r
-<p>Returns true if successful, false otherwise. \r
-<p><b>BlobEncode<a name="blobencode" id="blobencode"></a>($blob)</b> \r
-<p>Some databases require blob's to be encoded manually before upload. Note if \r
-       you use UpdateBlob( ) or UpdateBlobFile( ) the conversion is done automatically \r
-       for you and you do not have to call this function. For PostgreSQL, currently, \r
-       BlobEncode() can only be used for bytea fields.\r
-<p>Returns the encoded blob value.\r
-<p>Note that there is a connection property called <em>blobEncodeType</em> which \r
-       has 3 legal values: \r
-<p>false - no need to perform encoding or decoding.<br>\r
-       'I' - blob encoding required, and returned encoded blob is a numeric value \r
-       (no need to quote).<br>\r
-       'C' - blob encoding required, and returned encoded blob is a character value \r
-       (requires quoting).\r
-<p>This is purely for documentation purposes, so that programs that accept multiple \r
-       database drivers know what is the right thing to do when processing blobs.\r
-<p><strong>BlobDecode<a name="blobdecode"></a>($blob)</strong> \r
-</font><p><font color="#000000">Some databases require blob's to be decoded manually after doing a select statement. \r
-       If the database does not require decoding, then this function will return \r
-       the blob unchanged. Currently BlobDecode is only required for one database, \r
-       PostgreSQL, and only if you are using blob oid's (if you are using bytea fields, \r
-       we auto-decode for you).</font><font color="#000000">\r
-<pre>$rs = $db-&gt;Execute(&quot;select bloboid from postgres_table where id=$key&quot;);\r
-$blob = $db-&gt;BlobDecode( reset($rs-&gt;fields) );</pre>\r
-<p><b>Replace<a name="replace"></a>($table, $arrFields, $keyCols,$autoQuote=false)</b></p>\r
-<p>Try to update a record, and if the record is not found, an insert statement \r
-       is generated and executed. Returns 0 on failure, 1 if update statement worked, \r
-       2 if no record was found and the insert was executed successfully. This differs \r
-       from MySQL's replace which deletes the record and inserts a new record. This \r
-       also means you cannot update the primary key. The only exception to this is \r
-       Interbase and its derivitives, which uses delete and insert because of some \r
-       Interbase API limitations. \r
-<p>The parameters are $table which is the table name, the $keyCols which is an \r
-       associative array where the keys are the field names, and keyCols is the name \r
-       of the primary key, or an array of field names if it is a compound key. If \r
-       $autoQuote is set to true, then Replace() will quote all values that are non-numeric; \r
-       auto-quoting will not quote nulls. Note that auto-quoting will not work if \r
-       you use SQL functions or operators. \r
-<p>Examples: \r
-<pre>\r
-# single field primary key\r
-$ret = $db->Replace('atable', \r
-       array('id'=>1000,'firstname'=>'Harun','lastname'=>'Al-Rashid'),\r
-       'id',$autoquote = true);        \r
-# generates UPDATE atable SET firstname='Harun',lastname='Al-Rashid' WHERE id=1000\r
-# or INSERT INTO atable (id,firstname,lastname) VALUES (1000,'Harun','Al-Rashid')\r
-\r
-# compound key\r
-$ret = $db->Replace('atable2', \r
-       array('firstname'=>'Harun','lastname'=>'Al-Rashid', 'age' => 33, 'birthday' => 'null'),\r
-       array('lastname','firstname'),\r
-       $autoquote = true);\r
-\r
-# no auto-quoting\r
-$ret = $db->Replace('atable2', \r
-       array('firstname'=>"'Harun'",'lastname'=>"'Al-Rashid'", 'age' => 'null'),\r
-       array('lastname','firstname')); \r
-</pre>\r
-<p><b>GetUpdateSQL<a name="getupdatesql"></a>(&$rs, $arrFields, $forceUpdate=false,$magicq=false)</b></p>\r
-<p>Generate SQL to update a table given a recordset $rs, and the modified fields \r
-       of the array $arrFields (which must be an associative array holding the column \r
-       names and the new values) are compared with the current recordset. If $forceUpdate \r
-       is true, then we also generate the SQL even if $arrFields is identical to \r
-       $rs-&gt;fields. Requires the recordset to be associative. $magicq is used \r
-       to indicate whether magic quotes are enabled (see qstr()). The field names in the array \r
-       are case-insensitive.</p>\r
-       <p>Since 3.61, define('ADODB_FORCE_NULLS',1) and all PHP nulls will be auto-converted to SQL nulls.\r
-<p><b>GetInsertSQL<a name="getinsertsql"></a>(&$rs, $arrFields,$magicq=false)</b></p>\r
-<p>Generate SQL to insert into a table given a recordset $rs. Requires the query \r
-       to be associative. $magicq is used to indicate whether magic quotes are enabled \r
-       (for qstr()). The field names in the array are case-insensitive.</p>\r
-       \r
-<p>Since 3.61, define('ADODB_FORCE_NULLS',1) and all PHP nulls will be auto-converted \r
-  to SQL nulls. \r
-<p><b>PageExecute<a name="pageexecute"></a>($sql, $nrows, $page, $inputarr=false)</b> \r
-<p>Used for pagination of recordset. $page is 1-based. See <a href="#ex8">Example \r
-  8</a>.</p>\r
-</font> \r
-<p><font color="#000000"><b>CachePageExecute<a name="cachepageexecute"></a>($secs2cache, \r
-  $sql, $nrows, $page, $inputarr=false)</b> </font></p>\r
-<p><font color="#000000">Used for pagination of recordset. $page is 1-based. See \r
-  <a href="#ex8">Example 8</a>. Caching version of PageExecute.</font></p>\r
-<font color="#000000"> \r
-<p></p>\r
-<p><b>Close<a name="close"></a>( )</b></p>\r
-<p>Close the database connection. PHP4 proudly states that we no longer have to \r
-  clean up at the end of the connection because the reference counting mechanism \r
-  of PHP4 will automatically clean up for us.</p>\r
-  <p><b>StartTrans<a name="starttrans"></a>( )</b></p>\r
-  <p>Start a monitored transaction. As SQL statements are executed, ADOdb will monitor\r
-  for SQL errors, and if any are detected, when CompleteTrans() is called, we auto-rollback.\r
-  <p>\r
-  <p> To understand why StartTrans() is superior to BeginTrans(), \r
-  let us examine a few ways of using BeginTrans().\r
-  The following is the wrong way to use transactions: \r
-<pre>\r
-$DB->BeginTrans();\r
-$DB->Execute("update table1 set val=$val1 where id=$id");\r
-$DB->Execute("update table2 set val=$val2 where id=$id");\r
-$DB->CommitTrans();\r
-</pre>\r
-<p>because you perform no error checking. It is possible to update table1 and \r
-  for the update on table2 to fail. Here is a better way: \r
-<pre>\r
-$DB->BeginTrans();\r
-$ok = $DB->Execute("update table1 set val=$val1 where id=$id");\r
-if ($ok) $ok = $DB->Execute("update table2 set val=$val2 where id=$id");\r
-if ($ok) $DB->CommitTrans();\r
-else $DB->RollbackTrans();\r
-</pre>\r
-<p>Another way is (since ADOdb 2.0): \r
-<pre>\r
-$DB->BeginTrans();\r
-$ok = $DB->Execute("update table1 set val=$val1 where id=$id");\r
-if ($ok) $ok = $DB->Execute("update table2 set val=$val2 where id=$id");\r
-$DB->CommitTrans($ok);\r
-</pre>\r
-<p> Now it is a headache monitoring $ok all over the place. StartTrans() is an\r
-improvement because it monitors all SQL errors for you. This is particularly\r
-useful if you are calling black-box functions in which SQL queries might be executed.\r
- Also all BeginTrans, CommitTrans and RollbackTrans calls inside a StartTrans block \r
-  will be disabled, so even if the black box function does a commit, it will be ignored.\r
-<pre>\r
-$DB->StartTrans();\r
-CallBlackBox();\r
-$DB->Execute("update table1 set val=$val1 where id=$id");\r
-$DB->Execute("update table2 set val=$val2 where id=$id");\r
-$DB->CompleteTrans($ok);\r
-</pre>\r
-<p>Note that a StartTrans blocks are nestable, the inner blocks are ignored.\r
- <p><b>CompleteTrans<a name="completetrans"></a>($autoComplete=true)</b></p>\r
-  <p>Complete a transaction called with StartTrans(). This function monitors\r
-  for SQL errors, and will commit if no errors have occured, otherwise it will rollback. \r
-  Returns true on commit, false on rollback. If the parameter $autoComplete is true\r
-  monitor sql errors and commit and rollback as appropriate. Set $autoComplete to false \r
-  to force rollback even if no SQL error detected.\r
-  <p><b>FailTrans<a name="failtrans"></a>( )</b></p>\r
-  <p>Fail a transaction started with StartTrans(). The rollback will only occur when\r
-  CompleteTrans() is called.\r
-    <p><b>HasFailedTrans<a name="hasfailedtrans"></a>( )</b></p>\r
-       <p>Check whether smart transaction has failed, \r
-       eg. returns true if there was an error in SQL execution or FailTrans() was called.\r
-       If not within smart transaction, returns false.\r
-<p><b>BeginTrans<a name="begintrans"></a>( )</b></p>\r
-<p>Begin a transaction. Turns off autoCommit. Returns true if successful. Some \r
-  databases will always return false if transaction support is not available. \r
-   Any open transactions will be rolled back when the connection is closed. Among the\r
-   databases that support transactions are Oracle, PostgreSQL, Interbase, MSSQL, certain\r
-    versions of MySQL, DB2, Informix, Sybase, etc.</p>\r
- <p>Note that <a href=#starttrans>StartTrans()</a> and CompleteTrans() is a superior method of \r
- handling transactions, available since ADOdb 3.40. For a explanation, see the <a href=#starttrans>StartTrans()</a> documentation.\r
-\r
-<p>You can also use the ADOdb <a href=#errorhandling>error handler</a> to die \r
-  and rollback your transactions for you transparently. Some buggy database extensions \r
-  are known to commit all outstanding tranasactions, so you might want to explicitly \r
-  do a $DB->RollbackTrans() in your error handler for safety. \r
- <h4>Detecting Transactions</h4>\r
- <p>Since ADOdb 2.50, you are able to detect when you are inside a transaction. Check\r
- that $connection->transCnt > 0. This variable is incremented whenever BeginTrans() is called,\r
- and decremented whenever RollbackTrans() or CommitTrans() is called.\r
-<p><b>CommitTrans<a name="committrans"></a>($ok=true)</b></p>\r
-<p>End a transaction successfully. Returns true if successful. If the database \r
-  does not support transactions, will return true also as data is always committed. \r
-</p>\r
-<p>If you pass the parameter $ok=false, the data is rolled back. See example in \r
-  BeginTrans().</p>\r
-<p><b>RollbackTrans<a name="rollbacktrans"></a>( )</b></p>\r
-<p>End a transaction, rollback all changes. Returns true if successful. If the \r
-  database does not support transactions, will return false as data is never rollbacked. \r
-</p>\r
-</font><font color="#000000"> \r
-<p><b>GetAssoc<a name=getassoc1></a>($sql,$inputarr=false,$force_array=false,$first2cols=false)</b></p>\r
-<p>Returns an associative array for the given query $sql with optional bind parameters \r
-  in $inputarr. If the number of columns returned is greater to two, a 2-dimensional \r
-  array is returned, with the first column of the recordset becomes the keys \r
-  to the rest of the rows. If the columns is equal to two, a 1-dimensional array \r
-  is created, where the the keys directly map to the values (unless $force_array \r
-  is set to true, when an array is created for each value).\r
-<p> <font color="#000000">Examples:<a name=getassocex></a></font></p>\r
-</font>\r
-<p><font color="#000000">We have the following data in a recordset:</font></p>\r
-<p><font color="#000000">row1: Apple, Fruit, Edible<br>\r
-  row2: Cactus, Plant, Inedible<br>\r
-  row3: Rose, Flower, Edible</font></p>\r
-<p><font color="#000000">GetAssoc will generate the following 2-dimensional associative \r
-  array:</font></p>\r
-<p><font color="#000000">Apple =&gt; array[Fruit, Edible]<br>\r
-  Cactus =&gt; array[Plant, Inedible]<br>\r
-  Rose =&gt; array[Flower,Edible]</font></p>\r
-<p><font color="#000000">If the dataset is:</font></p>\r
-<p><font color="#000000"><font color="#000000"><font color="#000000">row1: Apple, \r
-  Fruit<br>\r
-  row2: Cactus, Plant<br>\r
-  row3: Rose, Flower</font> </font></font></p>\r
-<p><font color="#000000"><font color="#000000">GetAssoc will generate the following \r
-  1-dimensional associative array (with $force_array==false):</font></font></p>\r
-<p><font color="#000000">Apple =&gt; Fruit</font><br>\r
-  Cactus=&gt;Plant<br>\r
-  Rose=&gt;Flower <font color="#000000"><font color="#000000"> </font></font><font color="#000000"><font color="#000000"></font></font></p>\r
-<p><font color="#000000">The function returns:</font></p>\r
-<p><font color="#000000">The associative array, or false if an error occurs.</font></p>\r
-<font color="#000000">\r
-<p><b>CacheGetAssoc<a name="cachegetassoc"></a>([$secs2cache,] $sql,$inputarr=false,$force_array=false,$first2cols=false)</b></p>\r
-</font><font color="#000000"> \r
-<p>Caching version of <a href=#getassoc1>GetAssoc</a> function above.\r
-<p><b>GetOne<a name="getone"></a>($sql,$inputarr=false)</b></p>\r
-<p>Executes the SQL and returns the first field of the first row. The recordset \r
-  and remaining rows are discarded for you automatically. If an error occur, false \r
-  is returned.</p>\r
-<p><b>GetRow<a name="getrow"></a>($sql,$inputarr=false)</b></p>\r
-<p>Executes the SQL and returns the first row as an array. The recordset and remaining \r
-  rows are discarded for you automatically. If an error occurs, false is returned.</p>\r
-<p><b>GetAll<a name="getall"></a>($sql)</b></p>\r
-</font>\r
-<p><font color="#000000">Executes the SQL and returns the all the rows as a 2-dimensional \r
-  array. The recordset is discarded for you automatically. If an error occurs, \r
-  false is returned.</font></p>\r
- <p><b>GetCol<a name="getcol"></a>($sql,$inputarr=false,$trim=false)</b></p>\r
-\r
-<p><font color="#000000">Executes the SQL and returns all elements of the first column as a \r
-1-dimensional array. The recordset is discarded for you automatically. If an error occurs, \r
-  false is returned.</font></p>\r
-<p><font color="#000000"><b>CacheGetOne<a name="cachegetone"></a>([$secs2cache,] \r
-  $sql,$inputarr=false), CacheGetRow<a name="cachegetrow"></a>([$secs2cache,] $sql,$inputarr=false), CacheGetAll<a name="cachegetall"></a>([$secs2cache,] \r
-  $sql,$inputarr=false), CacheGetCol<a name="cachegetcol"></a>([$secs2cache,] \r
-  $sql,$inputarr=false,$trim=false)</b></font></p>\r
-<font color="#000000"> \r
-<p>Similar to above Get* functions, except that the recordset is serialized and \r
-  cached in the $ADODB_CACHE_DIR directory for $secs2cache seconds. Good for speeding \r
-  up queries on rarely changing data. Note that the $secs2cache parameter is optional. \r
-  If omitted, we use the value in $connection-&gt;cacheSecs (default is 3600 seconds, \r
-  or 1 hour).</p>\r
-<p><b>Prepare<a name="prepare"></a>($sql )</b></p>\r
-</font> \r
-<p><font color="#000000">Prepares (compiles) an SQL query for repeated execution. Bind parameters\r
-are denoted by ?, except for the oci8 driver, which uses the traditional Oracle :varname\r
-convention. \r
-  </font></p>\r
-<p><font color="#000000">Returns an array containing the original sql statement \r
-  in the first array element; the remaining elements of the array are driver dependent. \r
-  If there is an error, or we are emulating Prepare( ), we return the original \r
-  $sql string. This is because all error-handling has been centralized in Execute( \r
-  ).</font></p>\r
-<p><font color="#000000">Prepare( ) cannot be used with functions that use SQL \r
-  query rewriting techniques, e.g. PageExecute( ) and SelectLimit( ).</font></p>\r
-<p>Example:</p>\r
-<pre><font color="#000000">$stmt = $DB-&gt;Prepare('insert into table (col1,col2) values (?,?)');\r
-for ($i=0; $i &lt; $max; $i++)<br></font>      $DB-&gt;<font color="#000000">Execute($stmt,array((string) rand(), $i));\r
-</font></pre>\r
-<font color="#000000"> \r
-<p>Also see InParameter(), OutParameter() and PrepareSP() below. Only supported internally by interbase, \r
-  oci8 and selected ODBC-based drivers, otherwise it is emulated. There is no \r
-  performance advantage to using Prepare() with emulation. \r
-<p> Important: Due to limitations or bugs in PHP, if you are getting errors when \r
-  you using prepared queries, try setting $ADODB_COUNTRECS = false before preparing. \r
-  This behaviour has been observed with ODBC. \r
-<p><b>IfNull<a name="ifnull"></a>($field, $nullReplacementValue)</b></p>\r
-<p>Portable IFNULL function (NVL in Oracle). Returns a string that represents \r
-  the function that checks whether a $field is null for the given database, and \r
-  if null, change the value returned to $nullReplacementValue. Eg.</p>\r
-<pre>$sql = <font color="#993300">'SELECT '</font>.$db-&gt;IfNull('name', <font color="#993300">&quot;'- unknown -'&quot;</font>).<font color="#993300"> ' FROM table'</font>;</pre>\r
-\r
-<p><b>length<a name="length"></a></b></p>\r
-<p>This is not a function, but a property. Some databases have "length" and others "len"\r
-as the function to measure the length of a string. To use this property:\r
-<pre>\r
-  $sql = <font color="#993300">"SELECT "</font>.$db->length.<font color="#993300">"(field) from table"</font>;\r
-  $rs = $db->Execute($sql);\r
-</pre>\r
-\r
-<p><b>random<a name="random"></a></b></p>\r
-<p>This is not a function, but a property. This is a string that holds the sql to\r
-generate a random number between 0.0 and 1.0 inclusive.\r
-\r
-<p><b>substr<a name="substr"></a></b></p>\r
-<p>This is not a function, but a property. Some databases have "substr" and others "substring"\r
-as the function to retrieve a sub-string. To use this property:\r
-<pre>\r
-  $sql = <font color="#993300">"SELECT "</font>.$db->substr.<font color="#993300">"(field, $offset, $length) from table"</font>;\r
-  $rs = $db->Execute($sql);\r
-</pre>\r
-<p>For all databases, the 1st parameter of <i>substr</i> is the field, the 2nd is the\r
-offset (1-based) to the beginning of the sub-string, and the 3rd is the length of the sub-string.\r
-\r
-\r
-<p><b>Param<a name="param"></a>($name )</b></p>\r
-<p>Generates a bind placeholder portably. For most databases, the bind placeholder \r
-  is "?". However some databases use named bind parameters such as Oracle, eg \r
-  ":somevar". This allows us to portably define an SQL statement with bind parameters: \r
-<pre><font color="#000000">$sql = <font color="#993300">'insert into table (col1,col2) values ('</font>.$DB-&gt;Param('a').<font color="#993300">','</font>.$DB-&gt;Param('b').<font color="#993300">')'</font>;\r
-<font color="#006600"># generates 'insert into table (col1,col2) values (?,?)'\r
-# or        'insert into table (col1,col2) values (:a,:b)</font>'\r
-$stmt = $DB-&gt;Prepare($sql);\r
-$stmt = $DB-&gt;Execute($stmt,array('one','two'));\r
-</font></pre>\r
-<font color="#000000"> \r
-<p></p>\r
-<p><b>PrepareSP</b><b><a name="preparesp"></a></b><b>($sql)</b></p>\r
-<p>When calling stored procedures in mssql and oci8 (oracle), and you might want \r
-  to directly bind to parameters that return values, or for special LOB handling. \r
-  PrepareSP() allows you to do so. \r
-<p>Returns the same array or $sql string as Prepare( ) above. If you do not need \r
-  to bind to return values, you should use Prepare( ) instead.</p>\r
-<p>For examples of usage of PrepareSP( ), see InParameter( ) below. \r
-<p>Note: in the mssql driver, preparing stored procedures requires a special function \r
-  call, mssql_init( ), which is called by this function. PrepareSP( ) is available \r
-  in all other drivers, and is emulated by calling Prepare( ). </p>\r
-<p><b> InParameter<a name="inparameter"></a>($stmt, $var, $name,\r
-  $maxLen = 4000, $type = false )</b></p>\r
-Binds a PHP variable as input to a stored procedure variable. The parameter <i>$stmt</i>\r
- is the value returned by PrepareSP(), <i>$var</i> is the PHP variable you want to bind, $name\r
- is the name of the stored procedure variable. Optional is <i>$maxLen</i>, the maximum length of the\r
- data to bind, and $type which is database dependant. \r
- Consult <a href=http://php.net/mssql_bind>mssql_bind</a> and <a href=http://php.net/ocibindbyname>ocibindbyname</a> docs\r
-  at php.net for more info on legal values for $type. \r
- <p>\r
-InParameter() is a wrapper function that calls Parameter() with $isOutput=false. \r
-The advantage of this function is that it is self-documenting, because\r
-the $isOutput parameter is no longer needed.  Only for mssql \r
-  and oci8 currently.\r
-  <p>Here is an example using oci8:\r
-  <pre><font color="green"># For oracle, Prepare and PrepareSP are identical</font>\r
-$stmt = $db-&gt;PrepareSP(\r
-       <font color="#993300">&quot;declare RETVAL integer; \r
-       begin\r
-       :RETVAL := </font><font color="#993300">SP_RUNSOMETHING</font><font color="#993300">(:myid,:group);\r
-       end;&quot;</font>);\r
-$db-&gt;InParameter($stmt,$id,'myid');\r
-$db-&gt;InParameter($stmt,$group,'group',64);\r
-$db-&gt;OutParameter($stmt,$ret,'RETVAL');<br>$db-&gt;Execute($stmt);\r
-</pre>\r
-<p> The same example using mssql:</p>\r
-</font> \r
-<pre><font color="#000000"><font color="green"># @RETVAL = SP_RUNSOMETHING @myid,@group</font>\r
-$stmt = $db-&gt;PrepareSP(<font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font>); <br><font color="green"># note that the parameter name does not have @ in front!</font>\r
-$db-&gt;InParameter($stmt,$id,'myid');\r
-$db-&gt;InParameter($stmt,$group,'group',64);\r
-<font color="green"># return value in mssql - RETVAL is hard-coded name</font> \r
-$db-&gt;OutParameter($stmt,$ret,'RETVAL');\r
-$db-&gt;Execute($stmt); </font></pre>\r
-\r
-<p>Note that the only difference between the oci8 and mssql implementations is $sql.</p>\r
-  <p>\r
- If $type parameter is set to false, in mssql, $type will be dynamicly determined \r
-based on the type of the PHP variable passed <font face="Courier New, Courier, mono">(string \r
-=&gt; SQLCHAR, boolean =&gt;SQLINT1, integer =&gt;SQLINT4 or float/double=&gt;SQLFLT8)</font>.\r
-<p> \r
-In oci8, $type can be set to OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), \r
-OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID). To \r
-pass in a null, use<font face="Courier New, Courier, mono"> $db-&gt;Parameter($stmt, \r
-$null=null, 'param')</font>. \r
-  <p><b> OutParameter<a name="outparameter"></a>($stmt, $var, $name, \r
-  $maxLen = 4000, $type = false )</b></p>\r
-  Binds a PHP variable as output from a stored procedure variable. The parameter <i>$stmt</i>\r
- is the value returned by PrepareSP(), <i>$var</i> is the PHP variable you want to bind, <i>$name</i>\r
- is the name of the stored procedure variable. Optional is <i>$maxLen</i>, the maximum length of the\r
- data to bind, and <i>$type</i> which is database dependant. \r
-  <p>\r
-  OutParameter() is a wrapper function that calls Parameter() with $isOutput=true. \r
-  The advantage of this function is that it is self-documenting, because\r
-the $isOutput parameter is no longer needed.  Only for mssql \r
-  and oci8 currently.\r
-<p>\r
-For an example, see <a href=#inparameter>InParameter</a>.\r
-\r
-<p><b> Parameter<a name="parameter"></a>($stmt, $var, $name, $isOutput=false, \r
-  $maxLen = 4000, $type = false )</b></p>\r
-<p>Note: This function is deprecated, because of the new InParameter() and OutParameter() functions.\r
-These are superior because they are self-documenting, unlike Parameter().\r
-<p>Adds a bind parameter suitable for return values or special data handling (eg. \r
-  LOBs) after a statement has been prepared using PrepareSP(). Only for mssql \r
-  and oci8 currently. The parameters are:<br>\r
-  <br>\r
-  $<i><b>stmt</b></i> Statement returned by Prepare() or PrepareSP().<br>\r
-  $<i><b>var</b></i> PHP variable to bind to. Make sure you pre-initialize it!<br>\r
-  $<i><b>name</b></i> Name of stored procedure variable name to bind to.<br>\r
-  [$<i><b>isOutput</b></i>] Indicates direction of parameter 0/false=IN 1=OUT \r
-  2= IN/OUT. This is ignored in oci8 as this driver auto-detects the direction.<br>\r
-  [$<b>maxLen</b>] Maximum length of the parameter variable.<br>\r
-  [$<b>type</b>] Consult <a href="http://php.net/mssql_bind">mssql_bind</a> and \r
-  <a href="http://php.net/ocibindbyname">ocibindbyname</a> docs at php.net for \r
-  more info on legal values for type.</p>\r
-<p>Lastly, in oci8, bind parameters can be reused without calling PrepareSP( ) \r
-  or Parameters again. This is not possible with mssql. An oci8 example:</p>\r
-<pre>$id = 0; $i = 0;\r
-$stmt = $db-&gt;PrepareSP( <font color="#993300">&quot;update table set val=:i where id=:id&quot;</font>);\r
-$db-&gt;Parameter($stmt,$id,'id');\r
-$db-&gt;Parameter($stmt,$i, 'i');\r
-for ($cnt=0; $cnt &lt; 1000; $cnt++) {\r
-       $id = $cnt; <br>        $i = $cnt * $cnt; <font color="green"># works with oci8!</font>\r
-       $db-&gt;Execute($stmt); <br>}</pre>\r
-<p><b>Bind<a name="bind"></a>($stmt, $var, $size=4001, $type=false, $name=false)</b></p>\r
-</font> \r
-<p><font color="#000000">This is a low-level function supported only by the oci8 \r
-  driver. <b>Avoid using</b> unless you only want to support Oracle. The Parameter( \r
-  ) function is the recommended way to go with bind variables.</font></p>\r
-<p><font color="#000000">Bind( ) allows you to use bind variables in your sql \r
-  statement. This binds a PHP variable to a name defined in an Oracle sql statement \r
-  that was previously prepared using Prepare(). Oracle named variables begin with \r
-  a colon, and ADOdb requires the named variables be called :0, :1, :2, :3, etc. \r
-  The first invocation of Bind() will match :0, the second invocation will match \r
-  :1, etc. Binding can provide 100% speedups for insert, select and update statements. \r
-  </font></p>\r
-<p>The other variables, $size sets the buffer size for data storage, $type is \r
-  the optional descriptor type OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), \r
-  OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID). \r
-  Lastly, instead of using the default :0, :1, etc names, you can define your \r
-  own bind-name using $name. \r
-<p><font color="#000000">The following example shows 3 bind variables being used: \r
-  p1, p2 and p3. These variables are bound to :0, :1 and :2.</font></p>\r
-<pre>$stmt = $DB-&gt;Prepare(&quot;insert into table (col0, col1, col2) values (:0, :1, :2)&quot;);\r
-$DB-&gt;Bind($stmt, $p1);\r
-$DB-&gt;Bind($stmt, $p2);\r
-$DB-&gt;Bind($stmt, $p3);\r
-for ($i = 0; $i &lt; $max; $i++) { \r
-   $p1 = ?; $p2 = ?; $p3 = ?;\r
-   $DB-&gt;Execute($stmt);\r
-}</pre>\r
-<p>You can also use named variables:</p>\r
-<pre>\r
-$stmt = $DB-&gt;Prepare(&quot;insert into table (col0, col1, col2) values (:name0, :name1, :name2)&quot;);\r
-$DB-&gt;Bind($stmt, $p1, &quot;name0&quot;);\r
-$DB-&gt;Bind($stmt, $p2, &quot;name1&quot;);\r
-$DB-&gt;Bind($stmt, $p3, &quot;name2&quot;);\r
-for ($i = 0; $i &lt; $max; $i++) { \r
-   $p1 = ?; $p2 = ?; $p3 = ?;\r
-   $DB-&gt;Execute($stmt);\r
-}</pre>\r
-<p><b>LogSQL($enable=true)<a name=logsql></a></b></p>\r
-Call this method to install a SQL logging and timing function (using fnExecute). \r
-Then all SQL statements are logged into an adodb_logsql table in a database. If \r
-the adodb_logsql table does not exist, ADOdb will create the table if you have \r
-the appropriate permissions. Returns the previous logging value (true for enabled, \r
-false for disabled). Here are samples of the DDL for selected databases: \r
-<p> \r
-<pre>\r
-               <b>mysql:</b>\r
-               CREATE TABLE adodb_logsql (\r
-                 created datetime NOT NULL,\r
-                 sql0 varchar(250) NOT NULL,\r
-                 sql1 text NOT NULL,\r
-                 params text NOT NULL,\r
-                 tracer text NOT NULL,\r
-                 timer decimal(16,6) NOT NULL\r
-               )\r
-               \r
-               <b>postgres:</b>\r
-               CREATE TABLE adodb_logsql (\r
-                 created timestamp NOT NULL,\r
-                 sql0 varchar(250) NOT NULL,\r
-                 sql1 text NOT NULL,\r
-                 params text NOT NULL,\r
-                 tracer text NOT NULL,\r
-                 timer decimal(16,6) NOT NULL\r
-               )\r
-               \r
-               <b>mssql:</b>\r
-               CREATE TABLE adodb_logsql (\r
-                 created datetime NOT NULL,\r
-                 sql0 varchar(250) NOT NULL,\r
-                 sql1 varchar(4000) NOT NULL,\r
-                 params varchar(3000) NOT NULL,\r
-                 tracer varchar(500) NOT NULL,\r
-                 timer decimal(16,6) NOT NULL\r
-               )\r
-               \r
-               <b>oci8:</b>\r
-               CREATE TABLE adodb_logsql (\r
-                 created date NOT NULL,\r
-                 sql0 varchar(250) NOT NULL,\r
-                 sql1 varchar(4000) NOT NULL,\r
-                 params varchar(4000),\r
-                 tracer varchar(4000),\r
-                 timer decimal(16,6) NOT NULL\r
-               )\r
-</pre>\r
-Usage: \r
-<pre>\r
-       $conn->LogSQL(); // turn on logging\r
-         :\r
-       $conn->Execute(...);\r
-         :\r
-       $conn->LogSQL(false); // turn off logging\r
-       \r
-       # output summary of SQL logging results\r
-       $perf = NewPerfMonitor($conn);\r
-       echo $perf->SuspiciousSQL();\r
-       echo $perf->ExpensiveSQL();\r
-</pre>\r
-<p>One limitation of logging is that rollback also prevents SQL from being logged.\r
-<p>\r
-If you prefer to use another name for the table used to store the SQL, you can override it by calling \r
-adodb_perf::table($tablename), where $tablename is the new table name (you will still need to manually\r
-create the table yourself). An example:\r
-<pre>\r
-       include('adodb.inc.php');\r
-       include('adodb-perf.inc.php');\r
-       adodb_perf::table('my_logsql_table');\r
-</pre>\r
-Also see <a href=docs-perf.htm>Performance Monitor</a>. \r
-<p><font color="#000000"><b>fnExecute and fnCacheExecute properties<a name="fnexecute" id="fnexecute"></a></b></font></p>\r
-<p>These two properties allow you to define bottleneck functions for all sql statements \r
-  processed by ADOdb. This allows you to perform statistical analysis and query-rewriting \r
-  of your sql. \r
-<p><b>Examples of fnExecute</b></p>\r
-<p>Here is an example of using fnExecute, to count all cached queries and non-cached \r
-  queries, you can do this:</p>\r
-<pre><font color="#006600"># $db is the connection object</font>\r
-function CountExecs($db, $sql, $inputarray)\r
-{\r
-global $EXECS;\r
-\r
-if (!is_array(inputarray)) $EXECS++;\r
-<font color="#006600"># handle 2-dimensional input arrays</font>\r
-else if (is_array(reset($inputarray))) $EXECS += sizeof($inputarray);\r
-else $EXECS++;\r
-}\r
-\r
-<font color="#006600"># $db is the connection object</font>\r
-function CountCachedExecs($db, $secs2cache, $sql, $inputarray)\r
-{<br>global $CACHED; $CACHED++;\r
-}\r
-<br>$db = NewADOConnection('mysql');\r
-$db-&gt;Connect(...);\r
-$db-&gt;<strong>fnExecute</strong> = 'CountExecs';\r
-$db-&gt;<strong>fnCacheExecute</strong> = 'CountCachedExecs';\r
- :\r
- :<br><font color="#006600"># After many sql statements:</font>`\r
-printf(&quot;&lt;p&gt;Total queries=%d; total cached=%d&lt;/p&gt;&quot;,$EXECS+$CACHED, $CACHED);\r
-</pre>\r
-<p>The fnExecute function is called before the sql is parsed and executed, so \r
-  you can perform a query rewrite. If you are passing in a prepared statement, \r
-  then $sql is an array (see <a href="#prepare">Prepare</a>). The fnCacheExecute \r
-  function is only called if the recordset returned was cached.<font color="#000000"> \r
-  The function parameters match the Execute and CacheExecute functions respectively, \r
-  except that $this (the connection object) is passed as the first parameter.</font></p>\r
-<p>Since ADOdb 3.91, the behaviour of fnExecute varies depending on whether the \r
-  defined function returns a value. If it does not return a value, then the $sql \r
-  is executed as before. This is useful for query rewriting or counting sql queries. \r
-<p> On the other hand, you might want to replace the Execute function with one \r
-  of your own design. If this is the case, then have your function return a value. \r
-  If a value is returned, that value is returned immediately, without any further \r
-  processing. This is used internally by ADOdb to implement LogSQL() functionality. \r
-<p> <font color="#000000"> \r
-<hr>\r
-<h3>ADOConnection Utility Functions</h3>\r
-<p><b>BlankRecordSet<a name="blankrecordset"></a>([$queryid])</b></p>\r
-<p>No longer available - removed since 1.99.</p>\r
-<p><b>Concat<a name="concat"></a>($s1,$s2,....)</b></p>\r
-<p>Generates the sql string used to concatenate $s1, $s2, etc together. Uses the \r
-  string in the concat_operator field to generate the concatenation. Override \r
-  this function if a concatenation operator is not used, eg. MySQL.</p>\r
-<p>Returns the concatenated string.</p>\r
-<p><b>DBDate<a name="dbdate"></a>($date)</b></p>\r
-<p>Format the $<b>date</b> in the format the database accepts. This is used in \r
-  INSERT/UPDATE statements; for SELECT statements, use <a href="#sqldate">SQLDate</a>. \r
-  The $<b>date</b> parameter can be a Unix integer timestamp or an ISO format \r
-  Y-m-d. Uses the fmtDate field, which holds the format to use. If null or false \r
-  or '' is passed in, it will be converted to an SQL null.</p>\r
-<p>Returns the date as a quoted string.</p>\r
-<p><b>DBTimeStamp<a name="dbtimestamp"></a>($ts)</b></p>\r
-<p>Format the timestamp $<b>ts</b> in the format the database accepts; this can \r
-  be a Unix integer timestamp or an ISO format Y-m-d H:i:s. Uses the fmtTimeStamp \r
-  field, which holds the format to use. If null or false or '' is passed in, it \r
-  will be converted to an SQL null.</p>\r
-<p>Returns the timestamp as a quoted string.</p>\r
-<p><b>qstr<a name="qstr"></a>($s,[$magic_quotes_enabled</b>=false]<b>)</b></p>\r
-<p>Quotes a string to be sent to the database. The $<b>magic_quotes_enabled</b> \r
-  parameter may look funny, but the idea is if you are quoting a string extracted \r
-  from a POST/GET variable, then pass get_magic_quotes_gpc() as the second parameter. \r
-  This will ensure that the variable is not quoted twice, once by <i>qstr</i> \r
-  and once by the <i>magic_quotes_gpc</i>.</p>\r
-<p>Eg.<font face="Courier New, Courier, mono"> $s = $db-&gt;qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());</font></p>\r
-<p>Returns the quoted string.</p>\r
-<p><b>Quote<a name="quote"></a>($s)</b></p>\r
-<p>Quotes the string $s, escaping the database specific quote character as appropriate. \r
-  Formerly checked magic quotes setting, but this was disabled since 3.31 for \r
-  compatibility with PEAR DB. \r
-<p><b>Affected_Rows<a name="affected_rows"></a>( )</b></p>\r
-<p>Returns the number of rows affected by a update or delete statement. Returns \r
-  false if function not supported.</p>\r
-<p>Not supported by interbase/firebird currently. </p>\r
-<p><b>Insert_ID<a name="inserted_id"></a>( )</b></p>\r
-<p>Returns the last autonumbering ID inserted. Returns false if function not supported. \r
-</p>\r
-<p>Only supported by databases that support auto-increment or object id's, such \r
-  as PostgreSQL, MySQL and MS SQL Server currently. PostgreSQL returns the OID, which \r
-  can change on a database reload.</p>\r
-<p><b>RowLock<a name="rowlock"></a>($table,$where)</b></p>\r
-<p>Lock a table row for the duration of a transaction. For example to lock record $id in table1:\r
-<pre>\r
-       $DB->StartTrans();\r
-       $DB->RowLock("table1","rowid=$id");\r
-       $DB->Execute($sql1);\r
-       $DB->Execute($sql2);\r
-       $DB->CompleteTrans();\r
-</pre>\r
-<p>Supported in db2, interbase, informix, mssql, oci8, postgres, sybase.\r
-<p><b>MetaDatabases<a name="metadatabases"></a>()</b></p>\r
-<p>Returns a list of databases available on the server as an array. You have to \r
-  connect to the server first. Only available for ODBC, MySQL and ADO.</p>\r
-<p><b>MetaTables<a name="metatables"></a>($ttype = false, $showSchema = false, \r
-  $mask=false)</b></p>\r
-<p>Returns an array of tables and views for the current database as an array. \r
-  The array should exclude system catalog tables if possible. To only show tables, \r
-  use $db->MetaTables('TABLES'). To show only views, use $db->MetaTables('VIEWS'). \r
-  The $showSchema parameter currently works only for DB2, and when set to true, \r
-  will add the schema name to the table, eg. "SCHEMA.TABLE". </p>\r
-<p>You can define a mask for matching. For example, setting $mask = 'TMP%' will \r
-  match all tables that begin with 'TMP'. Currently only mssql, oci8, odbc_mssql \r
-  and postgres* support $mask. \r
-<p><b>MetaColumns<a name="metacolumns"></a>($table,$toupper=true)</b></p>\r
-<p>Returns an array of ADOFieldObject's, one field object for every column of \r
-  $table. A field object is a class instance with (name, type, max_length) defined.\r
-  Currently Sybase does not recognise date types, and ADO cannot identify \r
-  the correct data type (so we default to varchar).   \r
- <p> The $toupper parameter determines whether we uppercase the table name \r
- (required for some databases).\r
- <p>For schema support, pass in the $table parameter, "$schema.$tablename". This is only\r
- supported for selected databases.\r
-<p><b>MetaColumnNames<a name="metacolumnames"></a>($table)</b></p>\r
-<p>Returns an array of column names for $table. \r
-<p><font color="#000000"><b>MetaPrimaryKeys<a name="metaprimarykeys"></a>($table, \r
-  $owner=false)</b></font></font> \r
-<p><font color="#000000">Returns an array containing column names that are the \r
-  primary keys of $table. Supported by mysql, odbc (including db2, odbc_mssql, \r
-  etc), mssql, postgres, interbase/firebird, oci8 currently. </font><font color="#000000"> \r
-<p>Views (and some tables) have primary keys, but sometimes this information is not available from the\r
-database. You can define a function  ADODB_View_PrimaryKeys($databaseType, $database, $view, $owner) that\r
-should return an array containing the fields that make up the primary key. If that function exists,\r
-it will be called when MetaPrimaryKeys() cannot find a primary key for a table or view.\r
-<pre>\r
-// In this example: dbtype = 'oci8', $db = 'mydb', $view = 'dataView', $owner = false \r
-function ADODB_View_PrimaryKeys($dbtype,$db,$view,$owner)\r
-{\r
-       switch(strtoupper($view)) {\r
-       case 'DATAVIEW': return array('DATAID');\r
-       default: return false;\r
-       }\r
-}\r
-\r
-$db = NewADOConnection('oci8');\r
-$db->Connect('localhost','root','','mydb'); \r
-$db->MetaPrimaryKeys('dataView');\r
-</pre>\r
-<p><font color="#000000"><b>ServerInfo<a name="serverinfo" id="serverinfo"></a>($table)</b></font></font> \r
-<p><font color="#000000">Returns an array of containing two elements 'description' \r
-  and 'version'. The 'description' element contains the string description of \r
-  the database. The 'version' naturally holds the version number (which is also \r
-  a string).</font><font color="#000000"> \r
-<p><b>MetaForeignKeys<a name="metaforeignkeys"></a>($table, $owner=false, $upper=false)</b> \r
-<p>Returns an associate array of foreign keys, or false if not supported. For \r
-  example, if table employee has a foreign key where employee.deptkey points to \r
-  dept_table.deptid, and employee.posn=posn_table.postionid and employee.poscategory=posn_table.category, \r
-  then $conn->MetaForeignKeys('employee') will return \r
-<pre>\r
-       array(\r
-               'dept_table' => array('deptkey=deptid'),\r
-               'posn_table' => array('posn=positionid','poscategory=category')\r
-       )\r
-</pre>\r
-<p>The optional schema or owner can be defined in $owner. If $upper is true, then \r
-  the table names (array keys) are upper-cased. \r
-<hr>\r
-<h2>ADORecordSet<a name="adorecordset"></a></h2>\r
-<p>When an SQL statement successfully is executed by <font face="Courier New, Courier, mono">ADOConnection-&gt;Execute($sql),</font>an \r
-  ADORecordSet object is returned. This object contains a virtual cursor so we \r
-  can move from row to row, functions to obtain information about the columns \r
-  and column types, and helper functions to deal with formating the results to \r
-  show to the user.</p>\r
-<h3>ADORecordSet Fields</h3>\r
-<p><b>fields: </b>Array containing the current row. This is not associative, but \r
-  is an indexed array from 0 to columns-1. See also the function <b><a href="#fields">Fields</a></b>, \r
-  which behaves like an associative array.</p>\r
-<p><b>dataProvider</b>: The underlying mechanism used to connect to the database. \r
-  Normally set to <b>native</b>, unless using <b>odbc</b> or <b>ado</b>.</p>\r
-<p><b>blobSize</b>: Maximum size of a char, string or varchar object before it \r
-  is treated as a Blob (Blob's should be shown with textarea's). See the <a href="#metatype">MetaType</a> \r
-  function.</p>\r
-<p><b>sql</b>: Holds the sql statement used to generate this record set.</p>\r
-<p><b>canSeek</b>: Set to true if Move( ) function works.</p>\r
-<p><b>EOF</b>: True if we have scrolled the cursor past the last record.</p>\r
-<h3>ADORecordSet Functions</h3>\r
-<p><b>ADORecordSet( )</b></p>\r
-<p>Constructer. Normally you never call this function yourself.</p>\r
-<p><b>GetAssoc<a name="getassoc"></a>([$force_array])</b></p>\r
-<p>Generates an associative array from the recordset. Note that is this function \r
-  is also <a href="#getassoc1">available</a> in the connection object. More details \r
-  can be found there.</p>\r
-</font></font><font color="#000000"><font color="#000000"> </font></font><font color="#000000"><font color="#000000">\r
-<p><b>GetArray<a name="getarray"></a>([$number_of_rows])</b></p>\r
-<p>Generate a 2-dimensional array of records from the current cursor position, \r
-  indexed from 0 to $number_of_rows - 1. If $number_of_rows is undefined, till \r
-  EOF.</p>\r
-<p><b>GetRows<a name="getrows"></a>([$number_of_rows])</b></p>\r
-Generate a 2-dimensional array of records from the current cursor position. Synonym \r
-for GetArray() for compatibility with Microsoft ADO. \r
-<p> <b>GetMenu<a name="getmenu"></a>($name, [$default_str=''], [$blank1stItem=true], \r
-  [$multiple_select=false], [$size=0], [$moreAttr=''])</b></p>\r
-<p>Generate a HTML menu (&lt;select&gt;&lt;option&gt;&lt;option&gt;&lt;/select&gt;). \r
-  The first column of the recordset (fields[0]) will hold the string to display \r
-  in the option tags. If the recordset has more than 1 column, the second column \r
-  (fields[1]) is the value to send back to the web server.. The menu will be given \r
-  the name $<i>name</i>. \r
-<p> If $<i>default_str</i> is defined, then if $<i>default_str</i> == fields[0], \r
-  that field is selected. If $<i>blank1stItem</i> is true, the first option is \r
-  empty. You can also set the first option strings by setting $blank1stItem = \r
-  "$value:$text".</p>\r
-<p>$<i>Default_str</i> can be array for a multiple select listbox.</p>\r
-<p>To get a listbox, set the $<i>size</i> to a non-zero value (or pass $default_str \r
-  as an array). If $<i>multiple_select</i> is true then a listbox will be generated \r
-  with $<i>size</i> items (or if $size==0, then 5 items) visible, and we will \r
-  return an array to a server. Lastly use $<i>moreAttr </i> to add additional \r
-  attributes such as javascript or styles. </p>\r
-<p>Menu Example 1: <code>GetMenu('menu1','A',true)</code> will generate a menu: \r
-  <select name='menu1'>\r
-    <option> \r
-    <option value=1 selected>A \r
-    <option value=2>B \r
-    <option value=3>C \r
-  </select>\r
-  for the data (A,1), (B,2), (C,3). Also see <a href="#ex5">example 5</a>.</p>\r
-<p>Menu Example 2: For the same data, <code>GetMenu('menu1',array('A','B'),false)</code> \r
-  will generate a menu with both A and B selected: <br>\r
-  <select name='menu1' multiple size=3>\r
-    <option value=1 selected>A \r
-    <option value=2 selected>B \r
-    <option value=3>C \r
-  </select>\r
-<p> <b>GetMenu2<a name="getmenu2"></a>($name, [$default_str=''], [$blank1stItem=true], \r
-  [$multiple_select=false], [$size=0], [$moreAttr=''])</b></p>\r
-<p>This is nearly identical to GetMenu, except that the $<i>default_str</i> is \r
-  matched to fields[1] (the option values).</p>\r
-<p>Menu Example 3: Given the data in menu example 2, <code>GetMenu2('menu1',array('1','2'),false)</code> \r
-  will generate a menu with both A and B selected in menu example 2, but this \r
-  time the selection is based on the 2nd column, which holds the values to return \r
-  to the Web server. \r
-<p><b>UserDate<a name="userdate"></a>($str, [$fmt])</b></p>\r
-<p>Converts the date string $<i>str</i> to another format. The date format is Y-m-d,\r
-or Unix timestamp format. The default $<i>fmt</i> is Y-m-d.</p>\r
-<p><b>UserTimeStamp<a name="usertimestamp"></a>($str, [$fmt])</b></p>\r
-<p>Converts the timestamp string $<b>str</b> to another format. The timestamp \r
-  format is Y-m-d H:i:s, as in '2002-02-28 23:00:12', or Unix timestamp format.\r
-   UserTimeStamp calls UnixTimeStamp to parse $<i>str</i>, and $<i>fmt</i> defaults to Y-m-d H:i:s if not defined. \r
-</p>\r
-<p><b>UnixDate<a name="unixdate"></a>($str)</b></p>\r
-<p>Parses the date string $<b>str</b> and returns it in unix mktime format (eg. \r
-  a number indicating the seconds after January 1st, 1970). Expects the date to \r
-  be in Y-m-d H:i:s format, except for Sybase and Microsoft SQL Server, where \r
-  M d Y is also accepted (the 3 letter month strings are controlled by a global \r
-  array, which might need localisation).</p>\r
-<p>This function is available in both ADORecordSet and ADOConnection since 1.91.</p>\r
-<p><b>UnixTimeStamp<a name="unixtimestamp"></a>($str)</b></p>\r
-<p>Parses the timestamp string $<b>str</b> and returns it in unix mktime format \r
-  (eg. a number indicating the seconds after January 1st, 1970). Expects the date \r
-  to be in "Y-m-d, H:i:s" (1970-12-24, 00:00:00) or "Y-m-d H:i:s" (1970-12-24 00:00:00) or "YmdHis" (19701225000000) format, except for Sybase and Microsoft SQL Server, where \r
-  "M d Y h:i:sA" (Dec 25 1970 00:00:00AM) is also accepted (the 3 letter month strings are controlled by \r
-  a global array, which might need localisation).</p>\r
-</font> \r
-<p><font color="#000000">This function is available in both ADORecordSet and ADOConnection \r
-  since 1.91. </font></p>\r
-<p><font color="#000000"><b>OffsetDate<a name="offsetdate"></a>($dayFraction, \r
-  $basedate=false)</b></font></p>\r
-<p><font color="#000000"><font color="#000000">Returns a string </font>with the \r
-  native SQL functions to calculate future and past dates based on $basedate in \r
-  a portable fashion. If $basedate is not defined, then the current date (at 12 \r
-  midnight) is used. Returns the SQL string that performs the calculation when \r
-  passed to Execute(). </font></p>\r
-<p><font color="#000000">For example, in Oracle, to find the date and time that \r
-  is 2.5 days from today, you can use:</font></p>\r
-<pre><font color="#000000"># get date one week from now\r
-$fld = $conn-&gt;OffsetDate(7); // returns &quot;(trunc(sysdate)+7&quot;)</font></pre>\r
-<pre><font color="#000000"># get date and time that is 60 hours from current date and time\r
-$fld = $conn-&gt;OffsetDate(2.5, $conn-&gt;sysTimeStamp);      // returns &quot;(sysdate+2.5)&quot;</font>\r
-\r
-$conn-&gt;Execute(&quot;UPDATE TABLE SET dodate=$fld WHERE ID=$id&quot;);</pre>\r
-<p> This function is available for mysql, mssql, oracle, oci8 and postgresql drivers \r
-  since 2.13. It might work with other drivers<font color="#000000"> provided \r
-  they allow performing numeric day arithmetic on dates.</font></p>\r
-<font color="#000000"> \r
-<p><font color="#000000"><b>SQLDate<a name="sqldate"></a>($dateFormat, $basedate=false)</b></font></p>\r
-Returns a string which contains the native SQL functions to format a date or date \r
-column $basedate. This is used in SELECT statements. For INSERT/UPDATE statements, \r
-use <a href="#dbdate">DBDate</a>. It uses a case-sensitive $dateFormat, which \r
-supports: \r
-<pre>\r
- Y: 4-digit Year\r
- Q: Quarter (1-4)\r
- m: Month (01-12)\r
- d: Day (01-31)\r
- H: Hour (00-23)\r
- h: Hour (1-12)\r
- i: Minute (00-59)\r
- s: Second (00-60)\r
- A: AM/PM indicator</pre>\r
-<p>All other characters are treated as strings. You can also use \ to escape characters. \r
-  Available on selected databases, including mysql, postgresql, mssql, oci8 and \r
-  DB2. \r
-<p>This is useful in writing portable sql statements that GROUP BY on dates. For \r
-  example to display total cost of goods sold broken by quarter (dates are stored \r
-  in a field called postdate): \r
-<pre>\r
- $sqlfn = $db->SQLDate('Y-\QQ','postdate'); # get sql that formats postdate to output 2002-Q1\r
- $sql = "SELECT $sqlfn,SUM(cogs) FROM table GROUP BY $sqlfn ORDER BY 1 desc";\r
- </pre>\r
-<p><b>MoveNext<a name="movenext"></a>( )</b></p>\r
-<p>Move the internal cursor to the next row. The <i>$this->fields</i> array is \r
-  automatically updated. Returns false if unable to do so (normally because EOF \r
-  has been reached), otherwise true. \r
-<p> If EOF is reached, then the $this->fields array is set to false (this was \r
-  only implemented consistently in ADOdb 3.30). For the pre-3.30 behaviour of \r
-  $this->fields (at EOF), set the global variable $ADODB_COMPAT_FETCH = true.</p>\r
-<p>Example:</p>\r
-<pre>$rs = $db-&gt;Execute($sql);\r
-if ($rs) \r
-       while (!$rs-&gt;EOF) {\r
-               ProcessArray($rs->fields);      \r
-               $rs->MoveNext();\r
-       } </pre>\r
-<p><b>Move<a name="move"></a>($to)</b></p>\r
-<p>Moves the internal cursor to a specific row $<b>to</b>. Rows are zero-based \r
-  eg. 0 is the first row. The <b>fields</b> array is automatically updated. For \r
-  databases that do not support scrolling internally, ADOdb will simulate forward \r
-  scrolling. Some databases do not support backward scrolling. If the $<b>to</b> \r
-  position is after the EOF, $<b>to</b> will move to the end of the RecordSet \r
-  for most databases. Some obscure databases using odbc might not behave this \r
-  way.</p>\r
-<p>Note: This function uses <i>absolute positioning</i>, unlike Microsoft's ADO.</p>\r
-<p>Returns true or false. If false, the internal cursor is not moved in most implementations, \r
-  so AbsolutePosition( ) will return the last cursor position before the Move( \r
-  ). </p>\r
-<p><b>MoveFirst<a name="movefirst"></a>()</b></p>\r
-<p>Internally calls Move(0). Note that some databases do not support this function.</p>\r
-<p><b>MoveLast<a name="movelast"></a>()</b></p>\r
-<p>Internally calls Move(RecordCount()-1). Note that some databases do not support \r
-  this function.</p>\r
-<p><b>GetRowAssoc</b><a name="getrowassoc"></a>($toUpper=true)</p>\r
-<p>Returns an associative array containing the current row. The keys to the array \r
-  are the column names. The column names are upper-cased for easy access. To get \r
-  the next row, you will still need to call MoveNext(). </p>\r
-<p>For example:<br>\r
-  Array ( [ID] => 1 [FIRSTNAME] => Caroline [LASTNAME] => Miranda [CREATED] => \r
-  2001-07-05 ) </p>\r
-<p>Note: do not use GetRowAssoc() with $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC. \r
-  Because they have the same functionality, they will interfere with each other.</p>\r
-</font> \r
-<p><font color="#000000"><b>AbsolutePage<a name="absolutepage"></a>($page=-1) \r
-  </b></font></p>\r
-<p>Returns the current page. Requires PageExecute()/CachePageExecute() to be called. \r
-  See <a href=#ex8>Example 8</a>.</p>\r
-<font color="#000000"> \r
-<p><b>AtFirstPage<a name="atfirstpage">($status='')</a></b></p>\r
-<p>Returns true if at first page (1-based). Requires PageExecute()/CachePageExecute() \r
-  to be called. See <a href=#ex8>Example 8</a>.</p>\r
-<p><b>AtLastPage<a name="atlastpage">($status='')</a></b></p>\r
-<p>Returns true if at last page (1-based). Requires PageExecute()/CachePageExecute() \r
-  to be called. See <a href=#ex8>Example 8</a>.</p>\r
-<p><b>Fields</b><a name="fields"></a>(<b>$colname</b>)</p>\r
-<p>Returns the value of the \r
-  associated column $<b>colname</b> for the current row. The column name is case-insensitive.</p>\r
-<p>This is a convenience function. For higher performance, use <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a>. </p>\r
-<p><b>FetchRow</b><a name="fetchrow"></a>()</p>\r
-</font> \r
-<p><font color="#000000">Returns array containing current row, or false if EOF. \r
-  FetchRow( ) internally moves to the next record after returning the current \r
-  row. </font></p>\r
-<p><font color="#000000">Warning: Do not mix using FetchRow() with MoveNext().</font></p>\r
-<p><font color="#000000">Usage:</font></p>\r
-<pre><font color="#000000">$rs = $db-&gt;Execute($sql);\r
-if ($rs)\r
-       while ($arr = $rs-&gt;FetchRow()) &#123;\r
-          &nbsp;&nbsp;# process $arr   \r
-</font><font color="#000000">  &#125;</font></pre>\r
-<p><font color="#000000"><b>FetchInto</b><a name="fetchinto"></a>(<b>&amp;$array</b>)</font></p>\r
-<p><font color="#000000"> Sets $array to the current row. Returns PEAR_Error object \r
-  if EOF, 1 if ok (DB_OK constant). If PEAR is undefined, false is returned when \r
-  EOF. </font><font color="#000000">FetchInto( ) internally moves to the next \r
-  record after returning the current row. </font></p>\r
-<p><font color="#000000"> FetchRow() is easier to use. See above.</font></p>\r
-<font color="#000000"> \r
-<p><b>FetchField<a name="fetchfield"></a>($column_number)</b></p>\r
-<p>Returns an object containing the <b>name</b>, <b>type</b> and <b>max_length</b> \r
-  of the associated field. If the max_length cannot be determined reliably, it \r
-  will be set to -1. The column numbers are zero-based. See <a href="#ex2">example \r
-  2.</a></p>\r
-<p><b>FieldCount<a name="fieldcount"></a>( )</b></p>\r
-<p>Returns the number of fields (columns) in the record set.</p>\r
-<p><b>RecordCount<a name="recordcount"></a>( )</b></p>\r
-<p>Returns the number of rows in the record set. If the number of records returned \r
-  cannot be determined from the database driver API, we will buffer all rows and \r
-  return a count of the rows after all the records have been retrieved. This buffering \r
-  can be disabled (for performance reasons) by setting the global variable $ADODB_COUNTRECS \r
-  = false. When disabled, RecordCount( ) will return -1 for certain databases. \r
-  See the supported databases list above for more details. </p>\r
-<p> RowCount is a synonym for RecordCount.</p>\r
-<p><b>PO_RecordCount<a name="po_recordcount"></a>($table, $where)</b></p>\r
-<p>Returns the number of rows in the record set. If the database does not support \r
-  this, it will perform a SELECT COUNT(*) on the table $table, with the given \r
-  $where condition to return an estimate of the recordset size.</p>\r
-<p>$numrows = $rs-&gt;PO_RecordCount(&quot;articles_table&quot;, &quot;group=$group&quot;);</p>\r
-<b> NextRecordSet<a name="nextrecordset" id="nextrecordset"></a>()</b> \r
-<p>For databases that allow multiple recordsets to be returned in one query, this \r
-  function allows you to switch to the next recordset. Currently only supported \r
-  by mssql driver.</p>\r
-<pre>\r
-$rs = $db-&gt;Execute('execute return_multiple_rs');\r
-$arr1 = $rs-&gt;GetArray();\r
-$rs-&gt;NextRecordSet();\r
-$arr2 = $rs-&gt;GetArray();</pre>\r
-<p><b>FetchObject<a name="fetchobject"></a>($toupper=true)</b></p>\r
-<p>Returns the current row as an object. If you set $toupper to true, then the \r
-  object fields are set to upper-case. Note: The newer FetchNextObject() is the \r
-  recommended way of accessing rows as objects. See below.</p>\r
-<p><b>FetchNextObject<a name="fetchnextobject"></a>($toupper=true)</b></p>\r
-<p>Gets the current row as an object and moves to the next row automatically. \r
-  Returns false if at end-of-file. If you set $toupper to true, then the object \r
-  fields are set to upper-case.</p>\r
-<pre>\r
-$rs = $db->Execute('select firstname,lastname from table');\r
-if ($rs) &#123;\r
-       while ($o = $rs->FetchNextObject()) &#123;\r
-               print "$o->FIRSTNAME, $o->LASTNAME&lt;BR>";\r
-       &#125;\r
-&#125;\r
-</pre>\r
-<p>There is some trade-off in speed in using FetchNextObject(). If performance \r
-  is important, you should access rows with the <code>fields[]</code> array. <b>FetchObj<a name="fetchobj" id="fetchobj"></a>()</b> \r
-<p>Returns the current record as an object. Fields are not upper-cased, unlike \r
-  FetchObject. </font> \r
-<p><font color="#000000"><b>FetchNextObj<a name="fetchnextobj" id="fetchnextobj"></a>()</b> \r
-  </font></p>\r
-<p><font color="#000000">Returns the current record as an object and moves to \r
-  the next record. If EOF, false is returned. Fields are not upper-cased, unlike \r
-  FetctNextObject. </font></p>\r
-<font color="#000000"> \r
-<p><b>CurrentRow<a name="currentrow"></a>( )</b></p>\r
-<p>Returns the current row of the record set. 0 is the first row.</p>\r
-<p><b>AbsolutePosition<a name="abspos"></a>( )</b></p>\r
-<p>Synonym for <b>CurrentRow</b> for compatibility with ADO. Returns the current \r
-  row of the record set. 0 is the first row.</p>\r
-<p><b>MetaType<a name="metatype"></a>($nativeDBType[,$field_max_length],[$fieldobj])</b></p>\r
-<p>Determine what <i>generic</i> meta type a database field type is given its \r
-  native type $<b>nativeDBType</b> as a string and the length of the field $<b>field_max_length</b>. \r
-  Note that field_max_length can be -1 if it is not known. The field object returned \r
-  by FetchField() can be passed in $<b>fieldobj</b> or as the 1st parameter <b>$nativeDBType</b>. \r
-  This is useful for databases such as <i>mysql</i> which has additional properties \r
-  in the field object such as <i>primary_key</i>. </p>\r
-<p>Uses the field <b>blobSize</b> and compares it with $<b>field_max_length</b> \r
-  to determine whether the character field is actually a blob.</p>\r
-For example, $db-&gt;MetaType('char') will return 'C'. \r
-<p>Returns:</p>\r
-<ul>\r
-  <li><b>C</b>: Character fields that should be shown in a &lt;input type=&quot;text&quot;&gt; \r
-    tag. </li>\r
-  <li><b>X</b>: Clob (character large objects), or large text fields that should \r
-    be shown in a &lt;textarea&gt;</li>\r
-  <li><b>D</b>: Date field</li>\r
-  <li><b>T</b>: Timestamp field</li>\r
-  <li><b>L</b>: Logical field (boolean or bit-field)</li>\r
-  <li><b>N</b>: Numeric field. Includes decimal, numeric, floating point, and \r
-    real. </li>\r
-  <li><b>I</b>:&nbsp; Integer field. </li>\r
-  <li><b>R</b>: Counter or Autoincrement field. Must be numeric.</li>\r
-  <li><b>B</b>: Blob, or binary large objects.<font color="#000000"> </font></li>\r
-</ul>\r
-</font> \r
-<p><font color="#000000"> Since ADOdb 3.0, MetaType accepts $fieldobj as the first \r
-  parameter, instead of $nativeDBType. </font></p>\r
-<font color="#000000"> \r
-<p><b>Close( )<a name="rsclose"></a></b></p>\r
-<p>Closes the recordset, cleaning all memory and resources associated with the recordset. \r
-<p>\r
-If memory management is not an issue, you do not need to call this function as recordsets\r
-are closed for you by PHP at the end of the script. \r
-SQL statements such as INSERT/UPDATE/DELETE do not really return a recordset, so you do not have to call Close()\r
-for such SQL statements.</p>\r
-<hr>\r
-<h3>function rs2html<a name="rs2html"></a>($adorecordset,[$tableheader_attributes], \r
-  [$col_titles])</h3>\r
-<p>This is a standalone function (rs2html = recordset to html) that is similar \r
-  to PHP's <i>odbc_result_all</i> function, it prints a ADORecordSet, $<b>adorecordset</b> \r
-  as a HTML table. $<b>tableheader_attributes</b> allow you to control the table \r
-  <i>cellpadding</i>, <i>cellspacing</i> and <i>border</i> attributes. Lastly \r
-  you can replace the database column names with your own column titles with the \r
-  array $<b>col_titles</b>. This is designed more as a quick debugging mechanism, \r
-  not a production table recordset viewer.</p>\r
-<p>You will need to include the file <i>tohtml.inc.php</i>.</p>\r
-<p>Example of rs2html:<b><font color="#336600"><a name="exrs2html"></a></font></b></p>\r
-<pre><b><font color="#336600">&lt;?\r
-include('tohtml.inc.php')</font></b>; # load code common to ADOdb \r
-<b>include</b>('adodb.inc.php'); # load code common to ADOdb \r
-$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');   # create a connection \r
-$<font color="#663300">conn</font>->PConnect('localhost','userid','','agora');# connect to MySQL, agora db\r
-$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers'; \r
-$<font color="#663300">rs</font>   = $<font color="#663300">conn</font>->Execute($sql); \r
-<font color="#336600"><b>rs2html</b></font><b>($<font color="#663300">rs</font>,'<i>border=2 cellpadding=3</i>',array('<i>Customer Name','Customer ID</i>'));\r
-?&gt;</b></pre>\r
-<hr>\r
-<h3>Differences between this ADOdb library and Microsoft ADO<a name="adodiff"></a></h3>\r
-<ol>\r
-  <li>ADOdb only supports recordsets created by a connection object. Recordsets \r
-    cannot be created independently.</li>\r
-  <li>ADO properties are implemented as functions in ADOdb. This makes it easier \r
-    to implement any enhanced ADO functionality in the future.</li>\r
-  <li>ADOdb's <font face="Courier New, Courier, mono">ADORecordSet-&gt;Move()</font> \r
-    uses absolute positioning, not relative. Bookmarks are not supported.</li>\r
-  <li><font face="Courier New, Courier, mono">ADORecordSet-&gt;AbsolutePosition() \r
-    </font>cannot be used to move the record cursor.</li>\r
-  <li>ADO Parameter objects are not supported. Instead we have the ADOConnection::<a href="#parameter">Parameter</a>( \r
-    ) function, which provides a simpler interface for calling preparing parameters \r
-    and calling stored procedures.</li>\r
-  <li>Recordset properties for paging records are available, but implemented as \r
-    in <a href=#ex8>Example 8</a>.</li>\r
-</ol>\r
-<hr>\r
-<h1>Database Driver Guide<a name="driverguide"></a></h1>\r
-<p>This describes how to create a class to connect to a new database. To ensure \r
-  there is no duplication of work, kindly email me at jlim#natsoft.com.my if you \r
-  decide to create such a class.</p>\r
-<p>First decide on a name in lower case to call the database type. Let's say we \r
-  call it xbase. </p>\r
-<p>Then we need to create two classes ADODB_xbase and ADORecordSet_xbase in the \r
-  file adodb-xbase.inc.php.</p>\r
-<p>The simplest form of database driver is an adaptation of an existing ODBC driver. \r
-  Then we just need to create the class <i>ADODB_xbase extends ADODB_odbc</i> \r
-  to support the new <b>date</b> and <b>timestamp</b> formats, the <b>concatenation</b> \r
-  operator used, <b>true</b> and <b>false</b>. For the<i> ADORecordSet_xbase extends \r
-  ADORecordSet_odbc </i>we need to change the <b>MetaType</b> function. See<b> \r
-  adodb-vfp.inc.php</b> as an example.</p>\r
-<p>More complicated is a totally new database driver that connects to a new PHP \r
-  extension. Then you will need to implement several functions. Fortunately, you \r
-  do not have to modify most of the complex code. You only need to override a \r
-  few stub functions. See <b>adodb-mysql.inc.php</b> for example.</p>\r
-<p>The default date format of ADOdb internally is YYYY-MM-DD (Ansi-92). All dates \r
-  should be converted to that format when passing to an ADOdb date function. See \r
-  Oracle for an example how we use ALTER SESSION to change the default date format \r
-  in _pconnect _connect.</p>\r
-<p><b>ADOConnection Functions to Override</b></p>\r
-<p>Defining a constructor for your ADOConnection derived function is optional. \r
-  There is no need to call the base class constructor.</p>\r
-<p>_<b>connect</b>: Low level implementation of Connect. Returns true or false. \r
-  Should set the _<b>connectionID</b>.</p>\r
-<p>_<b>pconnect:</b> Low level implemention of PConnect. Returns true or false. \r
-  Should set the _<b>connectionID</b>.</p>\r
-<p>_<b>query</b>: Execute a query. Returns the queryID, or false.</p>\r
-<p>_<b>close: </b>Close the connection -- PHP should clean up all recordsets. \r
-</p>\r
-<p><b>ErrorMsg</b>: Stores the error message in the private variable _errorMsg. \r
-</p>\r
-<p><b>ADOConnection Fields to Set</b></p>\r
-<p>_<b>bindInputArray</b>: Set to true if binding of parameters for SQL inserts \r
-  and updates is allowed using ?, eg. as with ODBC.</p>\r
-<p><b>fmtDate</b></p>\r
-<p><b>fmtTimeStamp</b></p>\r
-<p><b>true</b></p>\r
-<p><b>false</b></p>\r
-<p><b>concat_operator</b></p>\r
-<p><b>replaceQuote</b></p>\r
-<p><b>hasLimit</b> support SELECT * FROM TABLE LIMIT 10 of MySQL.</p>\r
-<p><b>hasTop</b> support Microsoft style SELECT TOP 10 * FROM TABLE.</p>\r
-<p><b>ADORecordSet Functions to Override</b></p>\r
-<p>You will need to define a constructor for your ADORecordSet derived class that \r
-  calls the parent class constructor.</p>\r
-<p><b>FetchField: </b> as documented above in ADORecordSet</p>\r
-<p>_<b>initrs</b>: low level initialization of the recordset: setup the _<b>numOfRows</b> \r
-  and _<b>numOfFields</b> fields -- called by the constructor.</p>\r
-<p>_<b>seek</b>: seek to a particular row. Do not load the data into the fields \r
-  array. This is done by _fetch. Returns true or false. Note that some implementations \r
-  such as Interbase do not support seek. Set canSeek to false.</p>\r
-<p>_<b>fetch</b>: fetch a row using the database extension function and then move \r
-  to the next row. Sets the <b>fields</b> array. If the parameter $ignore_fields \r
-  is true then there is no need to populate the <b>fields</b> array, just move \r
-  to the next row. then Returns true or false.</p>\r
-<p>_<b>close</b>: close the recordset</p>\r
-<p><b>Fields</b>: If the array row returned by the PHP extension is not an associative \r
-  one, you will have to override this. See adodb-odbc.inc.php for an example. \r
-  For databases such as MySQL and MSSQL where an associative array is returned, \r
-  there is no need to override this function.</p>\r
-<p><b>ADOConnection Fields to Set</b></p>\r
-<p>canSeek: Set to true if the _seek function works.</p>\r
-<h2>ToDo:</h2>\r
-<p>See the <a href=http://php.weblogs.com/adodb-todo-roadmap>RoadMap</a> article.</p>\r
-<p>Also see the ADOdb <a href=http://php.weblogs.com/adodb_csv>proxy</a> article \r
-  for bridging Windows and Unix databases using http remote procedure calls. For \r
-  your education, visit <a href=http://palslib.com/>palslib.com</a> for database info, \r
-  and read this article on <a href=http://phplens.com/lens/php-book/optimizing-debugging-php.php>Optimizing \r
-  PHP</a>. </p>\r
-</font>\r
-<h2>Change Log<a name="Changes"></a><a name="changes"></a><a name="changelog"></a></h2>\r
-<p><b>4.11 27 Jan 2004</b>\r
-<p>Table misspelt in perf-oci8.inc.php. Changed v$conn_cache_advice to v$db_cache_advice. Reported by Steve W.\r
-<p>UserTimeStamp and DBTimeStamp did not handle YYYYMMDDHHMMSS format properly. Reported by Mike Muir. Fixed.\r
-<p>Changed oci8 Prepare(). Does not auto-allocate OCINewCursor automatically, unless 2nd param is set to true.\r
-This will break backward compat, if Prepare/Execute is used instead of ExecuteCursor. Reported by Chris Jones.\r
-<p>Added InParameter() and OutParameter(). Wrapper functions to Parameter(), but nicer because they\r
-are self-documenting.\r
-<p>Added 'R' handling in ActualType() to datadict-mysql.inc.php\r
-<p>Added ADOConnection::SerializableRS($rs). Returns a recordset that can be serialized in a session.\r
-<p>Added "Run SQL" to performance UI().\r
-<p>Misc spelling corrections in adodb-mysqli.inc.php, adodb-oci8.inc.php and datadict-oci8.inc.php, from Heinz Hombergs.\r
-<p>MetaIndexes() for ibase contributed by Heinz Hombergs.\r
-<p><b>4.10 12 Jan 2004</b>\r
-<p>Dan Cech contributed extensive changes to data dictionary to support name quoting (with `), and drop table/index.\r
-<p>Informix added cursorType property. Default remains IFX_SCROLL, but you can change to 0 (non-scrollable cursor) for performance.\r
-<p>Added ADODB_View_PrimaryKeys() for returning view primary keys to MetaPrimaryKeys().\r
-<p>Simplified chinese file, adodb-cn.inc.php from cysoft.\r
-<p>Added check for ctype_alnum in adodb-datadict.inc.php. Thx to Jason Judge.\r
-<p>Added connection parameter to ibase Prepare(). Fix by Daniel Hassan.\r
-<p>Added nameQuote for quoting identifiers and names to connection obj. Requested by Jason Judge. Also the\r
-data dictionary parser now detects `field name` and generates column names with spaces correctly.\r
-<p>BOOL type not recognised correctly as L. Fixed.\r
-<p>Fixed paths in ADODB_DIR for session files, and back-ported it to 4.05 (15 Dec 2003)\r
-<p>Added Schema to postgresql MetaTables. Thx to col#gear.hu\r
-<p>Empty postgresql recordsets that had blob fields did not set EOF properly. Fixed.\r
-<p>CacheSelectLimit internal parameters to SelectLimit were wrong. Thx to Nio.\r
-<p>Modified adodb_pr() and adodb_backtrace() to support command-line usage (eg. no html).\r
-<p>Fixed some fr and it lang errors. Thx to Gaetano G.\r
-<p>Added contrib directory, with adodb rs to xmlrpc convertor by Gaetano G.\r
-<p>Fixed array recordset bugs when _skiprow1 is true. Thx to Gaetano G.\r
-<p>Fixed pivot table code when count is false.\r
-<p>\r
-\r
-<p><b>4.05 13 Dec 2003 </b>\r
-<p>Added MetaIndexes - thx to Dan Cech.\r
-<p>Rewritten session code by Ross Smith. Moved code to adodb/session directory.\r
-<p>Added function exists check on connecting to most drivers, so we don't crash with the unknown function error.\r
-<p>Smart Transactions failed with GenID() when it no seq table has been created because the sql\r
-       statement fails. Fix by Mark Newnham.\r
-<p>Added $db->length, which holds name of function that returns strlen.\r
-<p>Fixed error handling for bad driver in ADONewConnection - passed too few params to error-handler.\r
-<p>Datadict did not handle types like 16.0 properly in _GetSize. Fixed.\r
-<p>Oci8 driver SelectLimit() bug &= instead of =& used. Thx to Swen Thümmler.\r
-<p>Jesse Mullan suggested not flushing outp when output buffering enabled. Due to Apache 2.0 bug. Added.\r
-<p>MetaTables/MetaColumns return ref bug with PHP5 fixed in adodb-datadict.inc.php.\r
-<p>New mysqli driver contributed by Arjen de Rijke. Based on adodb 3.40 driver.\r
-Then jlim added BeginTrans, CommitTrans, RollbackTrans, IfNull, SQLDate. Also fixed return ref bug.\r
-<p>$ADODB_FLUSH added, if true then force flush in debugging outp. Default is false.  In earlier\r
-versions, outp defaulted to flush, which is not compat with apache 2.0.\r
-<p>Mysql driver's GenID() function did not work when when sql logging is on. Fixed.\r
-<p>$ADODB_SESSION_TBL not declared as global var. Not available if adodb-session.inc.php included in function. Fixed.\r
-<p>The input array not passed to Execute() in _adodb_getcount(). Fixed.\r
-<p><b>4.04 13 Nov 2003 </b>\r
-<p>Switched back to foreach - faster than list-each.\r
-<p>Fixed bug in ado driver - wiping out $this->fields with date fields.\r
-<p>Performance Monitor, View SQL, Explain Plan did not work if strlen($SQL)>max($_GET length). Fixed.\r
-<p>Performance monitor, oci8 driver added memory sort ratio.\r
-<p>Added random property, returns SQL to generate a floating point number between 0 and 1;\r
-<p><b>4.03 6 Nov 2003 </b>\r
-<p>The path to adodb-php4.inc.php and adodb-iterators.inc.php was not setup properly.\r
-<p>Patched SQLDate in interbase to support hours/mins/secs. Thx to ari kuorikoski.\r
-<p>Force autorollback for pgsql persistent connections - \r
-apparently pgsql did not autorollback properly before 4.3.4. See http://bugs.php.net/bug.php?id=25404\r
-<p><b>4.02 5 Nov 2003 </b>\r
-<p>Some errors in adodb_error_pg() fixed. Thx to Styve.\r
-<p>Spurious Insert_ID() error was generated by LogSQL(). Fixed.\r
-<p>Insert_ID was interfering with Affected_Rows() and Replace()  when LogSQL() enabled. Fixed.\r
-<p>More foreach loops optimized with list/each.\r
-<p>Null dates not handled properly in ADO driver (it becomes 31 Dec 1969!).\r
-<p>Heinz Hombergs contributed patches for mysql MetaColumns - adding scale, made\r
-interbase MetaColumns work with firebird/interbase, and added lang/adodb-de.inc.php.\r
-<p>Added INFORMIXSERVER environment variable.\r
-<p>Added $ADODB_ANSI_PADDING_OFF for interbase/firebird.\r
-<p>PHP 5 beta 2 compat check. Foreach (Iterator) support. Exceptions support.\r
-<p><b>4.01 23 Oct 2003 </b>\r
-<p>Fixed bug in rs2html(), tohtml.inc.php, that generated blank table cells.\r
-<p>Fixed insert_id() incorrectly generated when logsql() enabled.\r
-<p>Modified PostgreSQL _fixblobs to use list/each instead of foreach.\r
-<p>Informix ErrorNo() implemented correctly.\r
-<p>Modified several places to use list/each, including GetRowAssoc().\r
-<p>Added UserTimeStamp() to connection class.\r
-<p>Added $ADODB_ANSI_PADDING_OFF for oci8po.\r
-<p><b>4.00 20 Oct 2003 </b>\r
-<p>Upgraded adodb-xmlschema to 1 Oct 2003 snapshot.\r
-<p>Fix to rs2html warning message. Thx to Filo.\r
-<p>Fix for odbc_mssql/mssql SQLDate(), hours was wrong.\r
-<p>Added MetaColumns and MetaPrimaryKeys for sybase. Thx to Chris Phillipson.\r
-<p>Added autoquoting to datadict for MySQL and PostgreSQL. Suggestion by Karsten Dambekalns  \r
-<p><b>3.94 11 Oct 2003 </b>\r
-<p>Create trigger in datadict-oci8.inc.php did not work, because all cr/lf's must be removed. \r
-<p>ErrorMsg()/ErrorNo() did not work for many databases when logging enabled. Fixed.\r
-<p>Removed global variable $ADODB_LOGSQL as it does not work properly with multiple connections.\r
-<p>Added SQLDate support for sybase. Thx to Chris Phillipson\r
-<p>Postgresql checking of pgsql resultset resource was incorrect. Fix by Bharat Mediratta bharat#menalto.com.\r
-Same patch applied to  _insertid and _affectedrows for adodb-postgres64.inc.php.\r
-<p>Added support for NConnect for postgresql.\r
-<p>Added Sybase data dict support. Thx to Chris Phillipson  \r
-<p>Extensive improvements in $perf->UI(), eg. Explain now opens in new window, we show scripts\r
-which call sql, etc.\r
-<p>Perf Monitor UI works with magic quotes enabled.\r
-<p>rsPrefix was declared twice. Removed.\r
-<p>Oci8 stored procedure support, eg. "begin func(); end;" was incorrect in _query. Fixed.\r
-<p>Tiraboschi Massimiliano contributed italian language file.\r
-<p>Fernando Ortiz, fortiz#lacorona.com.mx, contributed informix performance monitor.\r
-<p>Added _varchar (varchar arrays) support for postgresql. Reported by PREVOT Stéphane.\r
-<p><b>3.92 22 Sept 2003</b> \r
-<p>Added GetAssoc and CacheGetAssoc to connection object.\r
-<p>Removed TextMax and CharMax functions from adodb.inc.php. \r
-<p>HasFailedTrans() returned false when trans failed. Fixed. \r
-<p>Moved perf driver classes into adodb/perf/*.php. \r
-<p>Misc improvements to performance monitoring, including UI(). \r
-<p>RETVAL in mssql Parameter(), we do not append @ now. \r
-<p>Added Param($name) to connection class, returns '?' or ":$name", for defining \r
-  bind parameters portably. \r
-<p>LogSQL traps affected_rows() and saves its value properly now. Also fixed oci8 \r
-  _stmt and _affectedrows() bugs. \r
-<p>Session code timestamp check for oci8 works now. Formerly default NLS_DATE_FORMAT \r
-  stripped off time portion. Thx to Tony Blair (tonanbarbarian#hotmail.com). Also \r
-  added new $conn->datetime field to oci8, controls whether MetaType() returns \r
-  'D' ($this->datetime==false) or 'T' ($this->datetime == true) for DATE type. \r
-<p>Fixed bugs in adodb-cryptsession.inc.php and adodb-session-clob.inc.php. \r
-<p>Fixed misc bugs in adodb_key_exists, GetInsertSQL() and GetUpdateSQL(). \r
-<p>Tuned include_once handling to reduce file-system checking overhead. \r
-<p><b>3.91 9 Sept 2003</b> \r
-<p>Only released to InterAkt \r
-<p>Added LogSQL() for sql logging and $ADODB_NEWCONNECTION to override factory \r
-  for driver instantiation. \r
-<p>Added IfNull($field,$ifNull) function, thx to johnwilk#juno.com \r
-<p>Added portable substr support. \r
-<p>Now rs2html() has new parameter, $echo. Set to false to return $html instead \r
-  of echoing it. \r
-<p><b>3.90 5 Sept 2003</b> \r
-<p>First beta of performance monitoring released. \r
-<p>MySQL supports MetaTable() masking. \r
-<p>Fixed key_exists() bug in adodb-lib.inc.php \r
-<p>Added sp_executesql Prepare() support to mssql. \r
-<p>Added bind support to db2. \r
-<p>Added swedish language file - Christian Tiberg" christian#commsoft.nu \r
-<p>Bug in drop index for mssql data dict fixed. Thx to Gert-Rainer Bitterlich. \r
-<p>Left join setting for oci8 was wrong. Thx to johnwilk#juno.com \r
-<p><b>3.80 27 Aug 2003</b> \r
-<p>Patch for PHP 4.3.3 cached recordset csv2rs() fread loop incompatibility. \r
-<p>Added matching mask for MetaTables. Only for oci8, mssql and postgres currently. \r
-<p>Rewrite of "oracle" driver connection code, merging with "oci8", by Gaetano. \r
-<p>Added better debugging for Smart Transactions. \r
-<p>Postgres DBTimeStamp() was wrongly using TO_DATE. Changed to TO_TIMESTAMP. \r
-<p>ADODB_FETCH_CASE check pushed to ADONewConnection to allow people to define \r
-  it after including adodb.inc.php. \r
-<p>Added portugese (brazilian) to languages. Thx to "Levi Fukumori". \r
-<p>Removed arg3 parameter from Execute/SelectLimit/Cache* functions. \r
-<p>Execute() now accepts 2-d array as $inputarray. Also changed docs of fnExecute() \r
-  to note change in sql query counting with 2-d arrays. \r
-<p>Added MONEY to MetaType in PostgreSQL. \r
-<p>Added more debugging output to CacheFlush(). \r
-<p><b>3.72 9 Aug 2003</b> \r
-<p>Added qmagic($str), which is a qstr($str) that auto-checks for magic quotes \r
-  and does the right thing... \r
-<p>Fixed CacheFlush() bug - Thx to martin#gmx.de \r
-<p>Walt Boring contributed MetaForeignKeys for postgres7. \r
-<p>_fetch() called _BlobDecode() wrongly in interbase. Fixed. \r
-<p>adodb_time bug fixed with dates after 2038 fixed by Jason Pell. http://phplens.com/lens/lensforum/msgs.php?id=6980 \r
-<p><b>3.71 4 Aug 2003</b> \r
-<p>The oci8 driver, MetaPrimaryKeys() did not check the owner correctly when $owner \r
-  == false. \r
-<p>Russian language file contributed by "Cyrill Malevanov" cyrill#malevanov.spb.ru. \r
-<p>Spanish language file contributed by "Horacio Degiorgi" horaciod#codigophp.com. \r
-<p>Error handling in oci8 bugfix - if there was an error in Execute(), then when \r
-  calling ErrorNo() and/or ErrorMsg(), the 1st call would return the error, but \r
-  the 2nd call would return no error. \r
-<p>Error handling in odbc bugfix. ODBC would always return the last error, even \r
-  if it happened 5 queries ago. Now we reset the errormsg to '' and errorno to \r
-  0 everytime before CacheExecute() and Execute(). \r
-<p><b>3.70 29 July 2003</b> \r
-<p>Added new SQLite driver. Tested on PHP 4.3 and PHP 5. \r
-<p>Added limited "sapdb" driver support - mainly date support. \r
-<p>The oci8 driver did not identify NUMBER with no defined precision correctly. \r
-<p>Added ADODB_FORCE_NULLS, if set, then PHP nulls are converted to SQL nulls \r
-  in GetInsertSQL/GetUpdateSQL. \r
-<p>DBDate() and DBTimeStamp() format for postgresql had problems. Fixed. \r
-<p>Added tableoptions to ChangeTableSQL(). Thx to Mike Benoit. \r
-<p>Added charset support to postgresql. Thx to Julian Tarkhanov. \r
-<p>Changed OS check for MS-Windows to prevent confusion with darWIN (MacOS) \r
-<p>Timestamp format for db2 was wrong. Changed to yyyy-mm-dd-hh.mm.ss.nnnnnn. \r
-<p>adodb-cryptsession.php includes wrong. Fixed. \r
-<p>Added MetaForeignKeys(). Supported by mssql, odbc_mssql and oci8. \r
-<p>Fixed some oci8 MetaColumns/MetaPrimaryKeys bugs. Thx to Walt Boring. \r
-<p>adodb_getcount() did not init qryRecs to 0. Missing "WHERE" clause checking \r
-  in GetUpdateSQL fixed. Thx to Sebastiaan van Stijn. \r
-<p>Added support for only 'VIEWS' and "TABLES" in MetaTables. From Walt Boring. \r
-<p>Upgraded to adodb-xmlschema.inc.php 0.0.2. \r
-<p>NConnect for mysql now returns value. Thx to Dennis Verspuij. \r
-<p>ADODB_FETCH_BOTH support added to interbase/firebird. \r
-<p>Czech language file contributed by Kamil Jakubovic jake#host.sk. \r
-<p>PostgreSQL BlobDecode did not use _connectionID properly. Thx to Juraj Chlebec. \r
-<p>Added some new initialization stuff for Informix. Thx to "Andrea Pinnisi" pinnisi#sysnet.it \r
-<p>ADODB_ASSOC_CASE constant wrong in sybase _fetch(). Fixed. \r
-<p><b>3.60 16 June 2003</b> \r
-<p>We now SET CONCAT_NULL_YIELDS_NULL OFF for odbc_mssql driver to be compat with \r
-  mssql driver. \r
-<p>The property $emptyDate missing from connection class. Also changed 1903 to \r
-  constant (TIMESTAMP_FIRST_YEAR=100). Thx to Sebastiaan van Stijn. \r
-<p>ADOdb speedup optimization - we now return all arrays by reference. \r
-<p>Now DBDate() and DBTimeStamp() now accepts the string 'null' as a parameter. \r
-  Suggested by vincent. \r
-<p>Added GetArray() to connection class. \r
-<p>Added not_null check in informix metacolumns(). \r
-<p>Connection parameters for postgresql did not work correctly when port was defined. \r
-<p>DB2 is now a tested driver, making adodb 100% compatible. Extensive changes \r
-  to odbc driver for DB2, including implementing serverinfo() and SQLDate(), switching \r
-  to SQL_CUR_USE_ODBC as the cursor mode, and lastAffectedRows and SelectLimit() \r
-  fixes. \r
-<p>The odbc driver's FetchField() field names did not obey ADODB_ASSOC_CASE. Fixed. \r
-<p>Some bugs in adodb_backtrace() fixed. \r
-<p>Added "INT IDENTITY" type to adorecordset::MetaType() to support odbc_mssql \r
-  properly. \r
-<p>MetaColumns() for oci8, mssql, odbc revised to support scale. Also minor revisions \r
-  to odbc MetaColumns() for vfp and db2 compat. \r
-<p>Added unsigned support to mysql datadict class. Thx to iamsure. \r
-<p>Infinite loop in mssql MoveNext() fixed when ADODB_FETCH_ASSOC used. Thx to \r
-  Josh R, Night_Wulfe#hotmail.com. \r
-<p>ChangeTableSQL contributed by Florian Buzin. \r
-<p>The odbc_mssql driver now sets CONCAT_NULL_YIELDS_NULL OFF for compat with \r
-  mssql driver. \r
-<hr>\r
-<p><strong>0.10 Sept 9 2000</strong> First release \r
-<h3><strong>Old changelog history moved to <a href=old-changelog.htm>old-changelog.htm</a>. \r
-  </strong></h3>\r
-<p>&nbsp;</p>\r
-<p> </font> \r
-</body>\r
-</html>\r
+<html>
+<head>
+<title>ADODB Manual</title>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+<XSTYLE
+       body,td {font-family:Arial,Helvetica,sans-serif;font-size:11pt}
+       pre {font-size:9pt}
+       .toplink {font-size:8pt}
+       />
+</head>        
+<body bgcolor="#FFFFFF">
+
+<h2>ADOdb Library for PHP</h2>
+<p>V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim#natsoft.com)</p>
+<p><font size="1">This software is dual licensed using BSD-Style and LGPL. This 
+  means you can use it in compiled proprietary and commercial products.</font></p>
+       <p>Useful ADOdb links:  <a href=http://php.weblogs.com/adodb>Download</a> &nbsp; <a href=http://php.weblogs.com/adodb_manual>Other Docs</a>
+
+<p><a href="#intro"><b>Introduction</b></a><b><br>
+       <a href="#features">Unique Features</a><br>
+       <a href="#users">How People are using ADOdb</a><br>
+       <a href="#bugs">Feature Requests and Bug Reports</a><br>
+       </b><b><a href="#install">Installation</a><br>
+       <a href="#mininstall">Minimum Install</a><br>
+       <a href="#coding">Initializing Code and Connection Examples</a><br>
+       <font size="2"><a href=#adonewconnection>ADONewConnection</a></font> 
+       <font size="2"><a href=#adonewconnection>NewADOConnection</a></font><br>
+       <a href="#speed">High Speed ADOdb - tuning tips</a></b><br>
+       <b><a href="#hack">Hacking and Modifying ADOdb Safely</a><br>
+       <a href="#php5">PHP5 Features</a></b><br>
+       <font size="2"><a href=#php5iterators>foreach iterators</a> <a href=#php5exceptions>exceptions</a></font><br>
+       <b> <a href="#drivers">Supported Databases</a></b><br>
+       <b> <a href="#quickstart">Tutorials</a></b><br>
+       <a href="#ex1">Example 1: Select</a><br>
+       <a href="#ex2">Example 2: Advanced Select</a><br>
+       <a href="#ex3">Example 3: Insert</a><br>
+       <a href="#ex4">Example 4: Debugging</a> &nbsp;<a href="#exrs2html">rs2html 
+       example</a><br>
+       <a href="#ex5">Example 5: MySQL and Menus</a><br>
+       <a href="#ex6">Example 6: Connecting to Multiple Databases at once</a> <br>
+       <a href="#ex7">Example 7: Generating Update and Insert SQL</a> <br>
+       <a href="#ex8">Example 8: Implementing Scrolling with Next and Previous</a><br>
+       <a href="#ex9">Example 9: Exporting in CSV or Tab-Delimited Format</a> <br>
+       <a href="#ex10">Example 10: Custom filters</a><br>
+       <a href="#ex11">Example 11: Smart Transactions</a><br>
+       <br>
+       <b> <a href="#errorhandling">Using Custom Error Handlers and PEAR_Error</a><br>
+       <a href="#DSN">Data Source Names</a><br>
+       <a href="#caching">Caching</a><br>
+       <a href="#pivot">Pivot Tables</a></b> 
+<p><a href="#ref"><b>REFERENCE</b></a>
+<p> <font size="2">Variables: <a href="#adodb_countrecs">$ADODB_COUNTRECS</a> <a href=#adodb_ansi_padding_off>$ADODB_ANSI_PADDING_OFF</a>
+  <a href="#adodb_cache_dir">$ADODB_CACHE_DIR</a> </font><font size="2"><a href=#adodb_fetch_mode>$ADODB_FETCH_MODE</a> 
+  <a href=#adodb_lang>$ADODB_LANG</a><br>
+  Constants: </font><font size="2"><a href=#adodb_assoc_case>ADODB_ASSOC_CASE</a> 
+  </font><br>
+  <a href="#ADOConnection"><b> ADOConnection</b></a><br>
+  <font size="2">Connections: <a href="#connect">Connect</a> <a href="#pconnect">PConnect</a> 
+  <a href="#nconnect">NConnect</a> <br>
+  Executing SQL: <a href="#execute">Execute</a> <a href="#cacheexecute"><i>CacheExecute</i></a> 
+  <a href="#SelectLimit">SelectLimit</a> <a href="#cacheSelectLimit"><i>CacheSelectLimit</i></a> 
+  <a href="#param">Param</a> <a href="#prepare">Prepare</a> <a href=#preparesp>PrepareSP</a> 
+  <a href="#inparameter">InParameter</a> <a href="#outparameter">OutParameter</a>
+  <br>
+  &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="#getone">GetOne</a> 
+  <a href="#cachegetone"><i>CacheGetOne</i></a> <a href="#getrow">GetRow</a> <a href="#cachegetrow"><i>CacheGetRow</i></a> 
+  <a href="#getall">GetAll</a> <a href="#cachegetall"><i>CacheGetAll</i></a> <a href="#getcol">GetCol</a> 
+  <a href="#cachegetcol"><i>CacheGetCol</i></a> <a href="#getassoc1">GetAssoc</a> <a href="#cachegetassoc"><i>CacheGetAssoc</i></a> <a href="#replace">Replace</a> 
+  <br>
+  &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="#executecursor">ExecuteCursor</a> 
+  (oci8 only)<br>
+  Generates SQL strings: <a href="#getupdatesql">GetUpdateSQL</a> <a href="#getinsertsql">GetInsertSQL</a> 
+  <a href="#concat">Concat</a> <a href="#ifnull">IfNull</a> <a href="#length">length</a> <a href="#random">random</a> <a href="#substr">substr</a> 
+  <a href="#qstr">qstr</a> <a href="#param">Param</a> 
+  <a href="#prepare"></a><a href="#OffsetDate">OffsetDate</a> <a href="#SQLDate">SQLDate</a> 
+  <a href="#dbdate">DBDate</a> <a href="#dbtimestamp"></a> <a href="#dbtimestamp">DBTimeStamp</a>
+  <br>
+  Blobs: <a href="#updateblob">UpdateBlob</a> <a href="#updateclob">UpdateClob</a> 
+  <a href="#updateblobfile">UpdateBlobFile</a> <a href="#blobencode">BlobEncode</a> 
+  <a href="#blobdecode">BlobDecode</a><br>
+  Paging/Scrolling: <a href="#pageexecute">PageExecute</a> <a href="#cachepageexecute">CachePageExecute</a><br>
+  Cleanup: <a href="#cacheflush">CacheFlush</a> <a href="#Close">Close</a><br>
+  Transactions: <a href="#starttrans">StartTrans</a> <a href="#completetrans">CompleteTrans</a> 
+  <a href="#failtrans">FailTrans</a> <a href="#hasfailedtrans">HasFailedTrans</a> 
+  <a href="#begintrans">BeginTrans</a> <a href="#committrans">CommitTrans</a> 
+  <a href="#rollbacktrans">RollbackTrans</a> <br>
+  Fetching Data: </font> <font size="2"><a href="#setfetchmode">SetFetchMode</a><br>
+  Strings: <a href="#concat">concat</a> <a href="#length">length</a>  <a href="#qstr">qstr</a> <a href="#quote">quote</a> <a href="#substr">substr</a><br>
+  Dates: <a href="#dbdate">DBDate</a> <a href="#dbtimestamp">DBTimeStamp</a> <a href="#unixdate">UnixDate</a> 
+  <a href="#unixtimestamp">UnixTimeStamp</a> <a href="#OffsetDate">OffsetDate</a> 
+  <a href="#SQLDate">SQLDate</a> <br>
+  Row Management: <a href="#affected_rows">Affected_Rows</a> <a href="#inserted_id">Insert_ID</a>  <a href=#rowlock>RowLock</a>
+  <a href="#genid">GenID</a> <a href=#createseq>CreateSequence</a> <a href=#dropseq>DropSequence</a> 
+  <br>
+  Error Handling: <a href="#errormsg">ErrorMsg</a> <a href="#errorno">ErrorNo</a> 
+  <a href="#metaerror">MetaError</a> <a href="#metaerrormsg">MetaErrorMsg</a><br>
+  Data Dictionary (metadata): <a href="#metadatabases">MetaDatabases</a> <a href="#metatables">MetaTables</a> 
+  <a href="#metacolumns">MetaColumns</a> <a href="#metacolumnames">MetaColumnNames</a> 
+  <a href="#metaprimarykeys">MetaPrimaryKeys</a> <a href="#metaforeignkeys">MetaForeignKeys</a> 
+  <a href="#serverinfo">ServerInfo</a> <br>
+  Statistics and Query-Rewriting: <a href="#logsql">LogSQL</a> <a href="#fnexecute">fnExecute 
+  and fnCacheExecute</a><br>
+  </font><font size="2">Deprecated: <a href="#bind">Bind</a> <a href="#blankrecordset">BlankRecordSet</a>
+  <a href="#parameter">Parameter</a></font>
+  <a href="#adorecordSet"><b><br>
+  ADORecordSet</b></a><br>
+  <font size="2">
+  Returns one field: <a href="#fields">Fields</a><br>
+ Returns one row:<a href="#fetchrow">FetchRow</a> <a href="#fetchinto">FetchInto</a> 
+  <a href="#fetchobject">FetchObject</a> <a href="#fetchnextobject">FetchNextObject</a> 
+  <a href="#fetchobj">FetchObj</a> <a href="#fetchnextobj">FetchNextObj</a>
+ <a href="#getrowassoc">GetRowAssoc</a> <br>
+  Returns all rows:<a href="#getarray">GetArray</a> <a href="#getrows">GetRows</a> 
+  <a href="#getassoc">GetAssoc</a><br>
+  Scrolling:<a href="#move">Move</a> <a href="#movenext">MoveNext</a> <a href="#movefirst">MoveFirst</a> 
+  <a href="#movelast">MoveLast</a> <a href="#abspos">AbsolutePosition</a> <a href="#currentrow">CurrentRow</a> 
+  <a href="#atfirstpage">AtFirstPage</a> <a href="#atlastpage">AtLastPage</a> 
+  <a href="#absolutepage">AbsolutePage</a> </font> <font size="2"><br>
+  Menu generation:<a href="#getmenu">GetMenu</a> <a href="#getmenu2">GetMenu2</a><br>
+  Dates:<a href="#userdate">UserDate</a> <a href="#usertimestamp">UserTimeStamp</a> 
+  <a href="#unixdate">UnixDate</a> <a href="#unixtimestamp">UnixTimeStamp<br>
+  </a>Recordset Info:<a href="#recordcount">RecordCount</a> <a href="#po_recordcount">PO_RecordSet</a> 
+  <a href="#nextrecordset">NextRecordSet</a><br>
+  Field Info:<a href="#fieldcount">FieldCount</a> <a href="#fetchfield">FetchField</a> 
+  <a href="#metatype">MetaType</a><br>
+  Cleanup: <a href="#rsclose">Close</a></font> <font size="2"></font> 
+<p><font size="2"><a href="#rs2html"><b>rs2html</b></a>&nbsp; <a href="#exrs2html">example</a></font><br>
+  <a href="#adodiff">Differences between ADOdb and ADO</a><br>
+  <a href="#driverguide"><b>Database Driver Guide<br>
+  </b></a><b><a href="#changes">Change Log</a></b><br>
+</p>
+<h2>Introduction<a name="intro"></a></h2>
+<p>PHP's database access functions are not standardised. This creates a need for 
+  a database class library to hide the differences between the different database 
+  API's (encapsulate the differences) so we can easily switch databases. PHP 4.0.5 or later
+  is now required (because we use array-based str_replace).</p>
+<p>We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, Informix, 
+  PostgreSQL, FrontBase,  SQLite, Interbase (Firebird and Borland variants), Foxpro, Access, ADO, DB2, SAP DB and ODBC. 
+  We have had successful reports of connecting to Progress and CacheLite via ODBC. We hope more people 
+  will contribute drivers to support other databases.</p>
+<p>PHP4 supports session variables. You can store your session information using 
+  ADOdb for true portability and scalability. See adodb-session.php for more information.</p>
+<p>Also read <a href="http://php.weblogs.com/portable_sql">http://php.weblogs.com/portable_sql</a> 
+  (also available as tips_portable_sql.htm in the release) for tips on writing 
+  portable SQL.</p>
+<h2>Unique Features of ADOdb<a name="features"></a></h2>
+<ul>
+  <li><b>Easy for Windows programmers</b> to adapt to because many of the conventions 
+       are similar to Microsoft's ADO.</li>
+  <li>Unlike other PHP database classes which focus only on select statements, 
+       <b>we provide support code to handle inserts and updates which can be adapted 
+       to multiple databases quickly.</b> Methods are provided for date handling, 
+       string concatenation and string quoting characters for differing databases.</li>
+  <li>A<b> metatype system </b>is built in so that we can figure out that types 
+       such as CHAR, TEXT and STRING are equivalent in different databases.</li>
+  <li><b>Easy to port</b> because all the database dependant code are stored in 
+       stub functions. You do not need to port the core logic of the classes.</li>
+  <li><b>Portable table and index creation</b> with the <a href=docs-datadict.htm>datadict</a> classes.
+  <li><b>Database performance monitoring and SQL tuning</b> with the <a href=docs-perf.htm>performance monitoring</a> classes.
+  <li><b>Database-backed sessions</b> with the <a href=docs-session.htm>session management</a> classes. Supports session expiry notification.
+</ul>
+<h2>How People are using ADOdb<a name="users"></a></h2>
+Here are some examples of how people are using ADOdb (for a much longer list, 
+visit <a href="http://php.weblogs.com/adodb-cool-applications">http://php.weblogs.com/adodb-cool-applications</a>): 
+<ul>
+<li><a href="http://phplens.com/">PhpLens</a> is a commercial data grid component that allows both cool Web designers and serious unshaved programmers to develop and maintain databases on the Web easily. Developed by the author of ADOdb.<p>
+
+<li><a href="http://www.interakt.ro/phakt/">PHAkt: PHP Extension for DreamWeaver Ultradev</a> allows you to script PHP in the popular Web page editor. Database handling provided by ADOdb.<p>
+
+<li><a href="http://www.andrew.cmu.edu/~rdanyliw/snort/snortacid.html">Analysis Console for Intrusion Databases</a> (ACID): PHP-based analysis engine to search and process a database of security incidents generated by security-related software such as IDSes and firewalls (e.g. Snort, ipchains). By Roman Danyliw.<p>
+
+<li><a href="http://www.postnuke.com/">PostNuke</a> is a very popular free content management
+ system and weblog system. It offers full CSS support, HTML 4.01 transitional compliance throughout, an advanced blocks system, and is fully multi-lingual enabled. <p>
+
+<li><a href=http://www.auto-net.no/easypublish.php?page=index&lang_id=2>EasyPublish CMS</a>  is another free content management system for managing information and integrated modules on your internet, intranet- and extranet-sites. From Norway.<p>
+
+<li><a href="http://nola.noguska.com/">NOLA</a> is a full featured accounting, inventory, and job tracking application. It is licensed under the GPL, and developed by Noguska.
+</ul><p>
+
+<h2>Feature Requests and Bug Reports<a name="bugs"></a></h2>
+<p>Feature requests and bug reports can be emailed to <a href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a> 
+  or posted to the ADOdb Help forums at <a href="http://phplens.com/lens/lensforum/topics.php?id=4">http://phplens.com/lens/lensforum/topics.php?id=4</a>.</p>
+<h2>Installation Guide<a name="install"></a></h2>
+<p>Make sure you are running PHP 4.0.4 or later. 
+  Unpack all the files into a directory accessible by your webserver.</p>
+<p>To test, try modifying some of the tutorial examples. Make sure you customize 
+  the connection settings correctly. You can debug using <i>$db->debug = true</i> as shown below:</p>
+<pre>&lt;?php
+       include('adodb/adodb.inc.php');
+       $db = <a href="#adonewconnection">ADONewConnection</a>($dbdriver); # eg 'mysql' or 'postgres'
+       $db->debug = true;
+       $db-><a href="#connect">Connect</a>($server, $user, $password, $database);
+       $rs = $db-><a href="#execute">Execute</a>('select * from some_small_table');
+       print &quot;&lt;pre&gt;&quot;;
+       print_r($rs-><a href="#getrows">GetRows</a>());
+       print &quot;&lt;/pre&gt;&quot;;
+?&gt;</pre>
+
+ <h3>Minimum Install<a name=mininstall></a></h3>
+<p>For developers who want to release a minimal install of ADOdb, you will need:
+<ul>
+<li>adodb.inc.php
+<li>adodb-lib.inc.php
+<li>adodb-time.inc.php
+<li>adodb-csvlib.inc.php (if you use cached recordsets - CacheExecute(), etc)
+<li>adodb-error.inc.php and lang/adodb-$lang.inc.php (if you use MetaError())
+<li>drivers/adodb-$database.inc.php
+<li>license.txt (for legal reasons)
+</ul>
+
+<h3>Code Initialization Examples<a name="coding"></a></h3>
+<p>When running ADOdb, at least two files are loaded. First is adodb/adodb.inc.php, 
+ which contains all functions used by all database classes. The code specific 
+ to a particular database is in the adodb/driver/adodb-????.inc.php file.</p>
+ <a name="adonewconnection">
+<p>For example, to connect to a mysql database:</p>
+<pre>
+include('/path/to/set/here/adodb.inc.php');
+$conn = &amp;ADONewConnection('mysql');
+</pre>
+<p>Whenever you need to connect to a database, you create a Connection object 
+  using the <b>ADONewConnection</b></a>($driver) function. 
+  <b>NewADOConnection</b>($driver) is an alternative name for the same function.</p>
+
+<p>At this point, you are not connected to the database. You will first need to decide
+whether to use <i>persistent</i> or <i>non-persistent</i> connections. The advantage of <i>persistent</i>
+connections is that they are faster, as the database connection is never closed (even 
+when you call Close()). <i>Non-persistent </i>connections take up much fewer resources though,
+reducing the risk of your database and your web-server becoming overloaded. 
+<p>For persistent connections,
+use $conn-&gt;<a href="reference.functions.pconnect.html">PConnect()</a>,
+ or $conn-&gt;<a href="reference.functions.connect.html">Connect()</a> for non-persistent connections.
+Some database drivers also support <a href="reference.functions.nconnect.html">NConnect()</a>, which forces 
+the creation of a new connection. 
+<a name=connection_gotcha></a>
+<p><i>Connection Gotcha</i>:  If you create two connections, but both use the same userid and password,
+PHP will share the same connection. This can cause problems if the connections are meant to 
+different databases. The solution is to always use different userid's for different databases,
+ or use NConnect().
+
+<h3>Examples of Connecting to Databases</h3>
+<h4>MySQL and Most Other Database Drivers</h4>
+<p>MySQL connections are very straightforward, and the parameters are identical 
+  to mysql_connect:</p>
+<pre>
+       $conn = &amp;ADONewConnection('mysql'); 
+       $conn-&gt;PConnect('localhost','userid','password','database');
+ </pre>
+<p> Most other database drivers use a similar convention: Connect($server, $user, $password, $database). Exceptions are listed below.
+<h4>PostgreSQL</h4>
+<p>PostgreSQL accepts connections using: </p>
+<p>a. the standard connection string:</p>
+<pre>
+       $conn = &amp;ADONewConnection('postgres7'); 
+       $conn-&gt;PConnect('host=localhost port=5432 dbname=mary');</pre>
+<p> b. the classical 4 parameters:</p>
+ <pre>
+       $conn-&gt;PConnect('localhost','userid','password','database');
+ </pre>
+<h4>Interbase/Firebird</h4>
+You define the database in the $host parameter:
+<pre>
+       $conn = &ADONewConnection('ibase'); 
+       $conn->PConnect('localhost:c:\ibase\employee.gdb','sysdba','masterkey');
+</pre>
+<h4>SQLite</h4>
+Sqlite will create database if it does not exist.
+<pre>
+       $conn = &ADONewConnection('sqlite'); 
+       $conn->PConnect('c:\path\to\sqlite.db'); # sqlite will create if does not exist
+</pre>
+<h4>Oracle</h4>
+<p>With Oracle, you can connect in multiple ways.</p>
+<p>a. PHP and Oracle reside on the same machine, use default SID.</p>
+<pre>  $conn-&gt;Connect(false, 'scott', 'tiger');</pre>
+<p>b. TNS Name defined, eg. 'myTNS'</p>
+<pre>  $conn-&gt;PConnect(false, 'scott', 'tiger', 'myTNS');
+</pre>
+<p>or</p>
+<pre>  $conn-&gt;PConnect('myTNS', 'scott', 'tiger');</pre>
+<p>c. Host Address and SID</p>
+<pre>  $conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'SID');</pre>
+<p>d. Host Address and Service Name</p>
+<pre>  $conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'servicename');</pre>
+<a name=dsnless></a>
+<h4>DSN-less ODBC (access and mssql examples)</h4>
+<p>ODBC DSN's can be created in the ODBC control panel, or you can use a DSN-less 
+  connection.To use DSN-less connections with ODBC you need PHP 4.3 or later. 
+</p>
+<p>For Microsoft Access:</a></p>
+<pre>
+       $db =& ADONewConnection('access');
+       $dsn = <strong>"Driver=&#123;Microsoft Access Driver (*.mdb)&#125;;Dbq=d:\\northwind.mdb;Uid=Admin;Pwd=;";</strong>
+       $db->Connect($dsn);
+</pre>
+For Microsoft SQL Server: 
+<pre>
+       $db =& ADONewConnection('odbc_mssql');
+       $dsn = <strong>"Driver=&#123;SQL Server&#125;;Server=localhost;Database=northwind;"</strong>;
+       $db->Connect($dsn,'userid','password');
+</pre>
+<b>DSN-less Connections with ADO</b><br>
+If you are using versions of PHP earlier than PHP 4.3.0, DSN-less connections 
+only work with Microsoft's ADO, which is Microsoft's COM based API. An example 
+using the ADOdb library and Microsoft's ADO: 
+<pre>
+&lt;?php
+       include('adodb.inc.php'); 
+       $db = &ADONewConnection("ado_mssql");
+       print "&lt;h1>Connecting DSN-less $db->databaseType...&lt;/h1>";
+               
+       <b>$myDSN="PROVIDER=MSDASQL;DRIVER=&#123;SQL Server&#125;;"
+               . "SERVER=flipper;DATABASE=ai;UID=sa;PWD=;"  ;</b>
+       $db->Connect($myDSN);
+       
+       $rs = $db->Execute("select * from table");
+       $arr = $rs->GetArray();
+       print_r($arr);
+?>
+</pre><a name=speed></a>
+<h2>High Speed ADOdb - tuning tips</h2>
+<p>ADOdb is a big class library, yet it <a href=http://phplens.com/lens/adodb/>consistently beats</a> all other PHP class 
+  libraries in performance. This is because it is designed in a layered fashion, 
+  like an onion, with the fastest functions in the innermost layer. Stick to the 
+  following functions for best performance:</p>
+<table width="40%" border="1" align="center">
+  <tr>
+    <td><div align="center"><b>Innermost Layer</b></div></td>
+  </tr>
+  <tr> 
+    <td><p align="center">Connect, PConnect, NConnect<br>
+        Execute, CacheExecute<br>
+        SelectLimit, SelectLimit<br>
+        MoveNext, Close <br>
+               qstr, Affected_Rows, Insert_ID</p></td>
+  </tr>
+</table>
+<p>The fastest way to access the fields is by accessing the array $recordset->fields 
+  directly. Also set the global variables <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a> 
+  = ADODB_FETCH_NUM, and (for oci8, ibase/firebird and odbc) <a href="#adodb_countrecs">$ADODB_COUNTRECS</a> = false 
+  before you connect to your database. At the time of writing (Dec 2003).</p>
+<p>Consider using bind parameters if your database supports it, as it improves 
+  query plan reuse. Use ADOdb's performance tuning system to identify bottlenecks 
+  quickly. At the time of writing (Dec 2003), this means oci8 and odbc drivers.</p>
+<p>Lastly make sure you have a PHP accelerator cache installed such as APC, Turck 
+  MMCache, Zend Accelerator or ionCube.</p>
+ <p>Informix tips: Disable scrollable cursors with $db->cursorType = 0.
+<p><a name=hack></a> </p>
+<h2>Hacking ADOdb Safely</h2>
+<p>You might want to modify ADOdb for your own purposes. Luckily you can
+still maintain backward compatibility by sub-classing ADOdb and using the $ADODB_NEWCONNECTION
+variable. $ADODB_NEWCONNECTION allows you to override the behaviour of ADONewConnection().
+ADOConnection() checks for this variable and will call
+the function-name stored in this variable if it is defined.
+<p>In the following example, new functionality for the connection object 
+is placed in the <i>hack_mysql</i> and <i>hack_postgres7</i> classes. The recordset class naming convention
+can be controlled using $rsPrefix. Here we set it to 'hack_rs_', which will make ADOdb use
+<i>hack_rs_mysql</i> and <i>hack_rs_postgres7</i> as the recordset classes.
+If you want to use the default ADOdb drivers return false.
+
+<pre>
+class hack_mysql extends adodb_mysql {
+var $rsPrefix = 'hack_rs_';
+  /* Your mods here */
+}
+
+class hack_rs_mysql extends ADORecordSet_mysql {
+ /* Your mods here */
+}
+
+class hack_postgres7 extends adodb_postgres7 {
+var $rsPrefix = 'hack_rs_';
+  /* Your mods here */
+}
+
+class hack_rs_postgres7 extends ADORecordSet_postgres7 {
+ /* Your mods here */
+}
+
+$ADODB_NEWCONNECTION = 'hack_factory';
+
+function& hack_factory($driver)
+{
+       if ($driver !== 'mysql' && $driver !== 'postgres7') return false;
+       
+       $driver = 'hack_'.$driver;
+       $obj = new $driver();
+       return $obj;
+}
+
+include_once('adodb.inc.php');
+
+</pre>
+<p>Don't forget to call the constructor of the parent class.
+<a name="php5">
+<h2>PHP5 Features</h2>
+ ADOdb 4.02 or later will transparently determine which version of PHP you are using.
+If PHP5 is detected, the following features become available:
+<ul>
+<a name="php5iterators">
+<li><b>Foreach iterators</b>: This is a very natural way of going through a recordset:
+<pre>
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+       $rs = $db->Execute($sql);
+       foreach($rs as $k => $row) {
+               echo "r1=".$row[0]." r2=".$row[1]."&lt;br>";
+       }
+</pre>
+<p>
+<a name="php5exceptions">
+<li><b>Exceptions</b>: Just include <i>adodb-exceptions.inc.php</i> and you can now 
+catch exceptions on errors as they occur.
+<pre>
+       <b>include("../adodb-exceptions.inc.php");</b> 
+       include("../adodb.inc.php");     
+       try { 
+               $db = NewADOConnection("oci8"); 
+               $db->Connect('','scott','bad-password'); 
+       } catch (exception $e) { 
+               var_dump($e); 
+       } 
+</pre>
+</ul> 
+<h3><a name="drivers"></a>Databases Supported</h3>
+<table width="100%" border="1">
+  <tr valign="top"> 
+    <td><b>Name</b></td>
+    <td><b>Tested</b></td>
+    <td><b>Database</b></td>
+    <td><b><font size="2">RecordCount() usable</font></b></td>
+    <td><b>Prerequisites</b></td>
+    <td><b>Operating Systems</b></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">access</font></b></td>
+    <td><font size="2">B</font></td>
+    <td><font size="2">Microsoft Access/Jet. You need to create an ODBC DSN.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ODBC </font></td>
+    <td><font size="2">Windows only</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">ado</font></b></td>
+    <td><font size="2">B</font></td>
+    <td><p><font size="2">Generic ADO, not tuned for specific databases. Allows 
+        DSN-less connections. For best performance, use an OLEDB provider. This 
+        is the base class for all ado drivers.</font></p>
+      <p><font size="2">You can set $db-&gt;codePage before connecting.</font></p></td>
+    <td><font size="2">? depends on database</font></td>
+    <td><font size="2">ADO or OLEDB provider</font></td>
+    <td><font size="2">Windows only</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">ado_access</font></b></td>
+    <td><font size="2">B</font></td>
+    <td><font size="2">Microsoft Access/Jet using ADO. Allows DSN-less connections. 
+      For best performance, use an OLEDB provider.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ADO or OLEDB provider</font></td>
+    <td><font size="2">Windows only</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">ado_mssql</font></b></td>
+    <td><font size="2">B</font></td>
+    <td><font size="2">Microsoft SQL Server using ADO. Allows DSN-less connections. 
+      For best performance, use an OLEDB provider.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ADO or OLEDB provider</font></td>
+    <td><font size="2">Windows only</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="54"><b><font size="2">db2</font></b></td>
+    <td height="54"><font size="2">A</font></td>
+    <td height="54"><font size="2">DB2. Should work reliably as based on ODBC 
+      driver.</font></td>
+    <td height="54"><font size="2">Y/N</font></td>
+    <td height="54"><font size="2">DB2 CLI/ODBC interface</font></td>
+    <td height="54"> <p><font size="2">Unix and Windows. <a href="http://www.faqts.com/knowledge_base/view.phtml/aid/6283/fid/14">Unix 
+        install hints</a>. I have had reports that the $host and $database params have to be reversed in Connect() when using the CLI interface.</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">vfp</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">Microsoft Visual FoxPro. You need to create an ODBC DSN.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ODBC</font></td>
+    <td><font size="2">Windows only</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">fbsql</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">FrontBase. </font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">?</font></td>
+    <td> <p><font size="2">Unix and Windows</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">ibase</font></b></td>
+    <td><font size="2">B</font></td>
+    <td><font size="2">Interbase 6 or earlier. Some users report you might need 
+      to use this<br>
+      $db->PConnect('localhost:c:/ibase/employee.gdb', "sysdba", "masterkey") 
+      to connect. Lacks Affected_Rows currently.<br>
+      <br>
+      You can set $db->dialect, $db-&gt;buffers and $db->charSet before connecting.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Interbase client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><i><font size="2">firebird</font></i></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Firebird version of interbase.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Interbase client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><i><font size="2">borland_ibase</font></i></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Borland version of Interbase 6.5 or later. Very sad that 
+      the forks differ.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Interbase client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">informix72</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2"> Informix databases before Informix 7.3 that do no support 
+      SELECT FIRST.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Informix client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">informix</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Generic informix driver.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Informix client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="73"><b><font size="2">mssql</font></b></td>
+    <td height="73"><font size="2">A</font></td>
+    <td height="73"> <p><font size="2">Microsoft SQL Server 7 and later. Works 
+        with Microsoft SQL Server 2000 also. Note that date formating is problematic 
+        with this driver. For example, the PHP mssql extension does not return 
+        the seconds for datetime!</font></p></td>
+    <td height="73"><font size="2">Y/N</font></td>
+    <td height="73"><font size="2">Mssql client</font></td>
+    <td height="73"> <p><font size="2">Unix and Windows. <br>
+        <a href="http://phpbuilder.com/columns/alberto20000919.php3">Unix install 
+        howto</a> and <a href=http://linuxjournal.com/article.php?sid=6636&mode=thread&order=0>another 
+        one</a>. </font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="73"><b><font size="2">mssqlpo</font></b></td>
+    <td height="73"><font size="2">A</font></td>
+    <td height="73"> <p><font size="2">Portable mssql driver. Identical to above 
+        mssql driver, except that '||', the concatenation operator, is converted 
+        to '+'. Useful for porting scripts from most other sql variants that use 
+        ||.</font></p></td>
+    <td height="73"><font size="2">Y/N</font></td>
+    <td height="73"><font size="2">Mssql client</font></td>
+    <td height="73"> <p><font size="2">Unix and Windows. <a href="http://phpbuilder.com/columns/alberto20000919.php3"><br>
+        Unix install howto</a>.</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">mysql</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">MySQL without transaction support. You can also set $db-&gt;clientFlags 
+      before connecting.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">MySQL client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><font size="2"><b>mysqlt</b> or <b>maxsql</b></font></td>
+    <td><font size="2">A</font></td>
+    <td> <p><font size="2">MySQL with transaction support. We recommend using 
+        || as the concat operator for best portability. This can be done by running 
+        MySQL using: <br>
+        <i>mysqld --ansi</i> or <i>mysqld --sql-mode=PIPES_AS_CONCAT</i></font></p></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">MySQL client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">oci8</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">Oracle 8/9. Has more functionality than <i>oracle</i> driver 
+      (eg. Affected_Rows). You might have to putenv('ORACLE_HOME=...') before 
+      Connect/PConnect. </font> <p><font size="2"> There are 2 ways of connecting 
+        - with server IP and service name: <br>
+        <i>PConnect('serverip:1521','scott','tiger','service'</i>)<br>
+        or using an entry in TNSNAMES.ORA or ONAMES or HOSTNAMES: <br>
+        <i>PConnect(false, 'scott', 'tiger', $oraname)</i>. </font> 
+      <p><font size="2">Since 2.31, we support Oracle REF cursor variables directly 
+        (see <a href="#executecursor">ExecuteCursor</a>).</font> </td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Oracle client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">oci805</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Supports reduced Oracle functionality for Oracle 8.0.5. 
+      SelectLimit is not as efficient as in the oci8 or oci8po drivers.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Oracle client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">oci8po</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">Oracle 8/9 portable driver. This is nearly identical with 
+      the oci8 driver except (a) bind variables in Prepare() use the ? convention, 
+      instead of :bindvar, (b) field names use the more common PHP convention 
+      of lowercase names. </font> <p><font size="2">Use this driver if porting 
+        from other databases is important. Otherwise the oci8 driver offers better 
+        performance. </font> </td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Oracle client</font></td>
+    <td><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">odbc</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">Generic ODBC, not tuned for specific databases. To connect, 
+      use <br>
+      PConnect('DSN','user','pwd'). This is the base class for all odbc derived 
+      drivers.</font></td>
+    <td><font size="2">? depends on database</font></td>
+    <td><font size="2">ODBC</font></td>
+    <td><font size="2">Unix and Windows. <a href="http://phpbuilder.com/columns/alberto20000919.php3?page=4">Unix 
+      hints.</a></font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">odbc_mssql</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Uses ODBC to connect to MSSQL</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ODBC</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">odbc_oracle</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Uses ODBC to connect to Oracle</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">ODBC</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="34"><b><font size="2">oracle</font></b></td>
+    <td height="34"><font size="2">C</font></td>
+    <td height="34"><font size="2">Implements old Oracle 7 client API. Use oci8 
+      driver if possible for better performance.</font></td>
+    <td height="34"><font size="2">Y/N</font></td>
+    <td height="34"><font size="2">Oracle client</font></td>
+    <td height="34"><font size="2">Unix and Windows</font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">postgres</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">Generic PostgreSQL driver. Currently identical to postgres7 
+      driver. </font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">PostgreSQL client</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">postgres64</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">For PostgreSQL 6.4 and earlier which does not support LIMIT 
+      internally.</font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">PostgreSQL client</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">postgres7</font></b></td>
+    <td><font size="2">A</font></td>
+    <td><font size="2">PostgreSQL which supports LIMIT and other version 7 functionality.</font></td>
+    <td><font size="2">Y</font></td>
+    <td><font size="2">PostgreSQL client</font></td>
+    <td><font size="2">Unix and Windows. </font></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">sapdb</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">SAP DB. Should work reliably as based on ODBC driver.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">SAP ODBC client</font></td>
+    <td> <p><font size="2">?</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">sqlanywhere</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Sybase SQL Anywhere. Should work reliably as based on ODBC 
+      driver.</font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">SQL Anywhere ODBC client</font></td>
+    <td> <p><font size="2">?</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td height="54"><b><font size="2">sqlite</font></b></td>
+    <td height="54"><font size="2">B</font></td>
+    <td height="54"><font size="2">SQLite. Only tested on PHP5.</font></td>
+    <td height="54"><font size="2">Y</font></td>
+    <td height="54"><font size="2">-</font></td>
+    <td height="54"> <p><font size="2">Unix and Windows.</font></p></td>
+  </tr>
+  <tr valign="top"> 
+    <td><b><font size="2">sybase</font></b></td>
+    <td><font size="2">C</font></td>
+    <td><font size="2">Sybase. </font></td>
+    <td><font size="2">Y/N</font></td>
+    <td><font size="2">Sybase client</font></td>
+    <td> <p><font size="2">Unix and Windows.</font></p></td>
+  </tr>
+  <p> 
+</table>
+
+<p>The &quot;Tested&quot; column indicates how extensively the code has been tested 
+  and used. <br>
+  A = well tested and used by many people<br>
+  B = tested and usable, but some features might not be implemented<br>
+  C = user contributed or experimental driver. Might not fully support all of 
+  the latest features of ADOdb. </p>
+<p>The column &quot;RecordCount() usable&quot; indicates whether RecordCount() 
+  return the number of rows, or returns -1 when a SELECT statement is executed. 
+  If this column displays Y/N then the RecordCount() is emulated when the global 
+  variable $ADODB_COUNTRECS=true (this is the default). Note that for large recordsets, 
+  it might be better to disable RecordCount() emulation because substantial amounts 
+  of memory are required to cache the recordset for counting. Also there is a 
+  speed penalty of 40-50% if emulation is required. This is emulated in most databases 
+  except for PostgreSQL and MySQL. This variable is checked every time a query 
+  is executed, so you can selectively choose which recordsets to count.</p>
+<p> 
+<hr>
+<h1>Tutorials<a name="quickstart"></a></h1>
+<h3>Example 1: Select Statement<a name="ex1"></a></h3>
+<p>Task: Connect to the Access Northwind DSN, display the first 2 columns of each 
+  row.</p>
+<p>In this example, we create a ADOConnection object, which represents the connection 
+  to the database. The connection is initiated with <a href="#pconnect"><font face="Courier New, Courier, mono">PConnect</font></a>, 
+  which is a persistent connection. Whenever we want to query the database, we 
+  call the <font face="Courier New, Courier, mono">ADOConnection.<a href="#execute">Execute</a>()</font> 
+  function. This returns an ADORecordSet object which is actually a cursor that 
+  holds the current row in the array <font face="Courier New, Courier, mono">fields[]</font>. 
+  We use <font face="Courier New, Courier, mono"><a href="#movenext">MoveNext</a>()</font> 
+  to move from row to row.</p>
+<p>NB: A useful function that is not used in this example is <font face="Courier New, Courier, mono"><a href="#selectlimit">SelectLimit</a></font>, 
+  which allows us to limit the number of rows shown. 
+<pre>
+&lt;?
+<font face="Courier New, Courier, mono"><b>include</b>('adodb.inc.php');          # load code common to ADOdb
+$<font color="#660000">conn</font> = &amp;ADONewConnection('access');  # create a connection
+$<font color="#660000">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind DSN
+$<font color="#660000">recordSet</font> = &amp;$<font color="#660000">conn</font>->Execute('select * from products');
+if (!$<font color="#660000">recordSet</font>) 
+       print $<font color="#660000">conn</font>-&gt;ErrorMsg();
+else
+<b>while</b> (!$<font color="#660000">recordSet</font>-&gt;EOF) &#123;
+       <b>print</b> $<font color="#660000">recordSet</font>->fields[0].' '.$<font color="#660000">recordSet</font>->fields[1].'&lt;BR&gt;';
+       $<font color="#660000">recordSet</font>-&gt;MoveNext();
+&#125;</font><font face="Courier New, Courier, mono">
+
+$<font color="#660000">recordSet</font>->Close(); # optional
+$<font color="#660000">conn</font>->Close(); # optional
+</font>
+?>
+</pre>
+<p>The $<font face="Courier New, Courier, mono">recordSet</font> returned stores 
+  the current row in the <font face="Courier New, Courier, mono">$recordSet-&gt;fields</font> 
+  array, indexed by column number (starting from zero). We use the <font face="Courier New, Courier, mono"><a href="#movenext">MoveNext</a>()</font> 
+  function to move to the next row. The <font face="Courier New, Courier, mono">EOF</font> 
+  property is set to true when end-of-file is reached. If an error occurs in Execute(), 
+  we return false instead of a recordset.</p>
+<p>The <code>$recordSet-&gt;fields[]</code> array is generated by the PHP database 
+  extension. Some database extensions only index by number and do not index the 
+  array by field name. To force indexing by name - that is associative arrays 
+  - use the SetFetchMode function. Each recordset saves and uses whatever fetch 
+  mode was set when the recordset was created in Execute() or SelectLimit(). 
+<pre>
+       $db->SetFetchMode(ADODB_FETCH_NUM);
+       $rs1 = $db->Execute('select * from table');
+       $db->SetFetchMode(ADODB_FETCH_ASSOC);
+       $rs2 = $db->Execute('select * from table');
+       print_r($rs1->fields); # shows <i>array([0]=>'v0',[1] =>'v1')</i>
+       print_r($rs2->fields); # shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i>
+</pre>
+<p> </p>
+<p>To get the number of rows in the select statement, you can use <font face="Courier New, Courier, mono">$recordSet-&gt;<a href="#recordcount">RecordCount</a>()</font>. 
+  Note that it can return -1 if the number of rows returned cannot be determined.</p>
+<h3>Example 2: Advanced Select with Field Objects<a name="ex2"></a></h3>
+<p>Select a table, display the first two columns. If the second column is a date 
+  or timestamp, reformat the date to US format.</p>
+<pre>
+&lt;?
+<font face="Courier New, Courier, mono"><b>include</b>('adodb.inc.php');          # load code common to ADOdb
+$<font color="#660000">conn</font> = &amp;ADONewConnection('access');  # create a connection
+$<font color="#660000">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind dsn
+$<font color="#660000">recordSet</font> = &amp;$<font color="#660000">conn</font>->Execute('select CustomerID,OrderDate from Orders');
+if (!$<font color="#660000">recordSet</font>) 
+       print $<font color="#660000">conn</font>-&gt;ErrorMsg();
+else
+<b>while</b> (!$<font color="#660000">recordSet</font>-&gt;EOF) &#123;
+       $<font color="#660000">fld</font> = <font color="#336600"><b>$</b><font color="#660000">recordSet</font><b>-&gt;FetchField</b></font><font color="#006600">(</font>1<font color="#006600">);</font>
+       $<font color="#660000">type</font> = <font color="#336600"><b>$</b><font color="#660000">recordSet</font><b>-&gt;MetaType</b></font>($fld-&gt;type);
+
+       <b>if</b> ( $<font color="#660000">type</font> == 'D' || $<font color="#660000">type</font> == 'T') 
+               <b>print</b> $<font color="#660000">recordSet</font>-&gt;fields[0].' '.
+                       <b><font color="#336600">$</font></b><font color="#660000">recordSet</font><b><font color="#336600">-&gt;UserDate</font></b>($<font color="#660000">recordSet</font>-&gt;fields[1],'<b>m/d/Y</b>').'&lt;BR&gt;';
+       <b>else </b>
+               <b>print</b> $<font color="#660000">recordSet</font>->fields[0].' '.$<font color="#660000">recordSet</font>->fields[1].'&lt;BR&gt;';
+
+       $<font color="#660000">recordSet</font>-&gt;MoveNext();
+&#125;</font><font face="Courier New, Courier, mono">
+$<font color="#660000">recordSet</font>->Close(); # optional
+$<font color="#660000">conn</font>->Close(); # optional
+</font>
+?>
+</pre>
+<p>In this example, we check the field type of the second column using <font face="Courier New, Courier, mono"><a href="#fetchfield">FetchField</a>().</font> 
+  This returns an object with at least 3 fields.</p>
+<ul>
+  <li><b>name</b>: name of column</li>
+  <li> <b>type</b>: native field type of column</li>
+  <li> <b>max_length</b>: maximum length of field. Some databases such as MySQL 
+    do not return the maximum length of the field correctly. In these cases max_length 
+    will be set to -1.</li>
+</ul>
+<p>We then use <font face="Courier New, Courier, mono"><a href="#metatype">MetaType</a>()</font> 
+  to translate the native type to a <i>generic</i> type. Currently the following 
+  <i>generic</i> types are defined:</p>
+<ul>
+  <li><b>C</b>: character fields that should be shown in a &lt;input type=&quot;text&quot;&gt; 
+    tag.</li>
+  <li><b>X</b>: TeXt, large text fields that should be shown in a &lt;textarea&gt;</li>
+  <li><b>B</b>: Blobs, or Binary Large Objects. Typically images. 
+  <li><b>D</b>: Date field</li>
+  <li><b>T</b>: Timestamp field</li>
+  <li><b>L</b>: Logical field (boolean or bit-field)</li>
+  <li><b>I</b>:&nbsp; Integer field</li>
+  <li><b>N</b>: Numeric field. Includes autoincrement, numeric, floating point, 
+    real and integer. </li>
+  <li><b>R</b>: Serial field. Includes serial, autoincrement integers. This works 
+    for selected databases. </li>
+</ul>
+<p>If the metatype is of type date or timestamp, then we print it using the user 
+  defined date format with <font face="Courier New, Courier, mono"><a href="#userdate">UserDate</a>(),</font> 
+  which converts the PHP SQL date string format to a user defined one. Another 
+  use for <font face="Courier New, Courier, mono"><a href="#metatype">MetaType</a>()</font> 
+  is data validation before doing an SQL insert or update.</p>
+<h3>Example 3: Inserting<a name="ex3"></a></h3>
+<p>Insert a row to the Orders table containing dates and strings that need to 
+  be quoted before they can be accepted by the database, eg: the single-quote 
+  in the word <i>John's</i>.</p>
+<pre>
+&lt;?
+<b>include</b>('adodb.inc.php');          # load code common to ADOdb
+$<font color="#660000">conn</font> = &amp;ADONewConnection('access');  # create a connection
+
+$<font color="#660000">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind dsn
+$<font color="#660000">shipto</font> = <font color="#006600"><b>$conn-&gt;qstr</b></font>(&quot;<i>John's Old Shoppe</i>&quot;);
+
+$<font color="#660000">sql</font> = &quot;insert into orders (customerID,EmployeeID,OrderDate,ShipName) &quot;;
+$<font color="#660000">sql</font> .= &quot;values ('ANATR',2,&quot;.<b><font color="#006600">$conn-&gt;DBDate(</font>time()<font color="#006600">)</font></b><font color="#006600">.</font>&quot;,$<font color="#660000">shipto</font>)&quot;;
+
+<b>if</b> ($<font color="#660000">conn</font>->Execute($<font color="#660000">sql</font>) <font color="#336600"><b>=== false</b></font>) &#123;
+       <b>print</b> 'error inserting: '.<font color="#336600"><b>$conn-&gt;ErrorMsg()</b></font>.'&lt;BR&gt;';
+&#125;
+?>
+</pre>
+<p>In this example, we see the advanced date and quote handling facilities of 
+  ADOdb. The unix timestamp (which is a long integer) is appropriately formated 
+  for Access with <font face="Courier New, Courier, mono"><a href="#dbdate">DBDate</a>()</font>, 
+  and the right escape character is used for quoting the <i>John's Old Shoppe</i>, 
+  which is<b> </b><i>John'<b>'</b>s Old Shoppe</i> and not PHP's default <i>John<b>'</b>s 
+  Old Shoppe</i> with <font face="Courier New, Courier, mono"><a href="#qstr">qstr</a>()</font>. 
+</p>
+<p>Observe the error-handling of the Execute statement. False is returned by<font face="Courier New, Courier, mono"> 
+  <a href="#execute">Execute</a>() </font>if an error occured. The error message 
+  for the last error that occurred is displayed in <font face="Courier New, Courier, mono"><a href="#errormsg">ErrorMsg</a>()</font>. 
+  Note: <i>php_track_errors</i> might have to be enabled for error messages to 
+  be saved.</p>
+<h3> Example 4: Debugging<a name="ex4"></a></h3>
+<pre>&lt;?
+<b>include</b>('adodb.inc.php');          # load code common to ADOdb
+$<font color="#663300">conn</font> = &amp;ADONewConnection('access');  # create a connection
+$<font color="#663300">conn</font>->PConnect('northwind');   # connect to MS-Access, northwind dsn
+<font color="#000000">$<font color="#663300">shipto</font> = <b>$conn-&gt;qstr</b>(&quot;John's Old Shoppe&quot;);
+$<font color="#663300">sql</font> = &quot;insert into orders (customerID,EmployeeID,OrderDate,ShipName) &quot;;
+$<font color="#663300">sql</font> .= &quot;values ('ANATR',2,&quot;.$<font color="#663300">conn</font>-&gt;FormatDate(time()).&quot;,$shipto)&quot;;
+<b><font color="#336600">$<font color="#663300">conn</font>-&gt;debug = true;</font></b>
+<b>if</b> ($<font color="#663300">conn</font>->Execute($sql) <b>=== false</b>) <b>print</b> 'error inserting';</font>
+?&gt;
+</pre>
+<p>In the above example, we have turned on debugging by setting <b>debug = true</b>. 
+  This will display the SQL statement before execution, and also show any error 
+  messages. There is no need to call <font face="Courier New, Courier, mono"><a href="#errormsg">ErrorMsg</a>()</font> 
+  in this case. For displaying the recordset, see the <font face="Courier New, Courier, mono"><a href="#exrs2html">rs2html</a>() 
+  </font>example.</p>
+<p>Also see the section on <a href=#errorhandling>Custom Error Handlers</a>.</p>
+<h3>Example 5: MySQL and Menus<a name="ex5"></a></h3>
+<p>Connect to MySQL database <i>agora</i>, and generate a &lt;select&gt; menu 
+  from an SQL statement where the &lt;option&gt; captions are in the 1st column, 
+  and the value to send back to the server is in the 2nd column.</p>
+<pre>&lt;?
+<b>include</b>('adodb.inc.php'); # load code common to ADOdb
+$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');  # create a connection
+$<font color="#663300">conn</font>->PConnect('localhost','userid','','agora');# connect to MySQL, agora db
+<font color="#000000">$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers';
+$<font color="#663300">rs</font> = $<font color="#663300">conn</font>->Execute($sql);
+<b>print</b> <b><font color="#336600">$<font color="#663300">rs</font>-&gt;GetMenu('GetCust','Mary Rosli');
+?&gt;</font></b></font></pre>
+<p>Here we define a menu named GetCust, with the menu option 'Mary Rosli' selected. 
+  See <a href="#getmenu"><font face="Courier New, Courier, mono">GetMenu</font></a><font face="Courier New, Courier, mono">()</font>. 
+  We also have functions that return the recordset as an array: <font face="Courier New, Courier, mono"><a href="#getarray">GetArray</a>()</font>, 
+  and as an associative array with the key being the first column: <a href="#getassoc1">GetAssoc</a>().</p>
+<h3>Example 6: Connecting to 2 Databases At Once<a name="ex6"></a></h3>
+<pre>&lt;?
+<b>include</b>('adodb.inc.php');        # load code common to ADOdb
+$<font color="#663300">conn1</font> = &amp;ADONewConnection('mysql');  # create a mysql connection
+$<font color="#663300">conn2</font> = &amp;ADONewConnection('oracle');  # create a oracle connection
+
+$conn1-&gt;PConnect($server, $userid, $password, $database);
+$conn2-&gt;PConnect(false, $ora_userid, $ora_pwd, $oraname);
+
+$conn1-&gt;Execute('insert ...');
+$conn2-&gt;Execute('update ...');
+?&gt;</pre>
+<p> 
+<h3>Example 7: Generating Update and Insert SQL<a name="ex7"></a></h3>
+ADOdb 1.31 and later supports two new recordset functions: GetUpdateSQL( ) and 
+GetInsertSQL( ). This allow you to perform a "SELECT * FROM table query WHERE...", 
+make a copy of the $rs->fields, modify the fields, and then generate the SQL to 
+update or insert into the table automatically. 
+<p> We show how the functions can be used when accessing a table with the following 
+  fields: (ID, FirstName, LastName, Created). 
+<p> Before these functions can be called, you need to initialize the recordset 
+  by performing a select on the table. Idea and code by Jonathan Younger jyounger#unilab.com. 
+<p> 
+<pre>&lt;?
+#==============================================
+# SAMPLE GetUpdateSQL() and GetInsertSQL() code
+#==============================================
+include('adodb.inc.php');
+include('tohtml.inc.php');
+
+#==========================
+# This code tests an insert
+
+$sql = "SELECT * FROM ADOXYZ WHERE id = -1"; 
+# Select an empty record from the database
+
+$conn = &ADONewConnection("mysql");  # create a connection
+$conn->debug=1;
+$conn->PConnect("localhost", "admin", "", "test"); # connect to MySQL, testdb
+$rs = $conn->Execute($sql); # Execute the query and get the empty recordset
+
+$record = array(); # Initialize an array to hold the record data to insert
+
+# Set the values for the fields in the record
+# Note that field names are case-insensitive
+$record["firstname"] = "Bob";
+$record["lastNamE"] = "Smith";
+$record["creaTed"] = time();
+
+# Pass the empty recordset and the array containing the data to insert
+# into the GetInsertSQL function. The function will process the data and return
+# a fully formatted insert sql statement.
+$insertSQL = $conn->GetInsertSQL($rs, $record);
+
+$conn->Execute($insertSQL); # Insert the record into the database
+
+#==========================
+# This code tests an update
+
+$sql = "SELECT * FROM ADOXYZ WHERE id = 1"; 
+# Select a record to update
+
+$rs = $conn->Execute($sql); # Execute the query and get the existing record to update
+
+$record = array(); # Initialize an array to hold the record data to update
+
+# Set the values for the fields in the record
+# Note that field names are case-insensitive
+$record["firstname"] = "Caroline";
+$record["LasTnAme"] = "Smith"; # Update Caroline's lastname from Miranda to Smith
+
+# Pass the single record recordset and the array containing the data to update
+# into the GetUpdateSQL function. The function will process the data and return
+# a fully formatted update sql statement with the correct WHERE clause.
+# If the data has not changed, no recordset is returned
+$updateSQL = $conn->GetUpdateSQL($rs, $record);
+
+$conn->Execute($updateSQL); # Update the record in the database
+$conn->Close();
+?>
+</pre>
+<h3>Example 8: Implementing Scrolling with Next and Previous<a name="ex8"></a></h3>
+<p> The following code creates a very simple recordset pager, where you can scroll 
+  from page to page of a recordset.</p>
+<pre>
+include_once('../adodb.inc.php');
+include_once('../adodb-pager.inc.php');
+session_start();
+
+$db = NewADOConnection('mysql');
+
+$db->Connect('localhost','root','','xphplens');
+
+$sql = "select * from adoxyz ";
+
+$pager = new ADODB_Pager($db,$sql);
+$pager->Render($rows_per_page=5);</pre>
+<p>This will create a basic record pager that looks like this: <a name="scr"></a> 
+<p> 
+<table border=1 bgcolor=beige>
+  <tr> 
+    <td> <a href="#scr"><code>|&lt;</code></a> &nbsp; <a href="#scr"><code>&lt;&lt;</code></a> 
+      &nbsp; <a href="#scr"><code>>></code></a> &nbsp; <a href="#scr"><code>>|</code></a> 
+      &nbsp; </td>
+  </tr>
+  <tr>
+    <td><TABLE COLS=4 width=100% border=1 bgcolor=white>
+        <TH>ID</TH>
+        <TH>First Name</TH>
+        <TH>Last Name</TH>
+        <TH>Date Created</TH>
+        <TR> 
+          <TD align=right>36&nbsp;</TD>
+          <TD>Alan&nbsp;</TD>
+          <TD>Turing&nbsp;</TD>
+          <TD>Sat 06, Oct 2001&nbsp;</TD>
+        </TR>
+        <TR> 
+          <TD align=right>37&nbsp;</TD>
+          <TD>Serena&nbsp;</TD>
+          <TD>Williams&nbsp;</TD>
+          <TD>Sat 06, Oct 2001&nbsp;</TD>
+        </TR>
+        <TR> 
+          <TD align=right>38&nbsp;</TD>
+          <TD>Yat Sun&nbsp;</TD>
+          <TD>Sun&nbsp;</TD>
+          <TD>Sat 06, Oct 2001&nbsp;</TD>
+        </TR>
+        <TR> 
+          <TD align=right>39&nbsp;</TD>
+          <TD>Wai Hun&nbsp;</TD>
+          <TD>See&nbsp;</TD>
+          <TD>Sat 06, Oct 2001&nbsp;</TD>
+        </TR>
+        <TR> 
+          <TD align=right>40&nbsp;</TD>
+          <TD>Steven&nbsp;</TD>
+          <TD>Oey&nbsp;</TD>
+          <TD>Sat 06, Oct 2001&nbsp;</TD>
+        </TR>
+      </TABLE></td>
+  </tr>
+  <tr>
+    <td><font size=-1>Page 8/10</font></td>
+  </tr>
+</table>
+<p>The number of rows to display at one time is controled by the Render($rows) 
+  method. If you do not pass any value to Render(), ADODB_Pager will default to 
+  10 records per page. 
+<p>You can control the column titles by modifying your SQL (supported by most 
+  databases): 
+<pre>$sql = 'select id as &quot;ID&quot;, firstname as &quot;First Name&quot;, 
+                 lastname as &quot;Last Name&quot;, created as &quot;Date Created&quot; <br>           from adoxyz';</pre>
+<p>The above code can be found in the <i>adodb/tests/testpaging.php</i> example 
+  included with this release, and the class ADODB_Pager in <i>adodb/adodb-pager.inc.php</i>. 
+  The ADODB_Pager code can be adapted by a programmer so that the text links can 
+  be replaced by images, and the dull white background be replaced with more interesting 
+  colors. 
+<p>You can also allow display of html by setting $pager->htmlSpecialChars = false. 
+<p>Some of the code used here was contributed by Iv&aacute;n Oliva and Cornel 
+  G. </p>
+<h3><a name="ex9"></a>Example 9: Exporting in CSV or Tab-Delimited Format</h3>
+<p>We provide some helper functions to export in comma-separated-value (CSV) and 
+  tab-delimited formats:</p>
+<pre><b>include_once('/path/to/adodb/toexport.inc.php');</b><br>include_once('/path/to/adodb/adodb.inc.php');<br>
+$db = &amp;NewADOConnection('mysql');<br>$db-&gt;Connect($server, $userid, $password, $database);<br><br>$rs = $db-&gt;Execute('select fname as &quot;First Name&quot;, surname as &quot;Surname&quot; from table');
+
+print &quot;&lt;pre&gt;&quot;;<br>print <b>rs2csv</b>($rs); # return a string, CSV format<p>print '&lt;hr&gt;';
+<br>$rs-&gt;MoveFirst(); # note, some databases do not support MoveFirst<br>print <b>rs2tab</b>($rs,<i>false</i>); # return a string, tab-delimited
+                                                # false == suppress field names in first line</p>print '&lt;hr&gt;';<br>$rs-&gt;MoveFirst();<br><b>rs2tabout</b>($rs); # send to stdout directly (there is also an rs2csvout function)
+print &quot;&lt;/pre&gt;&quot;;
+
+$rs-&gt;MoveFirst();<br><b></b>$fp = fopen($path, &quot;w&quot;);
+if ($fp) {<br>  <b>rs2csvfile</b>($rs, $fp); # write to file (there is also an rs2tabfile function)
+  fclose($fp);<br>}
+</pre>
+<p> Carriage-returns or newlines are converted to spaces. Field names are returned 
+  in the first line of text. Strings containing the delimiter character are quoted 
+  with double-quotes. Double-quotes are double-quoted again. This conforms to 
+  Excel import and export guide-lines. 
+<p>All the above functions take as an optional last parameter, $addtitles which 
+  defaults to <i>true</i>. When set to <i>false</i> field names in the first line 
+  are suppressed. <br>
+<h3>Example 10: Recordset Filters<a name="ex10"></a></h3>
+<p>Sometimes we want to pre-process all rows in a recordset before we use it. 
+  For example, we want to ucwords all text in recordset. 
+<pre>
+include_once('adodb/rsfilter.inc.php');
+include_once('adodb/adodb.inc.php');
+
+// ucwords() every element in the recordset
+function do_ucwords(&$arr,$rs)
+&#123;
+       foreach($arr as $k => $v) &#123;
+               $arr[$k] = ucwords($v);
+       &#125;
+&#125;
+
+$db = NewADOConnection('mysql');
+$db->PConnect('server','user','pwd','db');
+
+$rs = $db->Execute('select ... from table');
+$rs = <b>RSFilter</b>($rs,'do_ucwords');
+</pre>
+<p>The <i>RSFilter</i> function takes 2 parameters, the recordset, and the name 
+  of the <i>filter</i> function. It returns the processed recordset scrolled to 
+  the first record. The <i>filter</i> function takes two parameters, the current 
+  row as an array, and the recordset object. For future compatibility, you should 
+  not use the original recordset object. </p>
+<h3>Example 11:<a name="ex11"></a> Smart Transactions</h3>
+The old way of doing transactions required you to use 
+<pre>
+$conn-><b>BeginTrans</b>();
+$ok = $conn->Execute($sql);
+if ($ok) $ok = $conn->Execute($sql2);
+if (!$ok) $conn-><b>RollbackTrans</b>();
+else $conn-><b>CommitTrans</b>();
+</pre>
+This is very complicated for large projects because you have to track the error 
+status. Smart Transactions is much simpler. You start a smart transaction by calling 
+StartTrans(): 
+<pre>
+$conn-><b>StartTrans</b>();
+$conn->Execute($sql);
+$conn->Execute($Sql2);
+$conn-><b>CompleteTrans</b>();
+</pre>
+CompleteTrans() detects when an SQL error occurs, and will Rollback/Commit as 
+appropriate. To specificly force a rollback even if no error occured, use FailTrans(). 
+Note that the rollback is done in CompleteTrans(), and not in FailTrans(). 
+<pre>
+$conn-><b>StartTrans</b>();
+$conn->Execute($sql);
+if (!CheckRecords()) $conn-><strong>FailTrans</strong>();
+$conn->Execute($Sql2);
+$conn-><b>CompleteTrans</b>();
+</pre>
+<p>You can also check if a transaction has failed, using HasFailedTrans(), which 
+  returns true if FailTrans() was called, or there was an error in the SQL execution. 
+  Make sure you call HasFailedTrans() before you call CompleteTrans(), as it is 
+  only works between StartTrans/CompleteTrans.
+<p>Lastly, StartTrans/CompleteTrans is nestable, and only the outermost block 
+  is executed. In contrast, BeginTrans/CommitTrans/RollbackTrans is NOT nestable. 
+<pre>
+$conn-><strong>StartTrans</strong>();
+$conn->Execute($sql);
+  $conn-><strong>StartTrans</strong>();    <font color="#006600"># ignored</font>
+  if (!CheckRecords()) $conn->FailTrans();
+  $conn-><strong>CompleteTrans</strong>(); <font color="#006600"># ignored</font>
+$conn->Execute($Sql2);
+$conn-><strong>CompleteTrans</strong>();
+</pre>
+<p>Note: Savepoints are currently not supported. 
+<h2><a name="errorhandling"></a>Using Custom Error Handlers and PEAR_Error</h2>
+Apart from the old $con->debug = true; way of debugging, ADOdb 1.50 onwards provides 
+another way of handling errors using ADOdb's custom error handlers. 
+<p> ADOdb provides two custom handlers which you can modify for your needs. The 
+  first one is in the <b>adodb-errorhandler.inc.php</b> file. This makes use of 
+  the standard PHP functions <a href=http://php.net/error_reporting>error_reporting</a> 
+  to control what error messages types to display, and <a href=http://php.net/trigger_error>trigger_error</a> 
+  which invokes the default PHP error handler. 
+<p> Including the above file will cause <i>trigger_error($errorstring,E_USER_ERROR)</i> 
+  to be called when<br>
+  (a) Connect() or PConnect() fails, or <br>
+  (b) a function that executes SQL statements such as Execute() or SelectLimit() 
+  has an error.<br>
+  (c) GenID() appears to go into an infinite loop. 
+<p> The $errorstring is generated by ADOdb and will contain useful debugging information 
+  similar to the error.log data generated below. This file adodb-errorhandler.inc.php 
+  should be included before you create any ADOConnection objects. 
+<p> If you define error_reporting(0), no errors will be passed to the error handler. 
+  If you set error_reporting(E_ALL), all errors will be passed to the error handler. 
+  You still need to use <b>ini_set("display_errors", "0" or "1")</b> to control 
+  the display of errors. 
+<pre>
+&lt;?php
+<b>error_reporting(E_ALL); # pass any error messages triggered to error handler
+include('adodb-errorhandler.inc.php');</b>
+include('adodb.inc.php');
+include('tohtml.inc.php');
+$c = NewADOConnection('mysql');
+$c->PConnect('localhost','root','','northwind');
+$rs=$c->Execute('select * from productsz'); #invalid table productsz');
+if ($rs) rs2html($rs);
+?>
+</pre>
+<p> If you want to log the error message, you can do so by defining the following 
+  optional constants ADODB_ERROR_LOG_TYPE and ADODB_ERROR_LOG_DEST. ADODB_ERROR_LOG_TYPE 
+  is the error log message type (see <a href=http://php.net/error_log>error_log</a> 
+  in the PHP manual). In this case we set it to 3, which means log to the file 
+  defined by the constant ADODB_ERROR_LOG_DEST. 
+<pre>
+&lt;?php
+<b>error_reporting(E_ALL); # report all errors
+ini_set("display_errors", "0"); # but do not echo the errors
+define('ADODB_ERROR_LOG_TYPE',3);
+define('ADODB_ERROR_LOG_DEST','C:/errors.log');
+include('adodb-errorhandler.inc.php');</b>
+include('adodb.inc.php');
+include('tohtml.inc.php');
+
+$c = NewADOConnection('mysql');
+$c->PConnect('localhost','root','','northwind');
+$rs=$c->Execute('select * from productsz'); ## invalid table productsz
+if ($rs) rs2html($rs);
+?>
+</pre>
+The following message will be logged in the error.log file: 
+<pre>
+(2001-10-28 14:20:38) mysql error: [1146: Table 'northwind.productsz' doesn't exist] in
+ EXECUTE("select * from productsz")
+</pre>
+The second error handler is <b>adodb-errorpear.inc.php</b>. This will create a 
+PEAR_Error derived object whenever an error occurs. The last PEAR_Error object 
+created can be retrieved using ADODB_Pear_Error(). 
+<pre>
+&lt;?php
+<b>include('adodb-errorpear.inc.php');</b>
+include('adodb.inc.php');
+include('tohtml.inc.php');
+$c = NewADOConnection('mysql');
+$c->PConnect('localhost','root','','northwind');
+$rs=$c->Execute('select * from productsz'); #invalid table productsz');
+if ($rs) rs2html($rs);
+else &#123;
+       <b>$e = ADODB_Pear_Error();
+       echo '&lt;p>',$e->message,'&lt;/p>';</b>
+&#125;
+?>
+</pre>
+<p> You can use a PEAR_Error derived class by defining the constant ADODB_PEAR_ERROR_CLASS 
+  before the adodb-errorpear.inc.php file is included. For easy debugging, you 
+  can set the default error handler in the beginning of the PHP script to PEAR_ERROR_DIE, 
+  which will cause an error message to be printed, then halt script execution: 
+<pre>
+include('PEAR.php');
+PEAR::setErrorHandling('PEAR_ERROR_DIE');
+</pre>
+<p> Note that we do not explicitly return a PEAR_Error object to you when an error 
+  occurs. We return false instead. You have to call ADODB_Pear_Error() to get 
+  the last error or use the PEAR_ERROR_DIE technique. 
+<h4>Error Messages</h4>
+<p>Error messages are outputted using the static method ADOConnnection::outp($msg,$newline=true). 
+  By default, it sends the messages to the client. You can override this to perform 
+  error-logging. 
+<h2><a name="dsn"></a> Data Source Names</h2>
+<p>We now support connecting using PEAR style DSN's. A DSN is a connection string 
+  of the form:</p>
+<p>$dsn = <i>&quot;$driver://$username:$password@$hostname/$databasename&quot;</i>;</p>
+<p>You pass the DSN to the static class function DB::Connect. An example:</p>
+<pre>   include_once('../adodb/adodb-pear.inc.php');
+   $username = 'root';
+   $password = '';
+   $hostname = 'localhost';
+   $databasename = 'xphplens';
+   $driver = 'mysql';
+   $dsn = &quot;$driver://$username:$password@$hostname/$databasename&quot;;</pre>
+<pre>   $db = DB::Connect($dsn);<br>   $rs = $db-&gt;Execute('select firstname,lastname from adoxyz');
+   $cnt = 0;
+   while ($arr = $rs-&gt;FetchRow()) {
+               print_r($arr); print &quot;&lt;br&gt;&quot;;
+   }</pre>
+<p>This requires PEAR to be installed and in the default include path in php.ini.</p>
+<h2><a name="caching"></a>Caching of Recordsets</h2>
+<p>ADOdb now supports caching of recordsets using the CacheExecute( ), CachePageExecute( 
+  ) and CacheSelectLimit( ) functions. There are similar to the non-cache functions, 
+  except that they take a new first parameter, $secs2cache. 
+<p> An example: 
+<pre>
+<b>include</b>('adodb.inc.php'); # load code common to ADOdb
+$ADODB_CACHE_DIR = '/usr/ADODB_cache';
+$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');  # create a connection
+$<font color="#663300">conn</font>->PConnect('localhost','userid','','agora');# connect to MySQL, agora db
+<font color="#000000">$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers';
+$<font color="#663300">rs</font> = $<font color="#663300">conn</font>->CacheExecute(15,$sql);</font></pre>
+<p><font color="#000000"> The first parameter is the number of seconds to cache 
+  the query. Subsequent calls to that query will used the cached version stored 
+  in $ADODB_CACHE_DIR. To force a query to execute and flush the cache, call CacheExecute() 
+  with the first parameter set to zero. Alternatively, use the CacheFlush($sql) 
+  call. </font></p>
+<p><font color="#000000">For the sake of security, we recommend you set <i>register_globals=off</i> 
+  in php.ini if you are using $ADODB_CACHE_DIR.</font></p>
+<p>In ADOdb 1.80 onwards, the secs2cache parameter is optional in CacheSelectLimit() 
+  and CacheExecute(). If you leave it out, it will use the $connection->cacheSecs 
+  parameter, which defaults to 60 minutes. 
+<pre>
+       $conn->Connect(...);
+       $conn->cacheSecs = 3600*24; # cache 24 hours
+       $rs = $conn->CacheExecute('select * from table');
+</pre>
+<p>Please note that magic_quotes_runtime should be turned off. <a href=http://phplens.com/lens/lensforum/msgs.php?LeNs#LensBM_forummsg>More 
+  info</a>. <font color="#000000"> 
+<h2><a name="pivot"></a>Pivot Tables</h2>
+</font> <p><font color="#000000">Since ADOdb 2.30, we support the generation of 
+SQL to create pivot tables, also known as cross-tabulations. For further explanation 
+read this DevShed <a href=http://www.devshed.com/Server_Side/MySQL/MySQLWiz/>Cross-Tabulation 
+tutorial. We assume that your database supports the SQL case-when expression. </font></p> 
+<font color="#000000"> 
+<p>In this example, we will use the Northwind database from Microsoft. In the 
+  database, we have a products table, and we want to analyze this table by <i>suppliers 
+  versus product categories</i>. We will place the suppliers on each row, and 
+  pivot on categories. So from the table on the left, we generate the pivot-table 
+  on the right:</p>
+</font> 
+<table border="0" cellspacing="2" cellpadding="2" align="center">
+  <tr>
+       <td>
+         <table border="1" cellspacing="2" cellpadding="2" align="center" width="142">
+               <tr> 
+                 <td><i>Supplier</i></td>
+                 <td><i>Category</i></td>
+               </tr>
+               <tr> 
+                 <td>supplier1</td>
+                 <td>category1</td>
+               </tr>
+               <tr> 
+                 <td>supplier2</td>
+                                       <td>category1</td>
+               </tr>
+               <tr> 
+                                       <td>supplier2</td>
+                 <td>category2</td>
+               </tr>
+         </table>
+       </td>
+       <td> <font face="Courier New, Courier, mono">--&gt;</font></td>
+       <td>
+         <table border="1" cellspacing="2" cellpadding="2" align="center">
+               <tr> 
+                 <td>&nbsp;</td>
+                 <td><i>category1</i></td>
+                 <td><i>category2</i></td>
+                 <td><i>total</i></td>
+               </tr>
+               <tr> 
+                 <td><i>supplier1</i></td>
+                 <td align="right">1</td>
+                 <td align="right">0</td>
+                 <td align="right">1</td>
+               </tr>
+               <tr> 
+                 <td><i>supplier2</i></td>
+                 <td align="right">1</td>
+                 <td align="right">1</td>
+                 <td align="right">2</td>
+               </tr>
+         </table>
+       </td>
+  </tr>
+</table>
+<font color="#000000"> 
+<p>The following code will generate the SQL for a cross-tabulation: 
+<pre>
+# Query the main "product" table
+# Set the rows to CompanyName
+# and the columns to the values of Categories
+# and define the joins to link to lookup tables 
+# "categories" and "suppliers"
+#
+ include &quot;adodb/pivottable.php&quot;;
+ $sql = PivotTableSQL(
+       $gDB,                                      # adodb connection
+       'products p ,categories c ,suppliers s',   # tables
+       'CompanyName',                             # rows (multiple fields allowed)
+       'CategoryName',                            # column to pivot on 
+       'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where
+);
+</pre>
+</font> 
+<p><font color="#000000"> This will generate the following SQL:</font></p>
+<p><code><font size="2">SELECT CompanyName, <br>
+  SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS &quot;Beverages&quot;, 
+  <br>
+  SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS &quot;Condiments&quot;, 
+  <br>
+  SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS &quot;Confections&quot;, 
+  <br>
+  SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS &quot;Dairy 
+  Products&quot;, <br>
+  SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS &quot;Grains/Cereals&quot;, 
+  <br>
+  SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS &quot;Meat/Poultry&quot;, 
+  <br>
+  SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS &quot;Produce&quot;, 
+  <br>
+  SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS &quot;Seafood&quot;, 
+  <br>
+  SUM(1) as Total <br>
+  FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID 
+  and s.SupplierID= p.SupplierID <br>
+  GROUP BY CompanyName</font></code></p>
+<p> You can also pivot on <i>numerical columns</i> and <i>generate totals</i> 
+       by using ranges. <font color="#000000">This code was revised in ADODB 2.41 
+       and is not backward compatible.</font> The second example shows this:</p>
+<pre>
+ $sql = PivotTableSQL(
+       $gDB,                                       # adodb connection
+       'products p ,categories c ,suppliers s',    # tables
+       'CompanyName',                              #<font color="#000000"> rows (multiple fields allowed)</font>
+   array(                                       # column ranges
+       ' 0 '      => 'UnitsInStock <= 0',
+       "1 to 5"   => '0 < UnitsInStock and UnitsInStock <= 5',
+       "6 to 10"  => '5 < UnitsInStock and UnitsInStock <= 10',
+       "11 to 15" => '10 < UnitsInStock and UnitsInStock <= 15',
+       "16+"      => '15 < UnitsInStock'
+       ),
+       ' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where
+       'UnitsInStock',                             # sum this field
+       'Sum '                                      # sum label prefix
+);
+</pre> 
+<p>Which generates: </p>
+<p> <code> <font size="2">SELECT CompanyName, <br>
+       SUM(CASE WHEN UnitsInStock &lt;= 0 THEN UnitsInStock ELSE 0 END) AS &quot;Sum 
+       0 &quot;, <br>
+       SUM(CASE WHEN 0 &lt; UnitsInStock and UnitsInStock &lt;= 5 THEN UnitsInStock 
+       ELSE 0 END) AS &quot;Sum 1 to 5&quot;,<br>
+       SUM(CASE WHEN 5 &lt; UnitsInStock and UnitsInStock &lt;= 10 THEN UnitsInStock 
+       ELSE 0 END) AS &quot;Sum 6 to 10&quot;,<br>
+       SUM(CASE WHEN 10 &lt; UnitsInStock and UnitsInStock &lt;= 15 THEN UnitsInStock 
+       ELSE 0 END) AS &quot;Sum 11 to 15&quot;, <br>
+       SUM(CASE WHEN 15 &lt; UnitsInStock THEN UnitsInStock ELSE 0 END) AS &quot;Sum 
+       16+&quot;, <br>
+       SUM(UnitsInStock) AS "Sum UnitsInStock", <br>
+       SUM(1) as Total,<br>
+       FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID 
+       and s.SupplierID= p.SupplierID <br>
+       GROUP BY CompanyName</font></code><font size="2"><br>
+       </font> </p>
+<font color="#000000"><hr>
+<h1>Class Reference<a name="ref"></a></h1>
+<p>Function parameters with [ ] around them are optional.</p>
+</font> 
+<h2>Global Variables</h2>
+<h3><font color="#000000"><a name="adodb_countrecs"></a></font>$ADODB_COUNTRECS</h3>
+<p>If the database driver API does not support counting the number of records 
+       returned in a SELECT statement, the function RecordCount() is emulated when 
+       the global variable $ADODB_COUNTRECS is set to true, which is the default. 
+       We emulate this by buffering the records, which can take up large amounts 
+       of memory for big recordsets. Set this variable to false for the best performance. 
+       This variable is checked every time a query is executed, so you can selectively 
+       choose which recordsets to count.</p>
+<h3><font color="#000000"><a name="adodb_cache_dir"></a>$ADODB_CACHE_DIR</font></h3>
+<font color="#000000"> 
+<p>If you are using recordset caching, this is the directory to save your recordsets 
+  in. Define this before you call any caching functions such as CacheExecute( 
+  ). We recommend setting <i>register_globals=off</i> in php.ini if you use this 
+  feature for security reasons.</p>
+<p>If you are using Unix and apache, you might need to set your cache directory 
+  permissions to something similar to the following:</p>
+</font> 
+<p>chown -R apache /path/to/adodb/cache<br>
+  chgrp -R apache /path/to/adodb/cache </p>
+<font color="#000000">
+<h3><a name="adodb_ansi_padding_off"></a>$ADODB_ANSI_PADDING_OFF</h3>
+<p>Determines whether to right trim CHAR fields (and also VARCHAR for ibase/firebird).
+Set to true to trim. Default is false. Currently works for oci8po, ibase and firebird 
+drivers. Added in ADOdb 4.01.
+<h3><font color="#000000"><a name="adodb_lang"></a></font>$ADODB_LANG</h3>
+<p>Determines the language used in MetaErrorMsg(). The default is 'en', for English. 
+To find out what languages are supported, see the files 
+in adodb/lang/adodb-$lang.inc.php, where $lang is the supported langauge.
+<h3><a name="adodb_fetch_mode"></a>$ADODB_FETCH_MODE</h3>
+<p>This is a global variable that determines how arrays are retrieved by recordsets. 
+  The recordset saves this value on creation (eg. in Execute( ) or SelectLimit( 
+  )), and any subsequent changes to $ADODB_FETCH_MODE have no affect on existing 
+  recordsets, only on recordsets created in the future.</p>
+<p>The following constants are defined:</p>
+</font> 
+<p><font color="#000000">define('ADODB_FETCH_DEFAULT',0);<br>
+  define('ADODB_FETCH_NUM',1);<br>
+  define('ADODB_FETCH_ASSOC',2);<br>
+  define('ADODB_FETCH_BOTH',3); </font></p>
+<font color="#000000"> 
+<p> An example: 
+<pre>
+       $ADODB_<b>FETCH_MODE</b> = ADODB_FETCH_NUM;
+       $rs1 = $db->Execute('select * from table');
+       $ADODB_<b>FETCH_MODE</b> = ADODB_FETCH_ASSOC;
+       $rs2 = $db->Execute('select * from table');
+       print_r($rs1->fields); # shows <i>array([0]=>'v0',[1] =>'v1')</i>
+       print_r($rs2->fields); # shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i>
+</pre>
+<p> As you can see in the above example, both recordsets store and use different 
+       fetch modes based on the $ADODB_FETCH_MODE setting when the recordset was 
+       created by Execute().</p>
+<p>If no fetch mode is predefined, the fetch mode defaults to ADODB_FETCH_DEFAULT. 
+       The behaviour of this default mode varies from driver to driver, so do not 
+       rely on ADODB_FETCH_DEFAULT. For portability, we recommend sticking to ADODB_FETCH_NUM 
+       or ADODB_FETCH_ASSOC. Many drivers do not support ADODB_FETCH_BOTH.</p>
+<p><strong>SetFetchMode Function</strong></p>
+<p>Some programmers prefer to use a more object-oriented solution, where the fetch 
+       mode is set by a object function, <a href="#setfetchmode">SetFetchMode</a>. 
+       Once this function is called for a connection object, that connection object 
+       will ignore the global variable $ADODB_FETCH_MODE and will use the internal 
+       fetchMode property exclusively.</p>
+<pre>
+       $db->SetFetchMode(ADODB_FETCH_NUM);
+       $rs1 = $db->Execute('select * from table');
+       $db->SetFetchMode(ADODB_FETCH_ASSOC);
+       $rs2 = $db->Execute('select * from table');
+       print_r($rs1->fields); # shows <i>array([0]=>'v0',[1] =>'v1')</i>
+       print_r($rs2->fields); # shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i></pre>
+<p>To retrieve the previous fetch mode, you can use check the $db-&gt;fetchMode 
+       property, or use the return value of SetFetchMode( ). 
+<p><strong><a name="adodb_assoc_case"></a>ADODB_ASSOC_CASE</strong></p>
+<p>You can control the associative fetch case for certain drivers which behave 
+       differently. For the sybase, oci8po, mssql, odbc and ibase drivers and all 
+       drivers derived from them, ADODB_ASSOC_CASE will by default generate recordsets 
+       where the field name keys are lower-cased. Use the constant ADODB_ASSOC_CASE 
+       to change the case of the keys. There are 3 possible values:</p>
+<p>0 = assoc lowercase field names. $rs-&gt;fields['orderid']<br>
+       1 = assoc uppercase field names. $rs-&gt;fields['ORDERID']<br>
+       2 = use native-case field names. $rs-&gt;fields['OrderID'] -- this is the 
+       default since ADOdb 2.90</p>
+<p>To use it, declare it before you incldue adodb.inc.php.</p>
+<p>define('ADODB_ASSOC_CASE', 2); # use native-case for ADODB_FETCH_ASSOC<br>
+       include('adodb.inc.php'); </p>
+<hr>
+<h2>ADOConnection<a name="adoconnection"></a></h2>
+<p>Object that performs the connection to the database, executes SQL statements 
+       and has a set of utility functions for standardising the format of SQL statements 
+       for issues such as concatenation and date formats.</p>
+<h3>ADOConnection Fields</h3>
+<p><b>databaseType</b>: Name of the database system we are connecting to. Eg. 
+       <b>odbc</b> or <b>mssql</b> or <b>mysql</b>.</p>
+<p><b>dataProvider</b>: The underlying mechanism used to connect to the database. 
+       Normally set to <b>native</b>, unless using <b>odbc</b> or <b>ado</b>.</p>
+<p><b>host: </b>Name of server or data source name (DSN) to connect to.</p>
+<p><b>database</b>: Name of the database or to connect to. If ado is used, it 
+       will hold the ado data provider.</p>
+<p><b>user</b>: Login id to connect to database. Password is not saved for security 
+       reasons.</p>
+<p><b>raiseErrorFn</b>: Allows you to define an error handling function. See adodb-errorhandler.inc.php 
+       for an example.</p>
+<p><b>debug</b>: Set to <i>true</i> to make debug statements to appear.</p>
+<p><b>concat_operator</b>: Set to '+' or '||' normally. The operator used to concatenate 
+       strings in SQL. Used by the <b><a href="#concat">Concat</a></b> function.</p>
+<p><b>fmtDate</b>: The format used by the <b><a href="#dbdate">DBDate</a></b> 
+       function to send dates to the database. is '#Y-m-d#' for Microsoft Access, 
+       and ''Y-m-d'' for MySQL.</p>
+<p><b>fmtTimeStamp: </b>The format used by the <b><a href="#dbtimestamp">DBTimeStamp</a></b> 
+       function to send timestamps to the database. </p>
+<p><b>true</b>: The value used to represent true.Eg. '.T.'. for Foxpro, '1' for 
+       Microsoft SQL.</p>
+<p><b>false: </b> The value used to represent false. Eg. '.F.'. for Foxpro, '0' 
+       for Microsoft SQL.</p>
+<p><b>replaceQuote</b>: The string used to escape quotes. Eg. double single-quotes 
+       for Microsoft SQL, and backslash-quote for MySQL. Used by <a href="#qstr">qstr</a>.</p>
+<p><b>autoCommit</b>: indicates whether automatic commit is enabled. Default is 
+       true.</p>
+<p><b>charSet</b>: set the default charset to use. Currently only interbase supports 
+       this.</p>
+<p><b>dialect</b>: set the default sql dialect to use. Currently only interbase 
+       supports this.</p>
+<p><b>metaTablesSQL</b>: SQL statement to return a list of available tables. Eg. 
+       <i>SHOW TABLES</i> in MySQL.</p>
+<p><b>genID</b>: The latest id generated by GenID() if supported by the database.</p>
+<p><b>cacheSecs</b>: The number of seconds to cache recordsets if CacheExecute() 
+       or CacheSelectLimit() omit the $secs2cache parameter. Defaults to 60 minutes.</p>
+<p><b>sysDate</b>: String that holds the name of the database function to call 
+       to get the current date. Useful for inserts and updates.</p>
+<p><b>sysTimeStamp</b>: String that holds the name of the database function to 
+       call to get the current timestamp/datetime value.</p>
+<p><b>leftOuter</b>: String that holds operator for left outer join, if known. 
+       Otherwise set to false.</p>
+<p><b>rightOuter</b>: String that holds operator for left outer join, if known. 
+       Otherwise set to false.</p>
+<p><b>ansiOuter</b>: Boolean that if true indicates that ANSI style outer joins 
+       are permitted. Eg. <i>select * from table1 left join table2 on p1=p2.</i></p>
+<p><b>connectSID</b>: Boolean that indicates whether to treat the $database parameter 
+       in connects as the SID for the oci8 driver. Defaults to false. Useful for 
+       Oracle 8.0.5 and earlier.</p>
+<p><b>autoRollback</b>: Persistent connections are auto-rollbacked in PConnect( 
+       ) if this is set to true. Default is false.</p>
+<hr>
+<h3>ADOConnection Main Functions</h3>
+<p><b>ADOConnection( )</b></p>
+<p>Constructor function. Do not call this directly. Use ADONewConnection( ) instead.</p>
+<p><b>Connect<a name="connect"></a>($host,[$user],[$password],[$database])</b></p>
+<p>Non-persistent connect to data source or server $<b>host</b>, using userid 
+       $<b>user </b>and password $<b>password</b>. If the server supports multiple 
+       databases, connect to database $<b>database</b>. </p>
+<p>Returns true/false depending on connection.</p>
+<p>ADO Note: If you are using a Microsoft ADO and not OLEDB, you can set the $database 
+       parameter to the OLEDB data provider you are using.</p>
+<p>PostgreSQL: An alternative way of connecting to the database is to pass the 
+       standard PostgreSQL connection string in the first parameter $host, and the 
+       other parameters will be ignored.</p>
+<p>For Oracle and Oci8, there are two ways to connect. First is to use the TNS 
+       name defined in your local tnsnames.ora (or ONAMES or HOSTNAMES). Place the 
+       name in the $database field, and set the $host field to false. Alternatively, 
+       set $host to the server, and $database to the database SID, this bypassed 
+       tnsnames.ora. 
+<p>Examples: 
+<pre> # $oraname in tnsnames.ora/ONAMES/HOSTNAMES
+ $conn->Connect(false, 'scott', 'tiger', $oraname); 
+ $conn->Connect('server:1521', 'scott', 'tiger', 'ServiceName'); # bypass tnsnames.ora</pre>
+<p>There are many examples of connecting to a database at <a href="http://php.weblogs.com/adodb">php.weblogs.com/ADOdb</a>, 
+       and in the testdatabases.inc.php file included in the release.</p>
+<p><b>PConnect<a name="pconnect"></a>($host,[$user],[$password],[$database])</b></p>
+<p>Persistent connect to data source or server $<b>host</b>, using userid $<b>user</b> 
+       and password $<b>password</b>. If the server supports multiple databases, 
+       connect to database $<b>database</b>.</p>
+<p>We now perform a rollback on persistent connection for selected databases since 
+       2.21, as advised in the PHP manual. See change log or source code for which 
+       databases are affected. 
+<p>Returns true/false depending on connection. See Connect( ) above for more info.</p>
+<p>Since ADOdb 2.21, we also support autoRollback. If you set:</p>
+</font> 
+<pre> $conn = &amp;NewADOConnection('mysql');
+ $conn-&gt;autoRollback = true; # default is false
+ $conn-&gt;PConnect(...); # rollback here</pre>
+<p> Then when doing a persistent connection with PConnect( ), ADOdb will 
+  perform a rollback first. This is because it is documented that PHP is 
+  not guaranteed to rollback existing failed transactions when 
+  persistent connections are used. This is implemented in Oracle, 
+  MySQL, PgSQL, MSSQL, ODBC currently. 
+<p>Since ADOdb 3.11, you can force non-persistent 
+connections even if PConnect is called by defining the constant 
+ADODB_NEVER_PERSIST  before you call PConnect.
+<p><b>NConnect<a name="nconnect"></a>($host,[$user],[$password],[$database])</b></p>
+<p>Always force a new connection. In contrast, PHP sometimes reuses connections 
+       when you use Connect() or PConnect(). Currently works only on mysql (PHP 4.3.0 
+       or later), postgresql and oci8-derived drivers. For other drivers, NConnect() works like 
+       Connect(). 
+<font color="#000000"> 
+<p><b>Execute<a name="execute"></a>($sql,$inputarr=false)</b></p>
+<p>Execute SQL statement $<b>sql</b> and return derived class of ADORecordSet 
+       if successful. Note that a record set is always returned on success, even 
+       if we are executing an insert or update statement. You can also pass in $sql a statement prepared 
+       in <a href=#prepare>Prepare()</a>.</p>
+<p>Returns derived class of ADORecordSet. Eg. if connecting via mysql, then ADORecordSet_mysql 
+       would be returned. False is returned if there was an error in executing the 
+       sql.</p>
+<p>The $inputarr parameter can be used for binding variables to parameters. Below 
+       is an Oracle example:</p>
+<pre>
+ $conn->Execute("SELECT * FROM TABLE WHERE COND=:val", array('val'=> $val));
+ </pre>
+<p>Another example, using ODBC,which uses the ? convention:</p>
+<pre>
+  $conn->Execute("SELECT * FROM TABLE WHERE COND=?", array($val));
+</pre>
+<a name="binding"></a>
+<i>Binding variables</i><p>
+Variable binding speeds the compilation and caching of SQL statements, leading 
+to higher performance. Currently Oracle, Interbase and ODBC supports variable binding. 
+Interbase/ODBC style ? binding is emulated in databases that do not support binding. 
+Note that you do not have to quote strings if you use binding.
+<p> Variable binding in the odbc, interbase and oci8po drivers. 
+<pre>
+$rs = $db->Execute('select * from table where val=?', array('10'));
+</pre>
+Variable binding in the oci8 driver: 
+<pre>
+$rs = $db->Execute('select name from table where val=:key', 
+  array('key' => 10));
+</pre>
+<a name="bulkbind"></a>
+<i>Bulk binding</i>
+<p>Since ADOdb 3.80, we support bulk binding in Execute(), in which you pass in a 2-dimensional array to
+be bound to an INSERT/UPDATE or DELETE statement.
+<pre>
+$arr = array(
+       array('Ahmad',32),
+       array('Zulkifli', 24),
+       array('Rosnah', 21)
+       );
+$ok = $db->Execute('insert into table (name,age) values (?,?)',$arr);
+</pre>
+<p>This provides very high performance as the SQL statement is prepared first. 
+The prepared statement is executed repeatedly for each array row until all rows are completed, 
+or until the first error. Very useful for importing data.
+
+<p><b>CacheExecute<a name="cacheexecute"></a>([$secs2cache,]$sql,$inputarr=false)</b></p>
+<p>Similar to Execute, except that the recordset is cached for $secs2cache seconds 
+       in the $ADODB_CACHE_DIR directory, and $inputarr only accepts 1-dimensional arrays. 
+       If CacheExecute() is called again with the same $sql, $inputarr, 
+       and also the same database, same userid, and the cached recordset 
+       has not expired, the cached recordset is returned. 
+<pre>
+  include('adodb.inc.php'); 
+  include('tohtml.inc.php');
+  $ADODB_<b>CACHE_DIR</b> = '/usr/local/ADOdbcache';
+  $conn = &ADONewConnection('mysql'); 
+  $conn->PConnect('localhost','userid','password','database');
+  $rs = $conn-><b>CacheExecute</b>(15, 'select * from table'); # cache 15 secs
+  rs2html($rs); /* recordset to html table */  
+</pre>
+<p> Alternatively, since ADOdb 1.80, the $secs2cache parameter is optional:</p>
+<pre>  $conn-&gt;Connect(...);
+       $conn-&gt;cacheSecs = 3600*24; // cache 24 hours
+       $rs = $conn-&gt;CacheExecute('select * from table');
+</pre>
+If $secs2cache is omitted, we use the value 
+in $connection-&gt;cacheSecs (default is 3600 seconds, or 1 hour). Use CacheExecute() 
+only with SELECT statements. 
+<p>Performance note: I have done some benchmarks and found that they vary so greatly 
+       that it's better to talk about when caching is of benefit. When your database 
+       server is <i>much slower </i>than your Web server or the database is <i>very 
+       overloaded </i>then ADOdb's caching is good because it reduces the load on 
+       your database server. If your database server is lightly loaded or much faster 
+       than your Web server, then caching could actually reduce performance. </p>
+<p><b>ExecuteCursor<a name="executecursor"></a>($sql,$cursorName='rs',$parameters=false)</b></p>
+<p>Execute an Oracle stored procedure, and returns an Oracle REF cursor variable as 
+       a regular ADOdb recordset. Does not work with any other database except oci8. 
+       Thanks to Robert Tuttle for the design.
+<pre>
+    $db = ADONewConnection("oci8"); 
+    $db->Connect("foo.com:1521", "uid", "pwd", "FOO"); 
+    $rs = $db->ExecuteCursor("begin :cursorvar := getdata(:param1); end;", 
+                                       'cursorvar',
+                                       array('param1'=>10)); 
+    # $rs is now just like any other ADOdb recordset object<br>    rs2html($rs);</pre>
+<p>ExecuteCursor() is a helper function that does the following internally: 
+<pre>
+       $stmt = $db->Prepare("BEGIN :RS := SP_FOO(); END;", true); 
+       $db->Parameter($stmt, $cur, 'RS', false, -1, OCI_B_CURSOR);
+       $rs = $db->Execute($stmt);</pre>
+<p><b>SelectLimit<a name="selectlimit"></a>($sql,$numrows=-1,$offset=-1,$inputarr=false)</b></p>
+<p>Returns a recordset if successful. Returns false otherwise. Performs a select 
+       statement, simulating PostgreSQL's SELECT statement, LIMIT $numrows OFFSET 
+       $offset clause.</p>
+<p>In PostgreSQL, SELECT * FROM TABLE LIMIT 3 will return the first 3 records 
+       only. The equivalent is <code>$connection->SelectLimit('SELECT * FROM TABLE',3)</code>. 
+       This functionality is simulated for databases that do not possess this feature.</p>
+<p>And SELECT * FROM TABLE LIMIT 3 OFFSET 2 will return records 3, 4 and 5 (eg. 
+       after record 2, return 3 rows). The equivalent in ADOdb is <code>$connection->SelectLimit('SELECT 
+       * FROM TABLE',3,2)</code>.</p>
+<p>Note that this is the <i>opposite</i> of MySQL's LIMIT clause. You can also 
+       set <code>$connection->SelectLimit('SELECT * FROM TABLE',-1,10)</code> to 
+       get rows 11 to the last row.</p>
+<p>The last parameter $inputarr is for databases that support variable binding 
+       such as Oracle oci8. This substantially reduces SQL compilation overhead. 
+       Below is an Oracle example:</p>
+<pre>
+ $conn->SelectLimit("SELECT * FROM TABLE WHERE COND=:val", 100,-1,array('val'=> $val));
+ </pre>
+<p>The oci8po driver (oracle portable driver) uses the more standard bind variable 
+       of ?: 
+<pre>
+ $conn->SelectLimit("SELECT * FROM TABLE WHERE COND=?", 100,-1,array('val'=> $val));
+</pre>
+<p> 
+<p>Ron Wilson reports that SelectLimit does not work with UNIONs. 
+<p><b>CacheSelectLimit<a name="cacheselectlimit"></a>([$secs2cache,] $sql, $numrows=-1,$offset=-1,$inputarr=false)</b></p>
+<p>Similar to SelectLimit, except that the recordset returned is cached for $secs2cache 
+       seconds in the $ADODB_CACHE_DIR directory. </p>
+<p>Since 1.80, $secs2cache has been optional, and you can define the caching time 
+       in $connection-&gt;cacheSecs.</p>
+</font> 
+<pre><font color="#000000">    $conn-&gt;Connect(...);
+   $conn-&gt;cacheSecs = 3600*24; // cache 24 hours
+       $rs = $conn-&gt;CacheSelectLimit('select * from table',10);</font></pre>
+<font color="#000000"> 
+<p><b>CacheFlush<a name="cacheflush"></a>($sql=false,$inputarr=false)</b></p>
+<p>Flush (delete) any cached recordsets for the SQL statement $sql in $ADODB_CACHE_DIR. 
+<p>If no parameter is passed in, then all adodb_*.cache files are deleted. 
+<p> If you want to flush all cached recordsets manually, execute the following 
+       PHP code (works only under Unix): <br>
+       <code> &nbsp; system(&quot;rm -f `find &quot;.$ADODB_CACHE_DIR.&quot; -name 
+       adodb_*.cache`&quot;);</code></p>
+<p>For general cleanup of all expired files, you should use <a href="http://www.superscripts.com/tutorial/crontab.html">crontab</a> 
+       on Unix, or at.exe on Windows, and a shell script similar to the following:<font face="Courier New, Courier, mono"><br>
+       #------------------------------------------------------ <br>
+       # This particular example deletes files in the TMPPATH <br>
+       # directory with the string &quot;.cache&quot; in their name that <br>
+       # are more than 7 days old. <br>
+       #------------------------------------------------------ <br>
+       AGED=7 <br>
+       find ${TMPPATH} -mtime +$AGED | grep &quot;\.cache&quot; | xargs rm -f <br>
+       </font> </p>
+<p><b>MetaError<a name="metaerror"></a>($errno=false)</b></p>
+<p>Returns a virtualized error number, based on PEAR DB's error number system. You might
+need to include adodb-error.inc.php before you call this function. The parameter $errno
+is the native error number you want to convert. If you do not pass any parameter, MetaError
+will call ErrorNo() for you and convert it. If the error number cannot be virtualized, MetaError 
+will return -1 (DB_ERROR).</p>
+
+<p><b>MetaErrorMsg<a name="metaerrormsg"></a>($errno)</b></p>
+<p>Pass the error number returned by MetaError() for the equivalent textual error message.</p>
+<p><b>ErrorMsg<a name="errormsg"></a>()</b></p>
+<p>Returns the last status or error message. The error message is reset after every 
+call to Execute(). 
+<p>
+This can return a string even if 
+       no error occurs. In general you do not need to call this function unless an 
+       ADOdb function returns false on an error. </p>
+<p>Note: If <b>debug</b> is enabled, the SQL error message is always displayed 
+       when the <b>Execute</b> function is called.</p>
+<p><b>ErrorNo<a name="errorno"></a>()</b></p>
+<p>Returns the last error number. The error number is reset after every call to Execute(). 
+If 0 is returned, no error occurred.
+<p>
+Note that old versions of PHP (pre 4.0.6) do 
+       not support error number for ODBC. In general you do not need to call this 
+       function unless an ADOdb function returns false on an error.</p>
+</font>
+<p><font color="#000000"><b>SetFetchMode<a name="setfetchmode"></a>($mode)</b></font></p>
+<p><font color="#000000">Sets the current fetch mode for the connection and stores 
+       it in $db-&gt;fetchMode. Legal modes are ADODB_FETCH_ASSOC and ADODB_FETCH_NUM. 
+       For more info, see <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a>.</font></p>
+<p><font color="#000000">Returns the previous fetch mode, which could be false 
+       if SetFetchMode( ) has not been called before.</font></p>
+<font color="#000000"> 
+<p><b>CreateSequence<a name="createseq"></a>($seqName = 'adodbseq',$startID=1)</b></p>
+<p>Create a sequence. The next time GenID( ) is called, the value returned will 
+       be $startID. Added in 2.60. 
+<p><b>DropSequenceD<a name="dropseq"></a>($seqName = 'adodbseq')</b></p>
+<p>Delete a sequence. Added in 2.60. 
+<p><b>GenID<a name="genid"></a>($seqName = 'adodbseq',$startID=1)</b></p>
+<p>Generate a sequence number . Works for interbase, 
+       mysql, postgresql, oci8, oci8po, mssql, ODBC based (access,vfp,db2,etc) drivers 
+       currently. Uses $seqName as the name of the sequence. GenID() will automatically 
+       create the sequence for you if it does not exist (provided the userid has 
+       permission to do so). Otherwise you will have to create the sequence yourself. 
+<p> If your database driver emulates sequences, the name of the table is the sequence 
+       name. The table has one column, "id" which should be of type integer, or if 
+       you need something larger - numeric(16). 
+<p> For ODBC and databases that do not support sequences natively (eg mssql, mysql), 
+       we create a table for each sequence. If the sequence has not been defined 
+       earlier, it is created with the starting value set in $startID.</p>
+<p>Note that the mssql driver's GenID() before 1.90 used to generate 16 byte GUID's.</p>
+<p><b>UpdateBlob<a name="updateblob"></a>($table,$column,$val,$where)</b></p>
+Allows you to store a blob (in $val) into $table into $column in a row at $where. 
+<p> Usage: 
+<p> 
+<pre>
+       # for oracle
+       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, empty_blob())');
+       $conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
+       
+       # non oracle databases
+       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+       $conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
+</pre>
+<p> Returns true if succesful, false otherwise. Supported by MySQL, PostgreSQL, 
+       Oci8, Oci8po and Interbase drivers. Other drivers might work, depending on 
+       the state of development.</p>
+<p>Note that when an Interbase blob is retrieved using SELECT, it still needs 
+       to be decoded using $connection->DecodeBlob($blob); to derive the original 
+       value in versions of PHP before 4.1.0. 
+<p>For PostgreSQL, you can store your blob using blob oid's or as a bytea field. 
+       You can use bytea fields but not blob oid's currently with UpdateBlob( ). 
+       Conversely UpdateBlobFile( ) supports oid's, but not bytea data.<br>
+       <br>
+       If you do not pass in an oid, then UpdateBlob() assumes that you are storing 
+       in bytea fields.
+<p><b>UpdateClob<a name="updateclob"></a>($table,$column,$val,$where)</b></p>
+Allows you to store a clob (in $val) into $table into $column in a row at $where. 
+Similar to UpdateBlob (see above), but for Character Large OBjects. 
+<p> Usage:
+<pre>
+       # for oracle
+       $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, empty_clob())');
+       $conn->UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');
+       
+       # non oracle databases
+       $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
+       $conn->UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');
+</pre>
+<p><b>UpdateBlobFile<a name="updateblobfile"></a>($table,$column,$path,$where,$blobtype='BLOB')</b></p>
+<p>Similar to UpdateBlob, except that we pass in a file path to where the blob 
+       resides.
+<p>For PostgreSQL, if you are using blob oid's, use this interface. This interface 
+       does not support bytea fields.
+<p>Returns true if successful, false otherwise. 
+<p><b>BlobEncode<a name="blobencode" id="blobencode"></a>($blob)</b> 
+<p>Some databases require blob's to be encoded manually before upload. Note if 
+       you use UpdateBlob( ) or UpdateBlobFile( ) the conversion is done automatically 
+       for you and you do not have to call this function. For PostgreSQL, currently, 
+       BlobEncode() can only be used for bytea fields.
+<p>Returns the encoded blob value.
+<p>Note that there is a connection property called <em>blobEncodeType</em> which 
+       has 3 legal values: 
+<p>false - no need to perform encoding or decoding.<br>
+       'I' - blob encoding required, and returned encoded blob is a numeric value 
+       (no need to quote).<br>
+       'C' - blob encoding required, and returned encoded blob is a character value 
+       (requires quoting).
+<p>This is purely for documentation purposes, so that programs that accept multiple 
+       database drivers know what is the right thing to do when processing blobs.
+<p><strong>BlobDecode<a name="blobdecode"></a>($blob)</strong> 
+</font><p><font color="#000000">Some databases require blob's to be decoded manually after doing a select statement. 
+       If the database does not require decoding, then this function will return 
+       the blob unchanged. Currently BlobDecode is only required for one database, 
+       PostgreSQL, and only if you are using blob oid's (if you are using bytea fields, 
+       we auto-decode for you).</font><font color="#000000">
+<pre>$rs = $db-&gt;Execute(&quot;select bloboid from postgres_table where id=$key&quot;);
+$blob = $db-&gt;BlobDecode( reset($rs-&gt;fields) );</pre>
+<p><b>Replace<a name="replace"></a>($table, $arrFields, $keyCols,$autoQuote=false)</b></p>
+<p>Try to update a record, and if the record is not found, an insert statement 
+       is generated and executed. Returns 0 on failure, 1 if update statement worked, 
+       2 if no record was found and the insert was executed successfully. This differs 
+       from MySQL's replace which deletes the record and inserts a new record. This 
+       also means you cannot update the primary key. The only exception to this is 
+       Interbase and its derivitives, which uses delete and insert because of some 
+       Interbase API limitations. 
+<p>The parameters are $table which is the table name, the $keyCols which is an 
+       associative array where the keys are the field names, and keyCols is the name 
+       of the primary key, or an array of field names if it is a compound key. If 
+       $autoQuote is set to true, then Replace() will quote all values that are non-numeric; 
+       auto-quoting will not quote nulls. Note that auto-quoting will not work if 
+       you use SQL functions or operators. 
+<p>Examples: 
+<pre>
+# single field primary key
+$ret = $db->Replace('atable', 
+       array('id'=>1000,'firstname'=>'Harun','lastname'=>'Al-Rashid'),
+       'id',$autoquote = true);        
+# generates UPDATE atable SET firstname='Harun',lastname='Al-Rashid' WHERE id=1000
+# or INSERT INTO atable (id,firstname,lastname) VALUES (1000,'Harun','Al-Rashid')
+
+# compound key
+$ret = $db->Replace('atable2', 
+       array('firstname'=>'Harun','lastname'=>'Al-Rashid', 'age' => 33, 'birthday' => 'null'),
+       array('lastname','firstname'),
+       $autoquote = true);
+
+# no auto-quoting
+$ret = $db->Replace('atable2', 
+       array('firstname'=>"'Harun'",'lastname'=>"'Al-Rashid'", 'age' => 'null'),
+       array('lastname','firstname')); 
+</pre>
+<p><b>GetUpdateSQL<a name="getupdatesql"></a>(&$rs, $arrFields, $forceUpdate=false,$magicq=false)</b></p>
+<p>Generate SQL to update a table given a recordset $rs, and the modified fields 
+       of the array $arrFields (which must be an associative array holding the column 
+       names and the new values) are compared with the current recordset. If $forceUpdate 
+       is true, then we also generate the SQL even if $arrFields is identical to 
+       $rs-&gt;fields. Requires the recordset to be associative. $magicq is used 
+       to indicate whether magic quotes are enabled (see qstr()). The field names in the array 
+       are case-insensitive.</p>
+       <p>Since 3.61, define('ADODB_FORCE_NULLS',1) and all PHP nulls will be auto-converted to SQL nulls.
+<p><b>GetInsertSQL<a name="getinsertsql"></a>(&$rs, $arrFields,$magicq=false)</b></p>
+<p>Generate SQL to insert into a table given a recordset $rs. Requires the query 
+       to be associative. $magicq is used to indicate whether magic quotes are enabled 
+       (for qstr()). The field names in the array are case-insensitive.</p>
+       
+<p>Since 3.61, define('ADODB_FORCE_NULLS',1) and all PHP nulls will be auto-converted 
+  to SQL nulls. 
+<p><b>PageExecute<a name="pageexecute"></a>($sql, $nrows, $page, $inputarr=false)</b> 
+<p>Used for pagination of recordset. $page is 1-based. See <a href="#ex8">Example 
+  8</a>.</p>
+</font> 
+<p><font color="#000000"><b>CachePageExecute<a name="cachepageexecute"></a>($secs2cache, 
+  $sql, $nrows, $page, $inputarr=false)</b> </font></p>
+<p><font color="#000000">Used for pagination of recordset. $page is 1-based. See 
+  <a href="#ex8">Example 8</a>. Caching version of PageExecute.</font></p>
+<font color="#000000"> 
+<p></p>
+<p><b>Close<a name="close"></a>( )</b></p>
+<p>Close the database connection. PHP4 proudly states that we no longer have to 
+  clean up at the end of the connection because the reference counting mechanism 
+  of PHP4 will automatically clean up for us.</p>
+  <p><b>StartTrans<a name="starttrans"></a>( )</b></p>
+  <p>Start a monitored transaction. As SQL statements are executed, ADOdb will monitor
+  for SQL errors, and if any are detected, when CompleteTrans() is called, we auto-rollback.
+  <p>
+  <p> To understand why StartTrans() is superior to BeginTrans(), 
+  let us examine a few ways of using BeginTrans().
+  The following is the wrong way to use transactions: 
+<pre>
+$DB->BeginTrans();
+$DB->Execute("update table1 set val=$val1 where id=$id");
+$DB->Execute("update table2 set val=$val2 where id=$id");
+$DB->CommitTrans();
+</pre>
+<p>because you perform no error checking. It is possible to update table1 and 
+  for the update on table2 to fail. Here is a better way: 
+<pre>
+$DB->BeginTrans();
+$ok = $DB->Execute("update table1 set val=$val1 where id=$id");
+if ($ok) $ok = $DB->Execute("update table2 set val=$val2 where id=$id");
+if ($ok) $DB->CommitTrans();
+else $DB->RollbackTrans();
+</pre>
+<p>Another way is (since ADOdb 2.0): 
+<pre>
+$DB->BeginTrans();
+$ok = $DB->Execute("update table1 set val=$val1 where id=$id");
+if ($ok) $ok = $DB->Execute("update table2 set val=$val2 where id=$id");
+$DB->CommitTrans($ok);
+</pre>
+<p> Now it is a headache monitoring $ok all over the place. StartTrans() is an
+improvement because it monitors all SQL errors for you. This is particularly
+useful if you are calling black-box functions in which SQL queries might be executed.
+ Also all BeginTrans, CommitTrans and RollbackTrans calls inside a StartTrans block 
+  will be disabled, so even if the black box function does a commit, it will be ignored.
+<pre>
+$DB->StartTrans();
+CallBlackBox();
+$DB->Execute("update table1 set val=$val1 where id=$id");
+$DB->Execute("update table2 set val=$val2 where id=$id");
+$DB->CompleteTrans($ok);
+</pre>
+<p>Note that a StartTrans blocks are nestable, the inner blocks are ignored.
+ <p><b>CompleteTrans<a name="completetrans"></a>($autoComplete=true)</b></p>
+  <p>Complete a transaction called with StartTrans(). This function monitors
+  for SQL errors, and will commit if no errors have occured, otherwise it will rollback. 
+  Returns true on commit, false on rollback. If the parameter $autoComplete is true
+  monitor sql errors and commit and rollback as appropriate. Set $autoComplete to false 
+  to force rollback even if no SQL error detected.
+  <p><b>FailTrans<a name="failtrans"></a>( )</b></p>
+  <p>Fail a transaction started with StartTrans(). The rollback will only occur when
+  CompleteTrans() is called.
+    <p><b>HasFailedTrans<a name="hasfailedtrans"></a>( )</b></p>
+       <p>Check whether smart transaction has failed, 
+       eg. returns true if there was an error in SQL execution or FailTrans() was called.
+       If not within smart transaction, returns false.
+<p><b>BeginTrans<a name="begintrans"></a>( )</b></p>
+<p>Begin a transaction. Turns off autoCommit. Returns true if successful. Some 
+  databases will always return false if transaction support is not available. 
+   Any open transactions will be rolled back when the connection is closed. Among the
+   databases that support transactions are Oracle, PostgreSQL, Interbase, MSSQL, certain
+    versions of MySQL, DB2, Informix, Sybase, etc.</p>
+ <p>Note that <a href=#starttrans>StartTrans()</a> and CompleteTrans() is a superior method of 
+ handling transactions, available since ADOdb 3.40. For a explanation, see the <a href=#starttrans>StartTrans()</a> documentation.
+
+<p>You can also use the ADOdb <a href=#errorhandling>error handler</a> to die 
+  and rollback your transactions for you transparently. Some buggy database extensions 
+  are known to commit all outstanding tranasactions, so you might want to explicitly 
+  do a $DB->RollbackTrans() in your error handler for safety. 
+ <h4>Detecting Transactions</h4>
+ <p>Since ADOdb 2.50, you are able to detect when you are inside a transaction. Check
+ that $connection->transCnt > 0. This variable is incremented whenever BeginTrans() is called,
+ and decremented whenever RollbackTrans() or CommitTrans() is called.
+<p><b>CommitTrans<a name="committrans"></a>($ok=true)</b></p>
+<p>End a transaction successfully. Returns true if successful. If the database 
+  does not support transactions, will return true also as data is always committed. 
+</p>
+<p>If you pass the parameter $ok=false, the data is rolled back. See example in 
+  BeginTrans().</p>
+<p><b>RollbackTrans<a name="rollbacktrans"></a>( )</b></p>
+<p>End a transaction, rollback all changes. Returns true if successful. If the 
+  database does not support transactions, will return false as data is never rollbacked. 
+</p>
+</font><font color="#000000"> 
+<p><b>GetAssoc<a name=getassoc1></a>($sql,$inputarr=false,$force_array=false,$first2cols=false)</b></p>
+<p>Returns an associative array for the given query $sql with optional bind parameters 
+  in $inputarr. If the number of columns returned is greater to two, a 2-dimensional 
+  array is returned, with the first column of the recordset becomes the keys 
+  to the rest of the rows. If the columns is equal to two, a 1-dimensional array 
+  is created, where the the keys directly map to the values (unless $force_array 
+  is set to true, when an array is created for each value).
+<p> <font color="#000000">Examples:<a name=getassocex></a></font></p>
+</font>
+<p><font color="#000000">We have the following data in a recordset:</font></p>
+<p><font color="#000000">row1: Apple, Fruit, Edible<br>
+  row2: Cactus, Plant, Inedible<br>
+  row3: Rose, Flower, Edible</font></p>
+<p><font color="#000000">GetAssoc will generate the following 2-dimensional associative 
+  array:</font></p>
+<p><font color="#000000">Apple =&gt; array[Fruit, Edible]<br>
+  Cactus =&gt; array[Plant, Inedible]<br>
+  Rose =&gt; array[Flower,Edible]</font></p>
+<p><font color="#000000">If the dataset is:</font></p>
+<p><font color="#000000"><font color="#000000"><font color="#000000">row1: Apple, 
+  Fruit<br>
+  row2: Cactus, Plant<br>
+  row3: Rose, Flower</font> </font></font></p>
+<p><font color="#000000"><font color="#000000">GetAssoc will generate the following 
+  1-dimensional associative array (with $force_array==false):</font></font></p>
+<p><font color="#000000">Apple =&gt; Fruit</font><br>
+  Cactus=&gt;Plant<br>
+  Rose=&gt;Flower <font color="#000000"><font color="#000000"> </font></font><font color="#000000"><font color="#000000"></font></font></p>
+<p><font color="#000000">The function returns:</font></p>
+<p><font color="#000000">The associative array, or false if an error occurs.</font></p>
+<font color="#000000">
+<p><b>CacheGetAssoc<a name="cachegetassoc"></a>([$secs2cache,] $sql,$inputarr=false,$force_array=false,$first2cols=false)</b></p>
+</font><font color="#000000"> 
+<p>Caching version of <a href=#getassoc1>GetAssoc</a> function above.
+<p><b>GetOne<a name="getone"></a>($sql,$inputarr=false)</b></p>
+<p>Executes the SQL and returns the first field of the first row. The recordset 
+  and remaining rows are discarded for you automatically. If an error occur, false 
+  is returned.</p>
+<p><b>GetRow<a name="getrow"></a>($sql,$inputarr=false)</b></p>
+<p>Executes the SQL and returns the first row as an array. The recordset and remaining 
+  rows are discarded for you automatically. If an error occurs, false is returned.</p>
+<p><b>GetAll<a name="getall"></a>($sql)</b></p>
+</font>
+<p><font color="#000000">Executes the SQL and returns the all the rows as a 2-dimensional 
+  array. The recordset is discarded for you automatically. If an error occurs, 
+  false is returned.</font></p>
+ <p><b>GetCol<a name="getcol"></a>($sql,$inputarr=false,$trim=false)</b></p>
+
+<p><font color="#000000">Executes the SQL and returns all elements of the first column as a 
+1-dimensional array. The recordset is discarded for you automatically. If an error occurs, 
+  false is returned.</font></p>
+<p><font color="#000000"><b>CacheGetOne<a name="cachegetone"></a>([$secs2cache,] 
+  $sql,$inputarr=false), CacheGetRow<a name="cachegetrow"></a>([$secs2cache,] $sql,$inputarr=false), CacheGetAll<a name="cachegetall"></a>([$secs2cache,] 
+  $sql,$inputarr=false), CacheGetCol<a name="cachegetcol"></a>([$secs2cache,] 
+  $sql,$inputarr=false,$trim=false)</b></font></p>
+<font color="#000000"> 
+<p>Similar to above Get* functions, except that the recordset is serialized and 
+  cached in the $ADODB_CACHE_DIR directory for $secs2cache seconds. Good for speeding 
+  up queries on rarely changing data. Note that the $secs2cache parameter is optional. 
+  If omitted, we use the value in $connection-&gt;cacheSecs (default is 3600 seconds, 
+  or 1 hour).</p>
+<p><b>Prepare<a name="prepare"></a>($sql )</b></p>
+</font> 
+<p><font color="#000000">Prepares (compiles) an SQL query for repeated execution. Bind parameters
+are denoted by ?, except for the oci8 driver, which uses the traditional Oracle :varname
+convention. 
+  </font></p>
+<p><font color="#000000">Returns an array containing the original sql statement 
+  in the first array element; the remaining elements of the array are driver dependent. 
+  If there is an error, or we are emulating Prepare( ), we return the original 
+  $sql string. This is because all error-handling has been centralized in Execute( 
+  ).</font></p>
+<p><font color="#000000">Prepare( ) cannot be used with functions that use SQL 
+  query rewriting techniques, e.g. PageExecute( ) and SelectLimit( ).</font></p>
+<p>Example:</p>
+<pre><font color="#000000">$stmt = $DB-&gt;Prepare('insert into table (col1,col2) values (?,?)');
+for ($i=0; $i &lt; $max; $i++)<br></font>      $DB-&gt;<font color="#000000">Execute($stmt,array((string) rand(), $i));
+</font></pre>
+<font color="#000000"> 
+<p>Also see InParameter(), OutParameter() and PrepareSP() below. Only supported internally by interbase, 
+  oci8 and selected ODBC-based drivers, otherwise it is emulated. There is no 
+  performance advantage to using Prepare() with emulation. 
+<p> Important: Due to limitations or bugs in PHP, if you are getting errors when 
+  you using prepared queries, try setting $ADODB_COUNTRECS = false before preparing. 
+  This behaviour has been observed with ODBC. 
+<p><b>IfNull<a name="ifnull"></a>($field, $nullReplacementValue)</b></p>
+<p>Portable IFNULL function (NVL in Oracle). Returns a string that represents 
+  the function that checks whether a $field is null for the given database, and 
+  if null, change the value returned to $nullReplacementValue. Eg.</p>
+<pre>$sql = <font color="#993300">'SELECT '</font>.$db-&gt;IfNull('name', <font color="#993300">&quot;'- unknown -'&quot;</font>).<font color="#993300"> ' FROM table'</font>;</pre>
+
+<p><b>length<a name="length"></a></b></p>
+<p>This is not a function, but a property. Some databases have "length" and others "len"
+as the function to measure the length of a string. To use this property:
+<pre>
+  $sql = <font color="#993300">"SELECT "</font>.$db->length.<font color="#993300">"(field) from table"</font>;
+  $rs = $db->Execute($sql);
+</pre>
+
+<p><b>random<a name="random"></a></b></p>
+<p>This is not a function, but a property. This is a string that holds the sql to
+generate a random number between 0.0 and 1.0 inclusive.
+
+<p><b>substr<a name="substr"></a></b></p>
+<p>This is not a function, but a property. Some databases have "substr" and others "substring"
+as the function to retrieve a sub-string. To use this property:
+<pre>
+  $sql = <font color="#993300">"SELECT "</font>.$db->substr.<font color="#993300">"(field, $offset, $length) from table"</font>;
+  $rs = $db->Execute($sql);
+</pre>
+<p>For all databases, the 1st parameter of <i>substr</i> is the field, the 2nd is the
+offset (1-based) to the beginning of the sub-string, and the 3rd is the length of the sub-string.
+
+
+<p><b>Param<a name="param"></a>($name )</b></p>
+<p>Generates a bind placeholder portably. For most databases, the bind placeholder 
+  is "?". However some databases use named bind parameters such as Oracle, eg 
+  ":somevar". This allows us to portably define an SQL statement with bind parameters: 
+<pre><font color="#000000">$sql = <font color="#993300">'insert into table (col1,col2) values ('</font>.$DB-&gt;Param('a').<font color="#993300">','</font>.$DB-&gt;Param('b').<font color="#993300">')'</font>;
+<font color="#006600"># generates 'insert into table (col1,col2) values (?,?)'
+# or        'insert into table (col1,col2) values (:a,:b)</font>'
+$stmt = $DB-&gt;Prepare($sql);
+$stmt = $DB-&gt;Execute($stmt,array('one','two'));
+</font></pre>
+<font color="#000000"> 
+<p></p>
+<p><b>PrepareSP</b><b><a name="preparesp"></a></b><b>($sql)</b></p>
+<p>When calling stored procedures in mssql and oci8 (oracle), and you might want 
+  to directly bind to parameters that return values, or for special LOB handling. 
+  PrepareSP() allows you to do so. 
+<p>Returns the same array or $sql string as Prepare( ) above. If you do not need 
+  to bind to return values, you should use Prepare( ) instead.</p>
+<p>For examples of usage of PrepareSP( ), see InParameter( ) below. 
+<p>Note: in the mssql driver, preparing stored procedures requires a special function 
+  call, mssql_init( ), which is called by this function. PrepareSP( ) is available 
+  in all other drivers, and is emulated by calling Prepare( ). </p>
+<p><b> InParameter<a name="inparameter"></a>($stmt, $var, $name,
+  $maxLen = 4000, $type = false )</b></p>
+Binds a PHP variable as input to a stored procedure variable. The parameter <i>$stmt</i>
+ is the value returned by PrepareSP(), <i>$var</i> is the PHP variable you want to bind, $name
+ is the name of the stored procedure variable. Optional is <i>$maxLen</i>, the maximum length of the
+ data to bind, and $type which is database dependant. 
+ Consult <a href=http://php.net/mssql_bind>mssql_bind</a> and <a href=http://php.net/ocibindbyname>ocibindbyname</a> docs
+  at php.net for more info on legal values for $type. 
+ <p>
+InParameter() is a wrapper function that calls Parameter() with $isOutput=false. 
+The advantage of this function is that it is self-documenting, because
+the $isOutput parameter is no longer needed.  Only for mssql 
+  and oci8 currently.
+  <p>Here is an example using oci8:
+  <pre><font color="green"># For oracle, Prepare and PrepareSP are identical</font>
+$stmt = $db-&gt;PrepareSP(
+       <font color="#993300">&quot;declare RETVAL integer; 
+       begin
+       :RETVAL := </font><font color="#993300">SP_RUNSOMETHING</font><font color="#993300">(:myid,:group);
+       end;&quot;</font>);
+$db-&gt;InParameter($stmt,$id,'myid');
+$db-&gt;InParameter($stmt,$group,'group',64);
+$db-&gt;OutParameter($stmt,$ret,'RETVAL');<br>$db-&gt;Execute($stmt);
+</pre>
+<p> The same example using mssql:</p>
+</font> 
+<pre><font color="#000000"><font color="green"># @RETVAL = SP_RUNSOMETHING @myid,@group</font>
+$stmt = $db-&gt;PrepareSP(<font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font>); <br><font color="green"># note that the parameter name does not have @ in front!</font>
+$db-&gt;InParameter($stmt,$id,'myid');
+$db-&gt;InParameter($stmt,$group,'group',64);
+<font color="green"># return value in mssql - RETVAL is hard-coded name</font> 
+$db-&gt;OutParameter($stmt,$ret,'RETVAL');
+$db-&gt;Execute($stmt); </font></pre>
+
+<p>Note that the only difference between the oci8 and mssql implementations is $sql.</p>
+  <p>
+ If $type parameter is set to false, in mssql, $type will be dynamicly determined 
+based on the type of the PHP variable passed <font face="Courier New, Courier, mono">(string 
+=&gt; SQLCHAR, boolean =&gt;SQLINT1, integer =&gt;SQLINT4 or float/double=&gt;SQLFLT8)</font>.
+<p> 
+In oci8, $type can be set to OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), 
+OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID). To 
+pass in a null, use<font face="Courier New, Courier, mono"> $db-&gt;Parameter($stmt, 
+$null=null, 'param')</font>. 
+  <p><b> OutParameter<a name="outparameter"></a>($stmt, $var, $name, 
+  $maxLen = 4000, $type = false )</b></p>
+  Binds a PHP variable as output from a stored procedure variable. The parameter <i>$stmt</i>
+ is the value returned by PrepareSP(), <i>$var</i> is the PHP variable you want to bind, <i>$name</i>
+ is the name of the stored procedure variable. Optional is <i>$maxLen</i>, the maximum length of the
+ data to bind, and <i>$type</i> which is database dependant. 
+  <p>
+  OutParameter() is a wrapper function that calls Parameter() with $isOutput=true. 
+  The advantage of this function is that it is self-documenting, because
+the $isOutput parameter is no longer needed.  Only for mssql 
+  and oci8 currently.
+<p>
+For an example, see <a href=#inparameter>InParameter</a>.
+
+<p><b> Parameter<a name="parameter"></a>($stmt, $var, $name, $isOutput=false, 
+  $maxLen = 4000, $type = false )</b></p>
+<p>Note: This function is deprecated, because of the new InParameter() and OutParameter() functions.
+These are superior because they are self-documenting, unlike Parameter().
+<p>Adds a bind parameter suitable for return values or special data handling (eg. 
+  LOBs) after a statement has been prepared using PrepareSP(). Only for mssql 
+  and oci8 currently. The parameters are:<br>
+  <br>
+  $<i><b>stmt</b></i> Statement returned by Prepare() or PrepareSP().<br>
+  $<i><b>var</b></i> PHP variable to bind to. Make sure you pre-initialize it!<br>
+  $<i><b>name</b></i> Name of stored procedure variable name to bind to.<br>
+  [$<i><b>isOutput</b></i>] Indicates direction of parameter 0/false=IN 1=OUT 
+  2= IN/OUT. This is ignored in oci8 as this driver auto-detects the direction.<br>
+  [$<b>maxLen</b>] Maximum length of the parameter variable.<br>
+  [$<b>type</b>] Consult <a href="http://php.net/mssql_bind">mssql_bind</a> and 
+  <a href="http://php.net/ocibindbyname">ocibindbyname</a> docs at php.net for 
+  more info on legal values for type.</p>
+<p>Lastly, in oci8, bind parameters can be reused without calling PrepareSP( ) 
+  or Parameters again. This is not possible with mssql. An oci8 example:</p>
+<pre>$id = 0; $i = 0;
+$stmt = $db-&gt;PrepareSP( <font color="#993300">&quot;update table set val=:i where id=:id&quot;</font>);
+$db-&gt;Parameter($stmt,$id,'id');
+$db-&gt;Parameter($stmt,$i, 'i');
+for ($cnt=0; $cnt &lt; 1000; $cnt++) {
+       $id = $cnt; <br>        $i = $cnt * $cnt; <font color="green"># works with oci8!</font>
+       $db-&gt;Execute($stmt); <br>}</pre>
+<p><b>Bind<a name="bind"></a>($stmt, $var, $size=4001, $type=false, $name=false)</b></p>
+</font> 
+<p><font color="#000000">This is a low-level function supported only by the oci8 
+  driver. <b>Avoid using</b> unless you only want to support Oracle. The Parameter( 
+  ) function is the recommended way to go with bind variables.</font></p>
+<p><font color="#000000">Bind( ) allows you to use bind variables in your sql 
+  statement. This binds a PHP variable to a name defined in an Oracle sql statement 
+  that was previously prepared using Prepare(). Oracle named variables begin with 
+  a colon, and ADOdb requires the named variables be called :0, :1, :2, :3, etc. 
+  The first invocation of Bind() will match :0, the second invocation will match 
+  :1, etc. Binding can provide 100% speedups for insert, select and update statements. 
+  </font></p>
+<p>The other variables, $size sets the buffer size for data storage, $type is 
+  the optional descriptor type OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), 
+  OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID). 
+  Lastly, instead of using the default :0, :1, etc names, you can define your 
+  own bind-name using $name. 
+<p><font color="#000000">The following example shows 3 bind variables being used: 
+  p1, p2 and p3. These variables are bound to :0, :1 and :2.</font></p>
+<pre>$stmt = $DB-&gt;Prepare(&quot;insert into table (col0, col1, col2) values (:0, :1, :2)&quot;);
+$DB-&gt;Bind($stmt, $p1);
+$DB-&gt;Bind($stmt, $p2);
+$DB-&gt;Bind($stmt, $p3);
+for ($i = 0; $i &lt; $max; $i++) { 
+   $p1 = ?; $p2 = ?; $p3 = ?;
+   $DB-&gt;Execute($stmt);
+}</pre>
+<p>You can also use named variables:</p>
+<pre>
+$stmt = $DB-&gt;Prepare(&quot;insert into table (col0, col1, col2) values (:name0, :name1, :name2)&quot;);
+$DB-&gt;Bind($stmt, $p1, &quot;name0&quot;);
+$DB-&gt;Bind($stmt, $p2, &quot;name1&quot;);
+$DB-&gt;Bind($stmt, $p3, &quot;name2&quot;);
+for ($i = 0; $i &lt; $max; $i++) { 
+   $p1 = ?; $p2 = ?; $p3 = ?;
+   $DB-&gt;Execute($stmt);
+}</pre>
+<p><b>LogSQL($enable=true)<a name=logsql></a></b></p>
+Call this method to install a SQL logging and timing function (using fnExecute). 
+Then all SQL statements are logged into an adodb_logsql table in a database. If 
+the adodb_logsql table does not exist, ADOdb will create the table if you have 
+the appropriate permissions. Returns the previous logging value (true for enabled, 
+false for disabled). Here are samples of the DDL for selected databases: 
+<p> 
+<pre>
+               <b>mysql:</b>
+               CREATE TABLE adodb_logsql (
+                 created datetime NOT NULL,
+                 sql0 varchar(250) NOT NULL,
+                 sql1 text NOT NULL,
+                 params text NOT NULL,
+                 tracer text NOT NULL,
+                 timer decimal(16,6) NOT NULL
+               )
+               
+               <b>postgres:</b>
+               CREATE TABLE adodb_logsql (
+                 created timestamp NOT NULL,
+                 sql0 varchar(250) NOT NULL,
+                 sql1 text NOT NULL,
+                 params text NOT NULL,
+                 tracer text NOT NULL,
+                 timer decimal(16,6) NOT NULL
+               )
+               
+               <b>mssql:</b>
+               CREATE TABLE adodb_logsql (
+                 created datetime NOT NULL,
+                 sql0 varchar(250) NOT NULL,
+                 sql1 varchar(4000) NOT NULL,
+                 params varchar(3000) NOT NULL,
+                 tracer varchar(500) NOT NULL,
+                 timer decimal(16,6) NOT NULL
+               )
+               
+               <b>oci8:</b>
+               CREATE TABLE adodb_logsql (
+                 created date NOT NULL,
+                 sql0 varchar(250) NOT NULL,
+                 sql1 varchar(4000) NOT NULL,
+                 params varchar(4000),
+                 tracer varchar(4000),
+                 timer decimal(16,6) NOT NULL
+               )
+</pre>
+Usage: 
+<pre>
+       $conn->LogSQL(); // turn on logging
+         :
+       $conn->Execute(...);
+         :
+       $conn->LogSQL(false); // turn off logging
+       
+       # output summary of SQL logging results
+       $perf = NewPerfMonitor($conn);
+       echo $perf->SuspiciousSQL();
+       echo $perf->ExpensiveSQL();
+</pre>
+<p>One limitation of logging is that rollback also prevents SQL from being logged.
+<p>
+If you prefer to use another name for the table used to store the SQL, you can override it by calling 
+adodb_perf::table($tablename), where $tablename is the new table name (you will still need to manually
+create the table yourself). An example:
+<pre>
+       include('adodb.inc.php');
+       include('adodb-perf.inc.php');
+       adodb_perf::table('my_logsql_table');
+</pre>
+Also see <a href=docs-perf.htm>Performance Monitor</a>. 
+<p><font color="#000000"><b>fnExecute and fnCacheExecute properties<a name="fnexecute" id="fnexecute"></a></b></font></p>
+<p>These two properties allow you to define bottleneck functions for all sql statements 
+  processed by ADOdb. This allows you to perform statistical analysis and query-rewriting 
+  of your sql. 
+<p><b>Examples of fnExecute</b></p>
+<p>Here is an example of using fnExecute, to count all cached queries and non-cached 
+  queries, you can do this:</p>
+<pre><font color="#006600"># $db is the connection object</font>
+function CountExecs($db, $sql, $inputarray)
+{
+global $EXECS;
+
+if (!is_array(inputarray)) $EXECS++;
+<font color="#006600"># handle 2-dimensional input arrays</font>
+else if (is_array(reset($inputarray))) $EXECS += sizeof($inputarray);
+else $EXECS++;
+}
+
+<font color="#006600"># $db is the connection object</font>
+function CountCachedExecs($db, $secs2cache, $sql, $inputarray)
+{<br>global $CACHED; $CACHED++;
+}
+<br>$db = NewADOConnection('mysql');
+$db-&gt;Connect(...);
+$db-&gt;<strong>fnExecute</strong> = 'CountExecs';
+$db-&gt;<strong>fnCacheExecute</strong> = 'CountCachedExecs';
+ :
+ :<br><font color="#006600"># After many sql statements:</font>`
+printf(&quot;&lt;p&gt;Total queries=%d; total cached=%d&lt;/p&gt;&quot;,$EXECS+$CACHED, $CACHED);
+</pre>
+<p>The fnExecute function is called before the sql is parsed and executed, so 
+  you can perform a query rewrite. If you are passing in a prepared statement, 
+  then $sql is an array (see <a href="#prepare">Prepare</a>). The fnCacheExecute 
+  function is only called if the recordset returned was cached.<font color="#000000"> 
+  The function parameters match the Execute and CacheExecute functions respectively, 
+  except that $this (the connection object) is passed as the first parameter.</font></p>
+<p>Since ADOdb 3.91, the behaviour of fnExecute varies depending on whether the 
+  defined function returns a value. If it does not return a value, then the $sql 
+  is executed as before. This is useful for query rewriting or counting sql queries. 
+<p> On the other hand, you might want to replace the Execute function with one 
+  of your own design. If this is the case, then have your function return a value. 
+  If a value is returned, that value is returned immediately, without any further 
+  processing. This is used internally by ADOdb to implement LogSQL() functionality. 
+<p> <font color="#000000"> 
+<hr>
+<h3>ADOConnection Utility Functions</h3>
+<p><b>BlankRecordSet<a name="blankrecordset"></a>([$queryid])</b></p>
+<p>No longer available - removed since 1.99.</p>
+<p><b>Concat<a name="concat"></a>($s1,$s2,....)</b></p>
+<p>Generates the sql string used to concatenate $s1, $s2, etc together. Uses the 
+  string in the concat_operator field to generate the concatenation. Override 
+  this function if a concatenation operator is not used, eg. MySQL.</p>
+<p>Returns the concatenated string.</p>
+<p><b>DBDate<a name="dbdate"></a>($date)</b></p>
+<p>Format the $<b>date</b> in the format the database accepts. This is used in 
+  INSERT/UPDATE statements; for SELECT statements, use <a href="#sqldate">SQLDate</a>. 
+  The $<b>date</b> parameter can be a Unix integer timestamp or an ISO format 
+  Y-m-d. Uses the fmtDate field, which holds the format to use. If null or false 
+  or '' is passed in, it will be converted to an SQL null.</p>
+<p>Returns the date as a quoted string.</p>
+<p><b>DBTimeStamp<a name="dbtimestamp"></a>($ts)</b></p>
+<p>Format the timestamp $<b>ts</b> in the format the database accepts; this can 
+  be a Unix integer timestamp or an ISO format Y-m-d H:i:s. Uses the fmtTimeStamp 
+  field, which holds the format to use. If null or false or '' is passed in, it 
+  will be converted to an SQL null.</p>
+<p>Returns the timestamp as a quoted string.</p>
+<p><b>qstr<a name="qstr"></a>($s,[$magic_quotes_enabled</b>=false]<b>)</b></p>
+<p>Quotes a string to be sent to the database. The $<b>magic_quotes_enabled</b> 
+  parameter may look funny, but the idea is if you are quoting a string extracted 
+  from a POST/GET variable, then pass get_magic_quotes_gpc() as the second parameter. 
+  This will ensure that the variable is not quoted twice, once by <i>qstr</i> 
+  and once by the <i>magic_quotes_gpc</i>.</p>
+<p>Eg.<font face="Courier New, Courier, mono"> $s = $db-&gt;qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());</font></p>
+<p>Returns the quoted string.</p>
+<p><b>Quote<a name="quote"></a>($s)</b></p>
+<p>Quotes the string $s, escaping the database specific quote character as appropriate. 
+  Formerly checked magic quotes setting, but this was disabled since 3.31 for 
+  compatibility with PEAR DB. 
+<p><b>Affected_Rows<a name="affected_rows"></a>( )</b></p>
+<p>Returns the number of rows affected by a update or delete statement. Returns 
+  false if function not supported.</p>
+<p>Not supported by interbase/firebird currently. </p>
+<p><b>Insert_ID<a name="inserted_id"></a>( )</b></p>
+<p>Returns the last autonumbering ID inserted. Returns false if function not supported. 
+</p>
+<p>Only supported by databases that support auto-increment or object id's, such 
+  as PostgreSQL, MySQL and MS SQL Server currently. PostgreSQL returns the OID, which 
+  can change on a database reload.</p>
+<p><b>RowLock<a name="rowlock"></a>($table,$where)</b></p>
+<p>Lock a table row for the duration of a transaction. For example to lock record $id in table1:
+<pre>
+       $DB->StartTrans();
+       $DB->RowLock("table1","rowid=$id");
+       $DB->Execute($sql1);
+       $DB->Execute($sql2);
+       $DB->CompleteTrans();
+</pre>
+<p>Supported in db2, interbase, informix, mssql, oci8, postgres, sybase.
+<p><b>MetaDatabases<a name="metadatabases"></a>()</b></p>
+<p>Returns a list of databases available on the server as an array. You have to 
+  connect to the server first. Only available for ODBC, MySQL and ADO.</p>
+<p><b>MetaTables<a name="metatables"></a>($ttype = false, $showSchema = false, 
+  $mask=false)</b></p>
+<p>Returns an array of tables and views for the current database as an array. 
+  The array should exclude system catalog tables if possible. To only show tables, 
+  use $db->MetaTables('TABLES'). To show only views, use $db->MetaTables('VIEWS'). 
+  The $showSchema parameter currently works only for DB2, and when set to true, 
+  will add the schema name to the table, eg. "SCHEMA.TABLE". </p>
+<p>You can define a mask for matching. For example, setting $mask = 'TMP%' will 
+  match all tables that begin with 'TMP'. Currently only mssql, oci8, odbc_mssql 
+  and postgres* support $mask. 
+<p><b>MetaColumns<a name="metacolumns"></a>($table,$toupper=true)</b></p>
+<p>Returns an array of ADOFieldObject's, one field object for every column of 
+  $table. A field object is a class instance with (name, type, max_length) defined.
+  Currently Sybase does not recognise date types, and ADO cannot identify 
+  the correct data type (so we default to varchar).   
+ <p> The $toupper parameter determines whether we uppercase the table name 
+ (required for some databases).
+ <p>For schema support, pass in the $table parameter, "$schema.$tablename". This is only
+ supported for selected databases.
+<p><b>MetaColumnNames<a name="metacolumnames"></a>($table)</b></p>
+<p>Returns an array of column names for $table. 
+<p><font color="#000000"><b>MetaPrimaryKeys<a name="metaprimarykeys"></a>($table, 
+  $owner=false)</b></font></font> 
+<p><font color="#000000">Returns an array containing column names that are the 
+  primary keys of $table. Supported by mysql, odbc (including db2, odbc_mssql, 
+  etc), mssql, postgres, interbase/firebird, oci8 currently. </font><font color="#000000"> 
+<p>Views (and some tables) have primary keys, but sometimes this information is not available from the
+database. You can define a function  ADODB_View_PrimaryKeys($databaseType, $database, $view, $owner) that
+should return an array containing the fields that make up the primary key. If that function exists,
+it will be called when MetaPrimaryKeys() cannot find a primary key for a table or view.
+<pre>
+// In this example: dbtype = 'oci8', $db = 'mydb', $view = 'dataView', $owner = false 
+function ADODB_View_PrimaryKeys($dbtype,$db,$view,$owner)
+{
+       switch(strtoupper($view)) {
+       case 'DATAVIEW': return array('DATAID');
+       default: return false;
+       }
+}
+
+$db = NewADOConnection('oci8');
+$db->Connect('localhost','root','','mydb'); 
+$db->MetaPrimaryKeys('dataView');
+</pre>
+<p><font color="#000000"><b>ServerInfo<a name="serverinfo" id="serverinfo"></a>($table)</b></font></font> 
+<p><font color="#000000">Returns an array of containing two elements 'description' 
+  and 'version'. The 'description' element contains the string description of 
+  the database. The 'version' naturally holds the version number (which is also 
+  a string).</font><font color="#000000"> 
+<p><b>MetaForeignKeys<a name="metaforeignkeys"></a>($table, $owner=false, $upper=false)</b> 
+<p>Returns an associate array of foreign keys, or false if not supported. For 
+  example, if table employee has a foreign key where employee.deptkey points to 
+  dept_table.deptid, and employee.posn=posn_table.postionid and employee.poscategory=posn_table.category, 
+  then $conn->MetaForeignKeys('employee') will return 
+<pre>
+       array(
+               'dept_table' => array('deptkey=deptid'),
+               'posn_table' => array('posn=positionid','poscategory=category')
+       )
+</pre>
+<p>The optional schema or owner can be defined in $owner. If $upper is true, then 
+  the table names (array keys) are upper-cased. 
+<hr>
+<h2>ADORecordSet<a name="adorecordset"></a></h2>
+<p>When an SQL statement successfully is executed by <font face="Courier New, Courier, mono">ADOConnection-&gt;Execute($sql),</font>an 
+  ADORecordSet object is returned. This object contains a virtual cursor so we 
+  can move from row to row, functions to obtain information about the columns 
+  and column types, and helper functions to deal with formating the results to 
+  show to the user.</p>
+<h3>ADORecordSet Fields</h3>
+<p><b>fields: </b>Array containing the current row. This is not associative, but 
+  is an indexed array from 0 to columns-1. See also the function <b><a href="#fields">Fields</a></b>, 
+  which behaves like an associative array.</p>
+<p><b>dataProvider</b>: The underlying mechanism used to connect to the database. 
+  Normally set to <b>native</b>, unless using <b>odbc</b> or <b>ado</b>.</p>
+<p><b>blobSize</b>: Maximum size of a char, string or varchar object before it 
+  is treated as a Blob (Blob's should be shown with textarea's). See the <a href="#metatype">MetaType</a> 
+  function.</p>
+<p><b>sql</b>: Holds the sql statement used to generate this record set.</p>
+<p><b>canSeek</b>: Set to true if Move( ) function works.</p>
+<p><b>EOF</b>: True if we have scrolled the cursor past the last record.</p>
+<h3>ADORecordSet Functions</h3>
+<p><b>ADORecordSet( )</b></p>
+<p>Constructer. Normally you never call this function yourself.</p>
+<p><b>GetAssoc<a name="getassoc"></a>([$force_array])</b></p>
+<p>Generates an associative array from the recordset. Note that is this function 
+  is also <a href="#getassoc1">available</a> in the connection object. More details 
+  can be found there.</p>
+</font></font><font color="#000000"><font color="#000000"> </font></font><font color="#000000"><font color="#000000">
+<p><b>GetArray<a name="getarray"></a>([$number_of_rows])</b></p>
+<p>Generate a 2-dimensional array of records from the current cursor position, 
+  indexed from 0 to $number_of_rows - 1. If $number_of_rows is undefined, till 
+  EOF.</p>
+<p><b>GetRows<a name="getrows"></a>([$number_of_rows])</b></p>
+Generate a 2-dimensional array of records from the current cursor position. Synonym 
+for GetArray() for compatibility with Microsoft ADO. 
+<p> <b>GetMenu<a name="getmenu"></a>($name, [$default_str=''], [$blank1stItem=true], 
+  [$multiple_select=false], [$size=0], [$moreAttr=''])</b></p>
+<p>Generate a HTML menu (&lt;select&gt;&lt;option&gt;&lt;option&gt;&lt;/select&gt;). 
+  The first column of the recordset (fields[0]) will hold the string to display 
+  in the option tags. If the recordset has more than 1 column, the second column 
+  (fields[1]) is the value to send back to the web server.. The menu will be given 
+  the name $<i>name</i>. 
+<p> If $<i>default_str</i> is defined, then if $<i>default_str</i> == fields[0], 
+  that field is selected. If $<i>blank1stItem</i> is true, the first option is 
+  empty. You can also set the first option strings by setting $blank1stItem = 
+  "$value:$text".</p>
+<p>$<i>Default_str</i> can be array for a multiple select listbox.</p>
+<p>To get a listbox, set the $<i>size</i> to a non-zero value (or pass $default_str 
+  as an array). If $<i>multiple_select</i> is true then a listbox will be generated 
+  with $<i>size</i> items (or if $size==0, then 5 items) visible, and we will 
+  return an array to a server. Lastly use $<i>moreAttr </i> to add additional 
+  attributes such as javascript or styles. </p>
+<p>Menu Example 1: <code>GetMenu('menu1','A',true)</code> will generate a menu: 
+  <select name='menu1'>
+    <option> 
+    <option value=1 selected>A 
+    <option value=2>B 
+    <option value=3>C 
+  </select>
+  for the data (A,1), (B,2), (C,3). Also see <a href="#ex5">example 5</a>.</p>
+<p>Menu Example 2: For the same data, <code>GetMenu('menu1',array('A','B'),false)</code> 
+  will generate a menu with both A and B selected: <br>
+  <select name='menu1' multiple size=3>
+    <option value=1 selected>A 
+    <option value=2 selected>B 
+    <option value=3>C 
+  </select>
+<p> <b>GetMenu2<a name="getmenu2"></a>($name, [$default_str=''], [$blank1stItem=true], 
+  [$multiple_select=false], [$size=0], [$moreAttr=''])</b></p>
+<p>This is nearly identical to GetMenu, except that the $<i>default_str</i> is 
+  matched to fields[1] (the option values).</p>
+<p>Menu Example 3: Given the data in menu example 2, <code>GetMenu2('menu1',array('1','2'),false)</code> 
+  will generate a menu with both A and B selected in menu example 2, but this 
+  time the selection is based on the 2nd column, which holds the values to return 
+  to the Web server. 
+<p><b>UserDate<a name="userdate"></a>($str, [$fmt])</b></p>
+<p>Converts the date string $<i>str</i> to another format. The date format is Y-m-d,
+or Unix timestamp format. The default $<i>fmt</i> is Y-m-d.</p>
+<p><b>UserTimeStamp<a name="usertimestamp"></a>($str, [$fmt])</b></p>
+<p>Converts the timestamp string $<b>str</b> to another format. The timestamp 
+  format is Y-m-d H:i:s, as in '2002-02-28 23:00:12', or Unix timestamp format.
+   UserTimeStamp calls UnixTimeStamp to parse $<i>str</i>, and $<i>fmt</i> defaults to Y-m-d H:i:s if not defined. 
+</p>
+<p><b>UnixDate<a name="unixdate"></a>($str)</b></p>
+<p>Parses the date string $<b>str</b> and returns it in unix mktime format (eg. 
+  a number indicating the seconds after January 1st, 1970). Expects the date to 
+  be in Y-m-d H:i:s format, except for Sybase and Microsoft SQL Server, where 
+  M d Y is also accepted (the 3 letter month strings are controlled by a global 
+  array, which might need localisation).</p>
+<p>This function is available in both ADORecordSet and ADOConnection since 1.91.</p>
+<p><b>UnixTimeStamp<a name="unixtimestamp"></a>($str)</b></p>
+<p>Parses the timestamp string $<b>str</b> and returns it in unix mktime format 
+  (eg. a number indicating the seconds after January 1st, 1970). Expects the date 
+  to be in "Y-m-d, H:i:s" (1970-12-24, 00:00:00) or "Y-m-d H:i:s" (1970-12-24 00:00:00) or "YmdHis" (19701225000000) format, except for Sybase and Microsoft SQL Server, where 
+  "M d Y h:i:sA" (Dec 25 1970 00:00:00AM) is also accepted (the 3 letter month strings are controlled by 
+  a global array, which might need localisation).</p>
+</font> 
+<p><font color="#000000">This function is available in both ADORecordSet and ADOConnection 
+  since 1.91. </font></p>
+<p><font color="#000000"><b>OffsetDate<a name="offsetdate"></a>($dayFraction, 
+  $basedate=false)</b></font></p>
+<p><font color="#000000"><font color="#000000">Returns a string </font>with the 
+  native SQL functions to calculate future and past dates based on $basedate in 
+  a portable fashion. If $basedate is not defined, then the current date (at 12 
+  midnight) is used. Returns the SQL string that performs the calculation when 
+  passed to Execute(). </font></p>
+<p><font color="#000000">For example, in Oracle, to find the date and time that 
+  is 2.5 days from today, you can use:</font></p>
+<pre><font color="#000000"># get date one week from now
+$fld = $conn-&gt;OffsetDate(7); // returns &quot;(trunc(sysdate)+7&quot;)</font></pre>
+<pre><font color="#000000"># get date and time that is 60 hours from current date and time
+$fld = $conn-&gt;OffsetDate(2.5, $conn-&gt;sysTimeStamp);      // returns &quot;(sysdate+2.5)&quot;</font>
+
+$conn-&gt;Execute(&quot;UPDATE TABLE SET dodate=$fld WHERE ID=$id&quot;);</pre>
+<p> This function is available for mysql, mssql, oracle, oci8 and postgresql drivers 
+  since 2.13. It might work with other drivers<font color="#000000"> provided 
+  they allow performing numeric day arithmetic on dates.</font></p>
+<font color="#000000"> 
+<p><font color="#000000"><b>SQLDate<a name="sqldate"></a>($dateFormat, $basedate=false)</b></font></p>
+Returns a string which contains the native SQL functions to format a date or date 
+column $basedate. This is used in SELECT statements. For INSERT/UPDATE statements, 
+use <a href="#dbdate">DBDate</a>. It uses a case-sensitive $dateFormat, which 
+supports: 
+<pre>
+ Y: 4-digit Year
+ Q: Quarter (1-4)
+ m: Month (01-12)
+ d: Day (01-31)
+ H: Hour (00-23)
+ h: Hour (1-12)
+ i: Minute (00-59)
+ s: Second (00-60)
+ A: AM/PM indicator</pre>
+<p>All other characters are treated as strings. You can also use \ to escape characters. 
+  Available on selected databases, including mysql, postgresql, mssql, oci8 and 
+  DB2. 
+<p>This is useful in writing portable sql statements that GROUP BY on dates. For 
+  example to display total cost of goods sold broken by quarter (dates are stored 
+  in a field called postdate): 
+<pre>
+ $sqlfn = $db->SQLDate('Y-\QQ','postdate'); # get sql that formats postdate to output 2002-Q1
+ $sql = "SELECT $sqlfn,SUM(cogs) FROM table GROUP BY $sqlfn ORDER BY 1 desc";
+ </pre>
+<p><b>MoveNext<a name="movenext"></a>( )</b></p>
+<p>Move the internal cursor to the next row. The <i>$this->fields</i> array is 
+  automatically updated. Returns false if unable to do so (normally because EOF 
+  has been reached), otherwise true. 
+<p> If EOF is reached, then the $this->fields array is set to false (this was 
+  only implemented consistently in ADOdb 3.30). For the pre-3.30 behaviour of 
+  $this->fields (at EOF), set the global variable $ADODB_COMPAT_FETCH = true.</p>
+<p>Example:</p>
+<pre>$rs = $db-&gt;Execute($sql);
+if ($rs) 
+       while (!$rs-&gt;EOF) {
+               ProcessArray($rs->fields);      
+               $rs->MoveNext();
+       } </pre>
+<p><b>Move<a name="move"></a>($to)</b></p>
+<p>Moves the internal cursor to a specific row $<b>to</b>. Rows are zero-based 
+  eg. 0 is the first row. The <b>fields</b> array is automatically updated. For 
+  databases that do not support scrolling internally, ADOdb will simulate forward 
+  scrolling. Some databases do not support backward scrolling. If the $<b>to</b> 
+  position is after the EOF, $<b>to</b> will move to the end of the RecordSet 
+  for most databases. Some obscure databases using odbc might not behave this 
+  way.</p>
+<p>Note: This function uses <i>absolute positioning</i>, unlike Microsoft's ADO.</p>
+<p>Returns true or false. If false, the internal cursor is not moved in most implementations, 
+  so AbsolutePosition( ) will return the last cursor position before the Move( 
+  ). </p>
+<p><b>MoveFirst<a name="movefirst"></a>()</b></p>
+<p>Internally calls Move(0). Note that some databases do not support this function.</p>
+<p><b>MoveLast<a name="movelast"></a>()</b></p>
+<p>Internally calls Move(RecordCount()-1). Note that some databases do not support 
+  this function.</p>
+<p><b>GetRowAssoc</b><a name="getrowassoc"></a>($toUpper=true)</p>
+<p>Returns an associative array containing the current row. The keys to the array 
+  are the column names. The column names are upper-cased for easy access. To get 
+  the next row, you will still need to call MoveNext(). </p>
+<p>For example:<br>
+  Array ( [ID] => 1 [FIRSTNAME] => Caroline [LASTNAME] => Miranda [CREATED] => 
+  2001-07-05 ) </p>
+<p>Note: do not use GetRowAssoc() with $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC. 
+  Because they have the same functionality, they will interfere with each other.</p>
+</font> 
+<p><font color="#000000"><b>AbsolutePage<a name="absolutepage"></a>($page=-1) 
+  </b></font></p>
+<p>Returns the current page. Requires PageExecute()/CachePageExecute() to be called. 
+  See <a href=#ex8>Example 8</a>.</p>
+<font color="#000000"> 
+<p><b>AtFirstPage<a name="atfirstpage">($status='')</a></b></p>
+<p>Returns true if at first page (1-based). Requires PageExecute()/CachePageExecute() 
+  to be called. See <a href=#ex8>Example 8</a>.</p>
+<p><b>AtLastPage<a name="atlastpage">($status='')</a></b></p>
+<p>Returns true if at last page (1-based). Requires PageExecute()/CachePageExecute() 
+  to be called. See <a href=#ex8>Example 8</a>.</p>
+<p><b>Fields</b><a name="fields"></a>(<b>$colname</b>)</p>
+<p>Returns the value of the 
+  associated column $<b>colname</b> for the current row. The column name is case-insensitive.</p>
+<p>This is a convenience function. For higher performance, use <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a>. </p>
+<p><b>FetchRow</b><a name="fetchrow"></a>()</p>
+</font> 
+<p><font color="#000000">Returns array containing current row, or false if EOF. 
+  FetchRow( ) internally moves to the next record after returning the current 
+  row. </font></p>
+<p><font color="#000000">Warning: Do not mix using FetchRow() with MoveNext().</font></p>
+<p><font color="#000000">Usage:</font></p>
+<pre><font color="#000000">$rs = $db-&gt;Execute($sql);
+if ($rs)
+       while ($arr = $rs-&gt;FetchRow()) &#123;
+          &nbsp;&nbsp;# process $arr   
+</font><font color="#000000">  &#125;</font></pre>
+<p><font color="#000000"><b>FetchInto</b><a name="fetchinto"></a>(<b>&amp;$array</b>)</font></p>
+<p><font color="#000000"> Sets $array to the current row. Returns PEAR_Error object 
+  if EOF, 1 if ok (DB_OK constant). If PEAR is undefined, false is returned when 
+  EOF. </font><font color="#000000">FetchInto( ) internally moves to the next 
+  record after returning the current row. </font></p>
+<p><font color="#000000"> FetchRow() is easier to use. See above.</font></p>
+<font color="#000000"> 
+<p><b>FetchField<a name="fetchfield"></a>($column_number)</b></p>
+<p>Returns an object containing the <b>name</b>, <b>type</b> and <b>max_length</b> 
+  of the associated field. If the max_length cannot be determined reliably, it 
+  will be set to -1. The column numbers are zero-based. See <a href="#ex2">example 
+  2.</a></p>
+<p><b>FieldCount<a name="fieldcount"></a>( )</b></p>
+<p>Returns the number of fields (columns) in the record set.</p>
+<p><b>RecordCount<a name="recordcount"></a>( )</b></p>
+<p>Returns the number of rows in the record set. If the number of records returned 
+  cannot be determined from the database driver API, we will buffer all rows and 
+  return a count of the rows after all the records have been retrieved. This buffering 
+  can be disabled (for performance reasons) by setting the global variable $ADODB_COUNTRECS 
+  = false. When disabled, RecordCount( ) will return -1 for certain databases. 
+  See the supported databases list above for more details. </p>
+<p> RowCount is a synonym for RecordCount.</p>
+<p><b>PO_RecordCount<a name="po_recordcount"></a>($table, $where)</b></p>
+<p>Returns the number of rows in the record set. If the database does not support 
+  this, it will perform a SELECT COUNT(*) on the table $table, with the given 
+  $where condition to return an estimate of the recordset size.</p>
+<p>$numrows = $rs-&gt;PO_RecordCount(&quot;articles_table&quot;, &quot;group=$group&quot;);</p>
+<b> NextRecordSet<a name="nextrecordset" id="nextrecordset"></a>()</b> 
+<p>For databases that allow multiple recordsets to be returned in one query, this 
+  function allows you to switch to the next recordset. Currently only supported 
+  by mssql driver.</p>
+<pre>
+$rs = $db-&gt;Execute('execute return_multiple_rs');
+$arr1 = $rs-&gt;GetArray();
+$rs-&gt;NextRecordSet();
+$arr2 = $rs-&gt;GetArray();</pre>
+<p><b>FetchObject<a name="fetchobject"></a>($toupper=true)</b></p>
+<p>Returns the current row as an object. If you set $toupper to true, then the 
+  object fields are set to upper-case. Note: The newer FetchNextObject() is the 
+  recommended way of accessing rows as objects. See below.</p>
+<p><b>FetchNextObject<a name="fetchnextobject"></a>($toupper=true)</b></p>
+<p>Gets the current row as an object and moves to the next row automatically. 
+  Returns false if at end-of-file. If you set $toupper to true, then the object 
+  fields are set to upper-case.</p>
+<pre>
+$rs = $db->Execute('select firstname,lastname from table');
+if ($rs) &#123;
+       while ($o = $rs->FetchNextObject()) &#123;
+               print "$o->FIRSTNAME, $o->LASTNAME&lt;BR>";
+       &#125;
+&#125;
+</pre>
+<p>There is some trade-off in speed in using FetchNextObject(). If performance 
+  is important, you should access rows with the <code>fields[]</code> array. <b>FetchObj<a name="fetchobj" id="fetchobj"></a>()</b> 
+<p>Returns the current record as an object. Fields are not upper-cased, unlike 
+  FetchObject. </font> 
+<p><font color="#000000"><b>FetchNextObj<a name="fetchnextobj" id="fetchnextobj"></a>()</b> 
+  </font></p>
+<p><font color="#000000">Returns the current record as an object and moves to 
+  the next record. If EOF, false is returned. Fields are not upper-cased, unlike 
+  FetctNextObject. </font></p>
+<font color="#000000"> 
+<p><b>CurrentRow<a name="currentrow"></a>( )</b></p>
+<p>Returns the current row of the record set. 0 is the first row.</p>
+<p><b>AbsolutePosition<a name="abspos"></a>( )</b></p>
+<p>Synonym for <b>CurrentRow</b> for compatibility with ADO. Returns the current 
+  row of the record set. 0 is the first row.</p>
+<p><b>MetaType<a name="metatype"></a>($nativeDBType[,$field_max_length],[$fieldobj])</b></p>
+<p>Determine what <i>generic</i> meta type a database field type is given its 
+  native type $<b>nativeDBType</b> as a string and the length of the field $<b>field_max_length</b>. 
+  Note that field_max_length can be -1 if it is not known. The field object returned 
+  by FetchField() can be passed in $<b>fieldobj</b> or as the 1st parameter <b>$nativeDBType</b>. 
+  This is useful for databases such as <i>mysql</i> which has additional properties 
+  in the field object such as <i>primary_key</i>. </p>
+<p>Uses the field <b>blobSize</b> and compares it with $<b>field_max_length</b> 
+  to determine whether the character field is actually a blob.</p>
+For example, $db-&gt;MetaType('char') will return 'C'. 
+<p>Returns:</p>
+<ul>
+  <li><b>C</b>: Character fields that should be shown in a &lt;input type=&quot;text&quot;&gt; 
+    tag. </li>
+  <li><b>X</b>: Clob (character large objects), or large text fields that should 
+    be shown in a &lt;textarea&gt;</li>
+  <li><b>D</b>: Date field</li>
+  <li><b>T</b>: Timestamp field</li>
+  <li><b>L</b>: Logical field (boolean or bit-field)</li>
+  <li><b>N</b>: Numeric field. Includes decimal, numeric, floating point, and 
+    real. </li>
+  <li><b>I</b>:&nbsp; Integer field. </li>
+  <li><b>R</b>: Counter or Autoincrement field. Must be numeric.</li>
+  <li><b>B</b>: Blob, or binary large objects.<font color="#000000"> </font></li>
+</ul>
+</font> 
+<p><font color="#000000"> Since ADOdb 3.0, MetaType accepts $fieldobj as the first 
+  parameter, instead of $nativeDBType. </font></p>
+<font color="#000000"> 
+<p><b>Close( )<a name="rsclose"></a></b></p>
+<p>Closes the recordset, cleaning all memory and resources associated with the recordset. 
+<p>
+If memory management is not an issue, you do not need to call this function as recordsets
+are closed for you by PHP at the end of the script. 
+SQL statements such as INSERT/UPDATE/DELETE do not really return a recordset, so you do not have to call Close()
+for such SQL statements.</p>
+<hr>
+<h3>function rs2html<a name="rs2html"></a>($adorecordset,[$tableheader_attributes], 
+  [$col_titles])</h3>
+<p>This is a standalone function (rs2html = recordset to html) that is similar 
+  to PHP's <i>odbc_result_all</i> function, it prints a ADORecordSet, $<b>adorecordset</b> 
+  as a HTML table. $<b>tableheader_attributes</b> allow you to control the table 
+  <i>cellpadding</i>, <i>cellspacing</i> and <i>border</i> attributes. Lastly 
+  you can replace the database column names with your own column titles with the 
+  array $<b>col_titles</b>. This is designed more as a quick debugging mechanism, 
+  not a production table recordset viewer.</p>
+<p>You will need to include the file <i>tohtml.inc.php</i>.</p>
+<p>Example of rs2html:<b><font color="#336600"><a name="exrs2html"></a></font></b></p>
+<pre><b><font color="#336600">&lt;?
+include('tohtml.inc.php')</font></b>; # load code common to ADOdb 
+<b>include</b>('adodb.inc.php'); # load code common to ADOdb 
+$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql');   # create a connection 
+$<font color="#663300">conn</font>->PConnect('localhost','userid','','agora');# connect to MySQL, agora db
+$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers'; 
+$<font color="#663300">rs</font>   = $<font color="#663300">conn</font>->Execute($sql); 
+<font color="#336600"><b>rs2html</b></font><b>($<font color="#663300">rs</font>,'<i>border=2 cellpadding=3</i>',array('<i>Customer Name','Customer ID</i>'));
+?&gt;</b></pre>
+<hr>
+<h3>Differences between this ADOdb library and Microsoft ADO<a name="adodiff"></a></h3>
+<ol>
+  <li>ADOdb only supports recordsets created by a connection object. Recordsets 
+    cannot be created independently.</li>
+  <li>ADO properties are implemented as functions in ADOdb. This makes it easier 
+    to implement any enhanced ADO functionality in the future.</li>
+  <li>ADOdb's <font face="Courier New, Courier, mono">ADORecordSet-&gt;Move()</font> 
+    uses absolute positioning, not relative. Bookmarks are not supported.</li>
+  <li><font face="Courier New, Courier, mono">ADORecordSet-&gt;AbsolutePosition() 
+    </font>cannot be used to move the record cursor.</li>
+  <li>ADO Parameter objects are not supported. Instead we have the ADOConnection::<a href="#parameter">Parameter</a>( 
+    ) function, which provides a simpler interface for calling preparing parameters 
+    and calling stored procedures.</li>
+  <li>Recordset properties for paging records are available, but implemented as 
+    in <a href=#ex8>Example 8</a>.</li>
+</ol>
+<hr>
+<h1>Database Driver Guide<a name="driverguide"></a></h1>
+<p>This describes how to create a class to connect to a new database. To ensure 
+  there is no duplication of work, kindly email me at jlim#natsoft.com.my if you 
+  decide to create such a class.</p>
+<p>First decide on a name in lower case to call the database type. Let's say we 
+  call it xbase. </p>
+<p>Then we need to create two classes ADODB_xbase and ADORecordSet_xbase in the 
+  file adodb-xbase.inc.php.</p>
+<p>The simplest form of database driver is an adaptation of an existing ODBC driver. 
+  Then we just need to create the class <i>ADODB_xbase extends ADODB_odbc</i> 
+  to support the new <b>date</b> and <b>timestamp</b> formats, the <b>concatenation</b> 
+  operator used, <b>true</b> and <b>false</b>. For the<i> ADORecordSet_xbase extends 
+  ADORecordSet_odbc </i>we need to change the <b>MetaType</b> function. See<b> 
+  adodb-vfp.inc.php</b> as an example.</p>
+<p>More complicated is a totally new database driver that connects to a new PHP 
+  extension. Then you will need to implement several functions. Fortunately, you 
+  do not have to modify most of the complex code. You only need to override a 
+  few stub functions. See <b>adodb-mysql.inc.php</b> for example.</p>
+<p>The default date format of ADOdb internally is YYYY-MM-DD (Ansi-92). All dates 
+  should be converted to that format when passing to an ADOdb date function. See 
+  Oracle for an example how we use ALTER SESSION to change the default date format 
+  in _pconnect _connect.</p>
+<p><b>ADOConnection Functions to Override</b></p>
+<p>Defining a constructor for your ADOConnection derived function is optional. 
+  There is no need to call the base class constructor.</p>
+<p>_<b>connect</b>: Low level implementation of Connect. Returns true or false. 
+  Should set the _<b>connectionID</b>.</p>
+<p>_<b>pconnect:</b> Low level implemention of PConnect. Returns true or false. 
+  Should set the _<b>connectionID</b>.</p>
+<p>_<b>query</b>: Execute a query. Returns the queryID, or false.</p>
+<p>_<b>close: </b>Close the connection -- PHP should clean up all recordsets. 
+</p>
+<p><b>ErrorMsg</b>: Stores the error message in the private variable _errorMsg. 
+</p>
+<p><b>ADOConnection Fields to Set</b></p>
+<p>_<b>bindInputArray</b>: Set to true if binding of parameters for SQL inserts 
+  and updates is allowed using ?, eg. as with ODBC.</p>
+<p><b>fmtDate</b></p>
+<p><b>fmtTimeStamp</b></p>
+<p><b>true</b></p>
+<p><b>false</b></p>
+<p><b>concat_operator</b></p>
+<p><b>replaceQuote</b></p>
+<p><b>hasLimit</b> support SELECT * FROM TABLE LIMIT 10 of MySQL.</p>
+<p><b>hasTop</b> support Microsoft style SELECT TOP 10 * FROM TABLE.</p>
+<p><b>ADORecordSet Functions to Override</b></p>
+<p>You will need to define a constructor for your ADORecordSet derived class that 
+  calls the parent class constructor.</p>
+<p><b>FetchField: </b> as documented above in ADORecordSet</p>
+<p>_<b>initrs</b>: low level initialization of the recordset: setup the _<b>numOfRows</b> 
+  and _<b>numOfFields</b> fields -- called by the constructor.</p>
+<p>_<b>seek</b>: seek to a particular row. Do not load the data into the fields 
+  array. This is done by _fetch. Returns true or false. Note that some implementations 
+  such as Interbase do not support seek. Set canSeek to false.</p>
+<p>_<b>fetch</b>: fetch a row using the database extension function and then move 
+  to the next row. Sets the <b>fields</b> array. If the parameter $ignore_fields 
+  is true then there is no need to populate the <b>fields</b> array, just move 
+  to the next row. then Returns true or false.</p>
+<p>_<b>close</b>: close the recordset</p>
+<p><b>Fields</b>: If the array row returned by the PHP extension is not an associative 
+  one, you will have to override this. See adodb-odbc.inc.php for an example. 
+  For databases such as MySQL and MSSQL where an associative array is returned, 
+  there is no need to override this function.</p>
+<p><b>ADOConnection Fields to Set</b></p>
+<p>canSeek: Set to true if the _seek function works.</p>
+<h2>ToDo:</h2>
+<p>See the <a href=http://php.weblogs.com/adodb-todo-roadmap>RoadMap</a> article.</p>
+<p>Also see the ADOdb <a href=http://php.weblogs.com/adodb_csv>proxy</a> article 
+  for bridging Windows and Unix databases using http remote procedure calls. For 
+  your education, visit <a href=http://palslib.com/>palslib.com</a> for database info, 
+  and read this article on <a href=http://phplens.com/lens/php-book/optimizing-debugging-php.php>Optimizing 
+  PHP</a>. </p>
+</font>
+<h2>Change Log<a name="Changes"></a><a name="changes"></a><a name="changelog"></a></h2>
+<p><b>4.20 27 Feb 2004</b>
+<p>Updated to AXMLS 1.01.
+<p>MetaForeignKeys for postgres7 modified by Edward Jaramilla, works on pg 7.4.
+<p>Now numbers accepts function calls or sequences for GetInsertSQL/GetUpdateSQL numeric fields.
+<p>Changed quotes of 'delete from $perf_table' to "". Thx Kehui (webmaster#kehui.net)
+<p>Added ServerInfo() for ifx, and putenv trim fix. Thx Fernando Ortiz.
+<p>Added addq(), which is analogous to addslashes().
+<p>Tested with php5b4. Fix some php5 compat problems with exceptions and sybase.
+<P>Carl-Christian Salvesen added patch to mssql _query to support binds greater than 4000 chars.
+<p>Mike suggested patch to PHP5 exception handler. $errno must be numeric.
+<p>Added double quotes (") to ADODB_TABLE_REGEX.
+<p>For oci8, Prepare(...,$cursor), $cursor's meaning was accidentally inverted in 4.11. This causes problems with ExecuteCursor() too, which calls Prepare() internally. Thx to William Lovaton.
+<p>Now dateHasTime property in connection object renamed to datetime for consistency. This could break bc.
+<p>Csongor Halmai reports that db2 SelectLimit with input array is not working. Fixed..
+<p><b>4.11 27 Jan 2004</b>
+<p>Csongor Halmai reports db2 binding not working. Reverted back to emulated binding.
+<p>Dan Cech modifies datadict code. Adds support for DropIndex. Minor cleanups.
+<p>Table misspelt in perf-oci8.inc.php. Changed v$conn_cache_advice to v$db_cache_advice. Reported by Steve W.
+<p>UserTimeStamp and DBTimeStamp did not handle YYYYMMDDHHMMSS format properly. Reported by Mike Muir. Fixed.
+<p>Changed oci8 Prepare(). Does not auto-allocate OCINewCursor automatically, unless 2nd param is set to true.
+This will break backward compat, if Prepare/Execute is used instead of ExecuteCursor. Reported by Chris Jones.
+<p>Added InParameter() and OutParameter(). Wrapper functions to Parameter(), but nicer because they
+are self-documenting.
+<p>Added 'R' handling in ActualType() to datadict-mysql.inc.php
+<p>Added ADOConnection::SerializableRS($rs). Returns a recordset that can be serialized in a session.
+<p>Added "Run SQL" to performance UI().
+<p>Misc spelling corrections in adodb-mysqli.inc.php, adodb-oci8.inc.php and datadict-oci8.inc.php, from Heinz Hombergs.
+<p>MetaIndexes() for ibase contributed by Heinz Hombergs.
+<p><b>4.10 12 Jan 2004</b>
+<p>Dan Cech contributed extensive changes to data dictionary to support name quoting (with `), and drop table/index.
+<p>Informix added cursorType property. Default remains IFX_SCROLL, but you can change to 0 (non-scrollable cursor) for performance.
+<p>Added ADODB_View_PrimaryKeys() for returning view primary keys to MetaPrimaryKeys().
+<p>Simplified chinese file, adodb-cn.inc.php from cysoft.
+<p>Added check for ctype_alnum in adodb-datadict.inc.php. Thx to Jason Judge.
+<p>Added connection parameter to ibase Prepare(). Fix by Daniel Hassan.
+<p>Added nameQuote for quoting identifiers and names to connection obj. Requested by Jason Judge. Also the
+data dictionary parser now detects `field name` and generates column names with spaces correctly.
+<p>BOOL type not recognised correctly as L. Fixed.
+<p>Fixed paths in ADODB_DIR for session files, and back-ported it to 4.05 (15 Dec 2003)
+<p>Added Schema to postgresql MetaTables. Thx to col#gear.hu
+<p>Empty postgresql recordsets that had blob fields did not set EOF properly. Fixed.
+<p>CacheSelectLimit internal parameters to SelectLimit were wrong. Thx to Nio.
+<p>Modified adodb_pr() and adodb_backtrace() to support command-line usage (eg. no html).
+<p>Fixed some fr and it lang errors. Thx to Gaetano G.
+<p>Added contrib directory, with adodb rs to xmlrpc convertor by Gaetano G.
+<p>Fixed array recordset bugs when _skiprow1 is true. Thx to Gaetano G.
+<p>Fixed pivot table code when count is false.
+<p>
+
+<p><b>4.05 13 Dec 2003 </b>
+<p>Added MetaIndexes - thx to Dan Cech.
+<p>Rewritten session code by Ross Smith. Moved code to adodb/session directory.
+<p>Added function exists check on connecting to most drivers, so we don't crash with the unknown function error.
+<p>Smart Transactions failed with GenID() when it no seq table has been created because the sql
+       statement fails. Fix by Mark Newnham.
+<p>Added $db->length, which holds name of function that returns strlen.
+<p>Fixed error handling for bad driver in ADONewConnection - passed too few params to error-handler.
+<p>Datadict did not handle types like 16.0 properly in _GetSize. Fixed.
+<p>Oci8 driver SelectLimit() bug &= instead of =& used. Thx to Swen Thümmler.
+<p>Jesse Mullan suggested not flushing outp when output buffering enabled. Due to Apache 2.0 bug. Added.
+<p>MetaTables/MetaColumns return ref bug with PHP5 fixed in adodb-datadict.inc.php.
+<p>New mysqli driver contributed by Arjen de Rijke. Based on adodb 3.40 driver.
+Then jlim added BeginTrans, CommitTrans, RollbackTrans, IfNull, SQLDate. Also fixed return ref bug.
+<p>$ADODB_FLUSH added, if true then force flush in debugging outp. Default is false.  In earlier
+versions, outp defaulted to flush, which is not compat with apache 2.0.
+<p>Mysql driver's GenID() function did not work when when sql logging is on. Fixed.
+<p>$ADODB_SESSION_TBL not declared as global var. Not available if adodb-session.inc.php included in function. Fixed.
+<p>The input array not passed to Execute() in _adodb_getcount(). Fixed.
+<p><b>4.04 13 Nov 2003 </b>
+<p>Switched back to foreach - faster than list-each.
+<p>Fixed bug in ado driver - wiping out $this->fields with date fields.
+<p>Performance Monitor, View SQL, Explain Plan did not work if strlen($SQL)>max($_GET length). Fixed.
+<p>Performance monitor, oci8 driver added memory sort ratio.
+<p>Added random property, returns SQL to generate a floating point number between 0 and 1;
+<p><b>4.03 6 Nov 2003 </b>
+<p>The path to adodb-php4.inc.php and adodb-iterators.inc.php was not setup properly.
+<p>Patched SQLDate in interbase to support hours/mins/secs. Thx to ari kuorikoski.
+<p>Force autorollback for pgsql persistent connections - 
+apparently pgsql did not autorollback properly before 4.3.4. See http://bugs.php.net/bug.php?id=25404
+<p><b>4.02 5 Nov 2003 </b>
+<p>Some errors in adodb_error_pg() fixed. Thx to Styve.
+<p>Spurious Insert_ID() error was generated by LogSQL(). Fixed.
+<p>Insert_ID was interfering with Affected_Rows() and Replace()  when LogSQL() enabled. Fixed.
+<p>More foreach loops optimized with list/each.
+<p>Null dates not handled properly in ADO driver (it becomes 31 Dec 1969!).
+<p>Heinz Hombergs contributed patches for mysql MetaColumns - adding scale, made
+interbase MetaColumns work with firebird/interbase, and added lang/adodb-de.inc.php.
+<p>Added INFORMIXSERVER environment variable.
+<p>Added $ADODB_ANSI_PADDING_OFF for interbase/firebird.
+<p>PHP 5 beta 2 compat check. Foreach (Iterator) support. Exceptions support.
+<p><b>4.01 23 Oct 2003 </b>
+<p>Fixed bug in rs2html(), tohtml.inc.php, that generated blank table cells.
+<p>Fixed insert_id() incorrectly generated when logsql() enabled.
+<p>Modified PostgreSQL _fixblobs to use list/each instead of foreach.
+<p>Informix ErrorNo() implemented correctly.
+<p>Modified several places to use list/each, including GetRowAssoc().
+<p>Added UserTimeStamp() to connection class.
+<p>Added $ADODB_ANSI_PADDING_OFF for oci8po.
+<p><b>4.00 20 Oct 2003 </b>
+<p>Upgraded adodb-xmlschema to 1 Oct 2003 snapshot.
+<p>Fix to rs2html warning message. Thx to Filo.
+<p>Fix for odbc_mssql/mssql SQLDate(), hours was wrong.
+<p>Added MetaColumns and MetaPrimaryKeys for sybase. Thx to Chris Phillipson.
+<p>Added autoquoting to datadict for MySQL and PostgreSQL. Suggestion by Karsten Dambekalns  
+<p><b>3.94 11 Oct 2003 </b>
+<p>Create trigger in datadict-oci8.inc.php did not work, because all cr/lf's must be removed. 
+<p>ErrorMsg()/ErrorNo() did not work for many databases when logging enabled. Fixed.
+<p>Removed global variable $ADODB_LOGSQL as it does not work properly with multiple connections.
+<p>Added SQLDate support for sybase. Thx to Chris Phillipson
+<p>Postgresql checking of pgsql resultset resource was incorrect. Fix by Bharat Mediratta bharat#menalto.com.
+Same patch applied to  _insertid and _affectedrows for adodb-postgres64.inc.php.
+<p>Added support for NConnect for postgresql.
+<p>Added Sybase data dict support. Thx to Chris Phillipson  
+<p>Extensive improvements in $perf->UI(), eg. Explain now opens in new window, we show scripts
+which call sql, etc.
+<p>Perf Monitor UI works with magic quotes enabled.
+<p>rsPrefix was declared twice. Removed.
+<p>Oci8 stored procedure support, eg. "begin func(); end;" was incorrect in _query. Fixed.
+<p>Tiraboschi Massimiliano contributed italian language file.
+<p>Fernando Ortiz, fortiz#lacorona.com.mx, contributed informix performance monitor.
+<p>Added _varchar (varchar arrays) support for postgresql. Reported by PREVOT Stéphane.
+<p><b>3.92 22 Sept 2003</b> 
+<p>Added GetAssoc and CacheGetAssoc to connection object.
+<p>Removed TextMax and CharMax functions from adodb.inc.php. 
+<p>HasFailedTrans() returned false when trans failed. Fixed. 
+<p>Moved perf driver classes into adodb/perf/*.php. 
+<p>Misc improvements to performance monitoring, including UI(). 
+<p>RETVAL in mssql Parameter(), we do not append @ now. 
+<p>Added Param($name) to connection class, returns '?' or ":$name", for defining 
+  bind parameters portably. 
+<p>LogSQL traps affected_rows() and saves its value properly now. Also fixed oci8 
+  _stmt and _affectedrows() bugs. 
+<p>Session code timestamp check for oci8 works now. Formerly default NLS_DATE_FORMAT 
+  stripped off time portion. Thx to Tony Blair (tonanbarbarian#hotmail.com). Also 
+  added new $conn->datetime field to oci8, controls whether MetaType() returns 
+  'D' ($this->datetime==false) or 'T' ($this->datetime == true) for DATE type. 
+<p>Fixed bugs in adodb-cryptsession.inc.php and adodb-session-clob.inc.php. 
+<p>Fixed misc bugs in adodb_key_exists, GetInsertSQL() and GetUpdateSQL(). 
+<p>Tuned include_once handling to reduce file-system checking overhead. 
+<p><b>3.91 9 Sept 2003</b> 
+<p>Only released to InterAkt 
+<p>Added LogSQL() for sql logging and $ADODB_NEWCONNECTION to override factory 
+  for driver instantiation. 
+<p>Added IfNull($field,$ifNull) function, thx to johnwilk#juno.com 
+<p>Added portable substr support. 
+<p>Now rs2html() has new parameter, $echo. Set to false to return $html instead 
+  of echoing it. 
+<p><b>3.90 5 Sept 2003</b> 
+<p>First beta of performance monitoring released. 
+<p>MySQL supports MetaTable() masking. 
+<p>Fixed key_exists() bug in adodb-lib.inc.php 
+<p>Added sp_executesql Prepare() support to mssql. 
+<p>Added bind support to db2. 
+<p>Added swedish language file - Christian Tiberg" christian#commsoft.nu 
+<p>Bug in drop index for mssql data dict fixed. Thx to Gert-Rainer Bitterlich. 
+<p>Left join setting for oci8 was wrong. Thx to johnwilk#juno.com 
+<p><b>3.80 27 Aug 2003</b> 
+<p>Patch for PHP 4.3.3 cached recordset csv2rs() fread loop incompatibility. 
+<p>Added matching mask for MetaTables. Only for oci8, mssql and postgres currently. 
+<p>Rewrite of "oracle" driver connection code, merging with "oci8", by Gaetano. 
+<p>Added better debugging for Smart Transactions. 
+<p>Postgres DBTimeStamp() was wrongly using TO_DATE. Changed to TO_TIMESTAMP. 
+<p>ADODB_FETCH_CASE check pushed to ADONewConnection to allow people to define 
+  it after including adodb.inc.php. 
+<p>Added portugese (brazilian) to languages. Thx to "Levi Fukumori". 
+<p>Removed arg3 parameter from Execute/SelectLimit/Cache* functions. 
+<p>Execute() now accepts 2-d array as $inputarray. Also changed docs of fnExecute() 
+  to note change in sql query counting with 2-d arrays. 
+<p>Added MONEY to MetaType in PostgreSQL. 
+<p>Added more debugging output to CacheFlush(). 
+<p><b>3.72 9 Aug 2003</b> 
+<p>Added qmagic($str), which is a qstr($str) that auto-checks for magic quotes 
+  and does the right thing... 
+<p>Fixed CacheFlush() bug - Thx to martin#gmx.de 
+<p>Walt Boring contributed MetaForeignKeys for postgres7. 
+<p>_fetch() called _BlobDecode() wrongly in interbase. Fixed. 
+<p>adodb_time bug fixed with dates after 2038 fixed by Jason Pell. http://phplens.com/lens/lensforum/msgs.php?id=6980 
+<p><b>3.71 4 Aug 2003</b> 
+<p>The oci8 driver, MetaPrimaryKeys() did not check the owner correctly when $owner 
+  == false. 
+<p>Russian language file contributed by "Cyrill Malevanov" cyrill#malevanov.spb.ru. 
+<p>Spanish language file contributed by "Horacio Degiorgi" horaciod#codigophp.com. 
+<p>Error handling in oci8 bugfix - if there was an error in Execute(), then when 
+  calling ErrorNo() and/or ErrorMsg(), the 1st call would return the error, but 
+  the 2nd call would return no error. 
+<p>Error handling in odbc bugfix. ODBC would always return the last error, even 
+  if it happened 5 queries ago. Now we reset the errormsg to '' and errorno to 
+  0 everytime before CacheExecute() and Execute(). 
+<p><b>3.70 29 July 2003</b> 
+<p>Added new SQLite driver. Tested on PHP 4.3 and PHP 5. 
+<p>Added limited "sapdb" driver support - mainly date support. 
+<p>The oci8 driver did not identify NUMBER with no defined precision correctly. 
+<p>Added ADODB_FORCE_NULLS, if set, then PHP nulls are converted to SQL nulls 
+  in GetInsertSQL/GetUpdateSQL. 
+<p>DBDate() and DBTimeStamp() format for postgresql had problems. Fixed. 
+<p>Added tableoptions to ChangeTableSQL(). Thx to Mike Benoit. 
+<p>Added charset support to postgresql. Thx to Julian Tarkhanov. 
+<p>Changed OS check for MS-Windows to prevent confusion with darWIN (MacOS) 
+<p>Timestamp format for db2 was wrong. Changed to yyyy-mm-dd-hh.mm.ss.nnnnnn. 
+<p>adodb-cryptsession.php includes wrong. Fixed. 
+<p>Added MetaForeignKeys(). Supported by mssql, odbc_mssql and oci8. 
+<p>Fixed some oci8 MetaColumns/MetaPrimaryKeys bugs. Thx to Walt Boring. 
+<p>adodb_getcount() did not init qryRecs to 0. Missing "WHERE" clause checking 
+  in GetUpdateSQL fixed. Thx to Sebastiaan van Stijn. 
+<p>Added support for only 'VIEWS' and "TABLES" in MetaTables. From Walt Boring. 
+<p>Upgraded to adodb-xmlschema.inc.php 0.0.2. 
+<p>NConnect for mysql now returns value. Thx to Dennis Verspuij. 
+<p>ADODB_FETCH_BOTH support added to interbase/firebird. 
+<p>Czech language file contributed by Kamil Jakubovic jake#host.sk. 
+<p>PostgreSQL BlobDecode did not use _connectionID properly. Thx to Juraj Chlebec. 
+<p>Added some new initialization stuff for Informix. Thx to "Andrea Pinnisi" pinnisi#sysnet.it 
+<p>ADODB_ASSOC_CASE constant wrong in sybase _fetch(). Fixed. 
+<p><b>3.60 16 June 2003</b> 
+<p>We now SET CONCAT_NULL_YIELDS_NULL OFF for odbc_mssql driver to be compat with 
+  mssql driver. 
+<p>The property $emptyDate missing from connection class. Also changed 1903 to 
+  constant (TIMESTAMP_FIRST_YEAR=100). Thx to Sebastiaan van Stijn. 
+<p>ADOdb speedup optimization - we now return all arrays by reference. 
+<p>Now DBDate() and DBTimeStamp() now accepts the string 'null' as a parameter. 
+  Suggested by vincent. 
+<p>Added GetArray() to connection class. 
+<p>Added not_null check in informix metacolumns(). 
+<p>Connection parameters for postgresql did not work correctly when port was defined. 
+<p>DB2 is now a tested driver, making adodb 100% compatible. Extensive changes 
+  to odbc driver for DB2, including implementing serverinfo() and SQLDate(), switching 
+  to SQL_CUR_USE_ODBC as the cursor mode, and lastAffectedRows and SelectLimit() 
+  fixes. 
+<p>The odbc driver's FetchField() field names did not obey ADODB_ASSOC_CASE. Fixed. 
+<p>Some bugs in adodb_backtrace() fixed. 
+<p>Added "INT IDENTITY" type to adorecordset::MetaType() to support odbc_mssql 
+  properly. 
+<p>MetaColumns() for oci8, mssql, odbc revised to support scale. Also minor revisions 
+  to odbc MetaColumns() for vfp and db2 compat. 
+<p>Added unsigned support to mysql datadict class. Thx to iamsure. 
+<p>Infinite loop in mssql MoveNext() fixed when ADODB_FETCH_ASSOC used. Thx to 
+  Josh R, Night_Wulfe#hotmail.com. 
+<p>ChangeTableSQL contributed by Florian Buzin. 
+<p>The odbc_mssql driver now sets CONCAT_NULL_YIELDS_NULL OFF for compat with 
+  mssql driver. 
+<hr>
+<p><strong>0.10 Sept 9 2000</strong> First release 
+<h3><strong>Old changelog history moved to <a href=old-changelog.htm>old-changelog.htm</a>. 
+  </strong></h3>
+<p>&nbsp;</p>
+<p> </font> 
+</body>
+</html>
index a5192d48ab2efd001f08f4728b5f7b66f08c48fc..aa795c0e76d13d923c53dc27b0e8fdad01fd0a47 100644 (file)
-<html>\r
-<head>\r
-<title>ADODB Data Dictionary Manual</title>\r
-<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">\r
-<XSTYLE\r
-       body,td {font-family:Arial,Helvetica,sans-serif;font-size:11pt}\r
-       pre {font-size:9pt}\r
-       .toplink {font-size:8pt}\r
-       />\r
-</head>        \r
-<body bgcolor="#FFFFFF">\r
-\r
-<h2>ADOdb Data Dictionary Library for PHP</h2>\r
-<p> V4.11 27 Jan 2004 (c) 2000-2004 John Lim (<a href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a>)</p>\r
-<p><font size=1>This software is dual licensed using BSD-Style and LGPL. This \r
-  means you can use it in compiled proprietary and commercial products.</font></p>\r
-<p>Useful ADOdb links:  <a href=http://php.weblogs.com/adodb?dd=1>Download</a> &nbsp; <a href=http://php.weblogs.com/adodb_manual?dd=1>Other Docs</a>\r
-\r
-<p>This documentation describes a class library to automate the creation of tables, \r
-  indexes and foreign key constraints portably for multiple databases. \r
-<p>Currently the following databases are supported: \r
-<p> Well-tested: PostgreSQL, MySQL, Oracle, MSSQL. <br>\r
-Beta-quality: DB2, Informix, Sybase, Interbase, Firebird.<br>\r
-Alpha-quality: MS Access (does not support DEFAULT values) and generic ODBC.</p>\r
-<h3>Example Usage</h3>\r
-<pre>include_once('adodb.inc.php');\r
-<font color="#006600">\r
-# First create a normal connection\r
-</font>$db->NewADOConnection('mysql');\r
-$db->Connect(...);\r
-<br>\r
-<font color="#006600"># Then create a data dictionary object, using this connection\r
-</font>$dict = <strong>NewDataDictionary</strong>($db);\r
-\r
-<font color="#006600"># We have a portable declarative data dictionary format in ADOdb 3.50, similar to SQL.\r
-# Field types use 1 character codes, and fields are separated by commas.\r
-# The following example creates three fields: "col1", "col2" and "col3":</font>\r
-$flds = " \r
-<font color="#663300"><strong> col1 C(32) NOTNULL DEFAULT 'abc',\r
- col2 I  DEFAULT 0,\r
- col3 N(12.2)</strong></font>\r
-";<br>\r
-<font color="#006600"># We demonstrate creating tables and indexes</font>\r
-$sqlarray = $dict-><strong>CreateTableSQL</strong>($tabname, $flds, $taboptarray);\r
-$dict-><strong>ExecuteSQLArray</strong>($sqlarray);<br>\r
-$idxflds = 'co11, col2';\r
-$sqlarray = $dict-><strong>CreateIndexSQL</strong>($idxname, $tabname, $idxflds);\r
-$dict-><strong>ExecuteSQLArray</strong>($sqlarray);\r
-</pre>\r
-<h3>Functions</h3>\r
-<p><b>function CreateDatabase($dbname, $optionsarray=false)</b>\r
-<p>Create a database with the name $dbname;\r
-<p><b>function CreateTableSQL($tabname, $fldarray, $taboptarray=false)</b>\r
-<pre>\r
-       RETURNS:        an array of strings, the sql to be executed, or false\r
-       $tabname:       name of table\r
-       $fldarray:      string (or array) containing field info\r
-       $taboptarray:   array containing table options\r
-</pre>\r
-<p>\r
-       The new format of $fldarray uses a free text format, where each field is comma-delimited.\r
-       The first token for each field is the field name, followed by the type and optional\r
-       field size. Then optional keywords in $otheroptions:\r
-       <pre>   "$fieldname $type $colsize $otheroptions"</pre>\r
-<p>    The older (and still supported) format of $fldarray is a 2-dimensional array, where each row in the \r
-       1st dimension represents one field. Each row has this format:\r
-<pre>  array($fieldname, $type, [,$colsize] [,$otheroptions]*)</pre>\r
-       \r
-<p>The first 2 fields must be the field name and the field type. The field type\r
-       can be a portable type codes or the actual type for that database.</p>\r
-<p>\r
-       Legal portable type codes include:\r
-<pre>\r
-C:  varchar\r
-X:  Largest varchar size \r
-XL: For Oracle, returns CLOB, otherwise same as 'X' above\r
-\r
-C2: Multibyte varchar\r
-X2: Multibyte varchar (largest size)\r
-\r
-B:  BLOB (binary large object)<br>\r
-D:  Date (some databases do not support this, and we return a datetime type)\r
-T:  Datetime or Timestamp\r
-L:  Integer field suitable for storing booleans (0 or 1)\r
-I:  Integer (mapped to I4)\r
-I1: 1-byte integer\r
-I2: 2-byte integer\r
-I4: 4-byte integer\r
-I8: 8-byte integer\r
-F:  Floating point number\r
-N:  Numeric or decimal number\r
-</pre>\r
-<p>    The $colsize field represents the size of the field. If a decimal number is \r
-       used, then it is assumed that the number following the dot is the precision,\r
-       so 6.2 means a number of size 6 digits and 2 decimal places. It is \r
-       recommended that the default for number types be represented as a string to \r
-       avoid any rounding errors.\r
-<p>\r
-       The $otheroptions include the following keywords (case-insensitive):\r
-<pre>\r
-AUTO            For autoincrement number. Emulated with triggers if not available.\r
-                               Sets NOTNULL also.\r
-AUTOINCREMENT   Same as auto.\r
-KEY             Primary key field. Sets NOTNULL also. Compound keys are supported.\r
-PRIMARY                Same as KEY.\r
-DEF             Synonym for DEFAULT for lazy typists.\r
-DEFAULT         The default value. Character strings are auto-quoted unless\r
-                the string begins and ends with spaces, eg ' SYSDATE '.\r
-NOTNULL         If field is not null.\r
-DEFDATE         Set default value to call function to get today's date.\r
-DEFTIMESTAMP    Set default to call function to get today's datetime.\r
-NOQUOTE         Prevents autoquoting of default string values.\r
-CONSTRAINTS     Additional constraints defined at the end of the field\r
-                definition.\r
-</pre>\r
-<p> The Data Dictonary accepts two formats, the older array specification: </p>\r
-<pre>\r
-$flds = array(\r
-       array('COLNAME',   'DECIMAL', '8.4', 'DEFAULT' => 0, 'NotNull'),\r
-       array('id',        'I'      , 'AUTO'),\r
-       array('`MY DATE`', 'D'      , 'DEFDATE'),\r
-       array('NAME',      'C'      , '32', \r
-                 'CONSTRAINTS' => 'FOREIGN KEY REFERENCES reftable')\r
-);  </pre>\r
-Or the simpler declarative format:\r
-<pre> $flds = "\r
-<font color="#660000"><strong> COLNAME DECIMAL(8.4) DEFAULT 0 NotNull,\r
- id I AUTO,\r
- `MY DATE` D DEFDATE, \r
- NAME C(32) CONSTRAINTS 'FOREIGN KEY REFERENCES reftable' </strong></font>\r
-"; \r
-</pre>\r
-<p>\r
-       Note that if you have special characters in the field name (e.g. My Date), you should enclose it in back-quotes. Normally field names are not case-sensitive, but if you enclose it in back-quotes, some databases treat the names as case-sensitive, and some don't. So be careful.\r
-<p>The $taboptarray is the 3rd parameter of the CreateTableSQL function. \r
-       This contains table specific settings. Legal keywords include:\r
-        \r
-<ul>\r
-       <li>REPLACE <br>\r
-               Indicates that the previous table definition should be removed (dropped)together \r
-               with ALL data. See first example below.<br>\r
-       </li>\r
-       <li>DROP <br>\r
-               Drop table. Useful for removing unused tables.<br>\r
-       </li>\r
-       <li>CONSTRAINTS <br>\r
-               Define this as the key, with the constraint as the value. See the postgresql \r
-               example below. Additional constraints defined for the whole table. You \r
-               will probably need to prefix this with a comma. </li>\r
-</ul>\r
-<p> Database specific table options can be defined also using the name of the \r
-       database type as the array key. In the following example, <em>create the table \r
-       as ISAM with MySQL, and store the table in the &quot;users&quot; tablespace \r
-       if using Oracle</em>. And if the table already exists, drop the table first.\r
-<pre>  $taboptarray = array('mysql' => 'TYPE=ISAM', 'oci8' => 'tablespace users', 'REPLACE');  </pre>\r
-<p>\r
-       You can also define foreignkey constraints. The following is syntax for \r
-       postgresql:<pre>\r
-       $taboptarray = array('constraints' => \r
-                                       ', FOREIGN KEY (col1) REFERENCES reftable (refcol)');\r
-</pre>\r
-<p><strong>function ChangeTableSQL($tabname, $flds)</strong>\r
-<p>Checks to see if table exists, if table does not exist, behaves like CreateTableSQL. \r
-  If table exists, generates appropriate ALTER TABLE MODIFY COLUMN commands if \r
-  field already exists, or ALTER TABLE ADD $column if field does not exist. \r
-<p>The class must be connected to the database for ChangeTableSQL to detect the \r
-  existance of the table. Idea and code contributed by Florian Buzin.\r
-<p><b>function CreateIndexSQL($idxname, $tabname, $flds, $idxoptarray=false)</b> \r
-<p>\r
-       RETURNS:                an array of strings, the sql to be executed, or false\r
-       <pre>\r
-       $idxname:               name of index\r
-       $tabname:               name of table\r
-       $flds:                  list of fields as a comma delimited string or an array of strings\r
-       $idxoptarray:   array of index creation options\r
-       </pre>\r
-<p>    $idxoptarray is similar to $taboptarray in that index specific information can\r
-       be embedded in the array. Other options include:\r
-       <pre>\r
-       CLUSTERED               Create clustered index (only mssql)\r
-       BITMAP                  Create bitmap index (only oci8)\r
-       UNIQUE                  Make unique index\r
-       FULLTEXT                Make fulltext index (only mysql)\r
-       HASH                    Create hash index (only postgres)\r
-       DROP            Drop legacy index\r
-       </pre>  \r
-<p> <strong>function AddColumnSQL($tabname, $flds)</strong>\r
-<p>Add one or more columns. Not guaranteed to work under all situations.\r
-<p><strong>function AlterColumnSQL($tabname, $flds)</strong>\r
-<p>Warning, not all databases support this feature.\r
-<p> <strong>function DropColumnSQL($tabname, $flds)</strong>\r
-<p>Drop 1 or more columns.\r
-<p> <strong>function ExecuteSQLArray($sqlarray, $contOnError = true)</strong> \r
-<pre>\r
-       RETURNS:                0 if failed, 1 if executed all but with errors, 2 if executed successfully\r
-       $sqlarray:              an array of strings with sql code (no semicolon at the end of string)\r
-       $contOnError:   if true, then continue executing even if error occurs\r
-</pre> \r
-<p>Executes an array of SQL strings returned by CreateTableSQL or CreateIndexSQL.\r
-<hr><a name=xmlschema></a>\r
-<h2>XML Schema</h2>\r
-This is a class contributed by Richard Tango-Lowy that allows the user to quickly\r
- and easily build a database using the excellent \r
-ADODB database library and a simple XML formatted file.\r
-\r
-\r
-<H3>Quick Start</H3>\r
-<P>First, create an XML database schema. Let's call it "schema.xml:"</P><PRE>\r
-&lt;?xml version="1.0"?&gt;\r
-&lt;schema&gt;\r
-  &lt;table name="mytable"&gt;\r
-    &lt;field name="row1" type="I"&gt;\r
-      &lt;descr&gt;An integer row that's a primary key and autoincrements&lt;/descr&gt;\r
-      &lt;KEY/&gt;\r
-      &lt;AUTOINCREMENT/&gt;\r
-    &lt;/field&gt;\r
-    &lt;field name="row2" type="C" size="16"&gt;\r
-      &lt;descr&gt;A 16 character varchar row that can't be null&lt;/descr&gt;\r
-      &lt;NOTNULL/&gt;\r
-    &lt;/field&gt;\r
-  &lt;/table&gt;\r
-  &lt;index name="myindex" table="mytable"&gt;\r
-    &lt;col&gt;row1&lt;/col&gt;\r
-    &lt;col&gt;row2&lt;/col&gt;\r
-  &lt;/index&gt;\r
-  &lt;sql&gt;\r
-    &lt;descr&gt;SQL to be executed only on specific platforms&lt;/descr&gt;\r
-    &lt;query platform="postgres|postgres7"&gt;\r
-      insert into mytable ( row1, row2 ) values ( 12, 'stuff' )\r
-    &lt;/query&gt;\r
-    &lt;query platform="mysql"&gt;\r
-      insert into mytable ( row1, row2 ) values ( 12, 'different stuff' )\r
-    &lt;/query&gt;\r
-  &lt;/sql&gt;\r
-&lt;/schema&gt;\r
-</PRE><P>Create a new database using the appropriate tool for your platform.\r
-Executing the following PHP code will create the a <i>mytable</i> and <i>myindex</i>\r
-in the database and insert one row into <i>mytable</i> if the platform is postgres or mysql. </P><PRE>                         \r
-include_once('/path/to/adodb.inc.php');\r
-include_once('/path/to/adodb-xmlschema.inc.php');\r
-\r
-// To build the schema, start by creating a normal ADOdb connection:\r
-$db->NewADOConnection( 'mysql' );\r
-$db->Connect( ... );\r
-\r
-// Create the schema object and build the query array.\r
-$schema = <B>new adoSchema</B>( $db );\r
-\r
-// Optionally, set a prefix for newly-created tables. In this example\r
-// the prefix "myprefix_" will result in a table named "myprefix_tablename".\r
-//$schema-><B>setPrefix</B>( "myprefix_" );\r
-       \r
-// Build the SQL array\r
-$sql = $schema-><B>ParseSchema</B>( "schema.xml" );\r
-\r
-// Execute the SQL on the database\r
-$result = $schema-><B>ExecuteSchema</B>( $sql );\r
-\r
-// Finally, clean up after the XML parser\r
-// (PHP won't do this for you!)\r
-$schema-><B>Destroy</B>();\r
-\r
-</PRE>\r
-       \r
-<H3>XML Schema Format:</H3>\r
-<P>(See <a href="http://arscognita.com/xmlschema.dtd">ADOdb_schema.dtd</a> for the full specification)</P>\r
-<PRE>\r
-&lt;?xml version="1.0"?&gt;\r
-&lt;schema&gt;\r
-  &lt;table name="tablename" platform="platform1|platform2|..."&gt;\r
-    &lt;descr&gt;Optional description&lt;/descr&gt;\r
-    &lt;field name="fieldname" type="datadict_type" size="size"&gt;\r
-      &lt;KEY/&gt;\r
-      &lt;NOTNULL/&gt;\r
-      &lt;AUTOINCREMENT/&gt;\r
-      &lt;DEFAULT value="value"/&gt;\r
-    &lt;/field&gt;\r
-       ... <i>more fields</i>\r
-  &lt;/table&gt;\r
-  ... <i>more tables</i>\r
-  \r
-  &lt;index name="indexname" platform="platform1|platform2|..."&gt;\r
-    &lt;descr&gt;Optional description&lt;/descr&gt;\r
-    &lt;col&gt;fieldname&lt;/col&gt;\r
-    ... <i>more columns</i>\r
-  &lt;/index&gt;\r
-  ... <i>more indices</i>\r
-  \r
-  &lt;sql platform="platform1|platform2|..."&gt;\r
-    &lt;descr&gt;Optional description&lt;/descr&gt;\r
-    &lt;query platform="platform1|platform2|..."&gt;SQL query&lt;/query&gt;\r
-    ... <i>more queries</i>\r
-  &lt;/sql&gt;\r
-  ... <i>more SQL</i>\r
-  &lt;/schema&gt;\r
-</PRE>\r
-<HR>\r
-\r
-<address>If you have any questions or comments, please email them to me  at \r
-<a href="mailto:richtl#arscognita.com">richtl#arscognita.com</a>.</address>\r
-\r
-</body>\r
-</html>\r
+<html>
+  <head>
+    <title>ADODB Data Dictionary Manual</title>
+    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+    <style type="text/css">
+      body, td {
+        /*font-family: Arial, Helvetica, sans-serif;*/
+        font-size: 11pt;
+      }
+      pre {
+        font-size: 9pt;
+      }
+      .toplink {
+        font-size: 8pt;
+      }
+    </style>
+  </head>      
+  <body bgcolor="#FFFFFF">
+
+<h2>ADOdb Data Dictionary Library for PHP</h2>
+<p>V4.20 22 Feb 2004 (c) 2000-2004 John Lim (<a href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a>).<br> AXMLS (c) 2004 ars Cognita, Inc</p>
+<p><font size="1">This software is dual licensed using BSD-Style and LGPL. This means you can use it in compiled proprietary and commercial products.</font></p>
+<p>Useful ADOdb links:  <a href=http://php.weblogs.com/adodb?dd=1>Download</a> &nbsp; <a href=http://php.weblogs.com/adodb_manual?dd=1>Other Docs</a></p>
+
+<p>This documentation describes a PHP class library to automate the creation of tables, 
+  indexes and foreign key constraints portably for multiple databases. Richard Tango-Lowy and Dan Cech
+  have been kind enough to contribute <a href=#xmlschema>AXMLS</a>, an XML schema system for defining databases.</p>
+
+<p>Currently the following databases are supported:</p>
+<p>
+  <b>Well-tested:</b> PostgreSQL, MySQL, Oracle, MSSQL.<br />
+  <b>Beta-quality:</b> DB2, Informix, Sybase, Interbase, Firebird.<br />
+  <b>Alpha-quality:</b> MS Access (does not support DEFAULT values) and generic ODBC.
+</p>
+
+<h3>Example Usage</h3>
+<pre>
+  include_once('adodb.inc.php');
+  <font color="#006600"># First create a normal connection</font>
+  $db->NewADOConnection('mysql');
+  $db->Connect(...);
+
+  <font color="#006600"># Then create a data dictionary object, using this connection</font>
+  $dict = <strong>NewDataDictionary</strong>($db);
+
+  <font color="#006600"># We have a portable declarative data dictionary format in ADOdb, similar to SQL.
+  # Field types use 1 character codes, and fields are separated by commas.
+  # The following example creates three fields: "col1", "col2" and "col3":</font>
+  $flds = " 
+  <font color="#663300"><strong> col1 C(32) NOTNULL DEFAULT 'abc',
+   col2 I  DEFAULT 0,
+   col3 N(12.2)</strong></font>
+  ";
+
+  <font color="#006600"># We demonstrate creating tables and indexes</font>
+  $sqlarray = $dict-><strong>CreateTableSQL</strong>($tabname, $flds, $taboptarray);
+  $dict-><strong>ExecuteSQLArray</strong>($sqlarray);<br>
+  $idxflds = 'co11, col2';
+  $sqlarray = $dict-><strong>CreateIndexSQL</strong>($idxname, $tabname, $idxflds);
+  $dict-><strong>ExecuteSQLArray</strong>($sqlarray);
+</pre>
+
+<h3>Functions</h3>
+
+<h4>function CreateDatabase($dbname, $optionsarray=false)</h4>
+<p>Create a database with the name $dbname;</p>
+
+<h4>function CreateTableSQL($tabname, $fldarray, $taboptarray=false)</h4>
+<pre>
+  RETURNS:      an array of strings, the sql to be executed, or false
+  $tabname:     name of table
+  $fldarray:    string (or array) containing field info
+  $taboptarray: array containing table options
+</pre>
+<p>The new format of $fldarray uses a free text format, where each field is comma-delimited.
+The first token for each field is the field name, followed by the type and optional
+field size. Then optional keywords in $otheroptions:</p>
+<pre>  "$fieldname $type $colsize $otheroptions"</pre>
+<p>The older (and still supported) format of $fldarray is a 2-dimensional array, where each row in the 1st dimension represents one field. Each row has this format:</p>
+<pre>  array($fieldname, $type, [,$colsize] [,$otheroptions]*)</pre>
+
+<p>The first 2 fields must be the field name and the field type. The field type can be a portable type codes or the actual type for that database.</p>
+<p>Legal portable type codes include:</p>
+<pre>
+  C:  varchar
+  X:  Largest varchar size 
+  XL: For Oracle, returns CLOB, otherwise same as 'X' above
+
+  C2: Multibyte varchar
+  X2: Multibyte varchar (largest size)
+
+  B:  BLOB (binary large object)
+
+  D:  Date (some databases do not support this, and we return a datetime type)
+  T:  Datetime or Timestamp
+  L:  Integer field suitable for storing booleans (0 or 1)
+  I:  Integer (mapped to I4)
+  I1: 1-byte integer
+  I2: 2-byte integer
+  I4: 4-byte integer
+  I8: 8-byte integer
+  F:  Floating point number
+  N:  Numeric or decimal number
+</pre>
+<p>The $colsize field represents the size of the field. If a decimal number is used, then it is assumed that the number following the dot is the precision, so 6.2 means a number of size 6 digits and 2 decimal places. It is recommended that the default for number types be represented as a string to avoid any rounding errors.</p>
+<p>The $otheroptions include the following keywords (case-insensitive):</p>
+<pre>
+  AUTO            For autoincrement number. Emulated with triggers if not available.
+                  Sets NOTNULL also.
+  AUTOINCREMENT   Same as auto.
+  KEY             Primary key field. Sets NOTNULL also. Compound keys are supported.
+  PRIMARY         Same as KEY.
+  DEF             Synonym for DEFAULT for lazy typists.
+  DEFAULT         The default value. Character strings are auto-quoted unless
+                  the string begins and ends with spaces, eg ' SYSDATE '.
+  NOTNULL         If field is not null.
+  DEFDATE         Set default value to call function to get today's date.
+  DEFTIMESTAMP    Set default to call function to get today's datetime.
+  NOQUOTE         Prevents autoquoting of default string values.
+  CONSTRAINTS     Additional constraints defined at the end of the field
+                  definition.
+</pre>
+<p>The Data Dictonary accepts two formats, the older array specification:</p>
+<pre>
+  $flds = array(
+    array('COLNAME',   'DECIMAL', '8.4', 'DEFAULT' => 0, 'NOTNULL'),
+    array('id',        'I'      , 'AUTO'),
+    array('`MY DATE`', 'D'      , 'DEFDATE'),
+    array('NAME',      'C'      , '32', 'CONSTRAINTS' => 'FOREIGN KEY REFERENCES reftable')
+  );
+</pre>
+<p>Or the simpler declarative format:</p>
+<pre>
+  $flds = "<font color="#660000"><strong>
+    COLNAME DECIMAL(8.4) DEFAULT 0 NOTNULL,
+    id I AUTO,
+    `MY DATE` D DEFDATE,
+    NAME C(32) CONSTRAINTS 'FOREIGN KEY REFERENCES reftable'</strong></font>
+  ";
+</pre>
+<p>Note that if you have special characters in the field name (e.g. My Date), you should enclose it in back-quotes. Normally field names are not case-sensitive, but if you enclose it in back-quotes, some databases treat the names as case-sensitive, and some don't. So be careful.</p>
+
+<p>The $taboptarray is the 3rd parameter of the CreateTableSQL function. This contains table specific settings. Legal keywords include:</p>
+<ul>
+  <li><b>REPLACE</b><br />
+    Indicates that the previous table definition should be removed (dropped)together with ALL data. See first example below.
+  </li>
+  <li><b>DROP</b><br />
+    Drop table. Useful for removing unused tables.
+  </li>
+  <li><b>CONSTRAINTS</b><br />
+    Define this as the key, with the constraint as the value. See the postgresql example below.
+    Additional constraints defined for the whole table. You will probably need to prefix this with a comma.
+  </li>
+</ul>
+
+<p>Database specific table options can be defined also using the name of the database type as the array key. In the following example, <em>create the table as ISAM with MySQL, and store the table in the &quot;users&quot; tablespace if using Oracle</em>. And because we specified REPLACE, drop the table first.</p>
+<pre>  $taboptarray = array('mysql' => 'TYPE=ISAM', 'oci8' => 'tablespace users', 'REPLACE');</pre>
+
+<p>You can also define foreignkey constraints. The following is syntax for postgresql:
+<pre>  $taboptarray = array('constraints' => ', FOREIGN KEY (col1) REFERENCES reftable (refcol)');</pre>
+
+<h4>function DropTableSQL($tabname)</h4>
+<p>Returns the SQL to drop the specified table.</p>
+
+<h4>function ChangeTableSQL($tabname, $flds)</h4>
+<p>Checks to see if table exists, if table does not exist, behaves like CreateTableSQL. 
+  If table exists, generates appropriate ALTER TABLE MODIFY COLUMN commands if 
+  field already exists, or ALTER TABLE ADD $column if field does not exist.</p>
+<p>The class must be connected to the database for ChangeTableSQL to detect the 
+  existence of the table. Idea and code contributed by Florian Buzin.</p>
+
+<h4>function CreateIndexSQL($idxname, $tabname, $flds, $idxoptarray=false)</h4>
+<pre>
+  RETURNS:      an array of strings, the sql to be executed, or false
+  $idxname:     name of index
+  $tabname:     name of table
+  $flds:        list of fields as a comma delimited string or an array of strings
+  $idxoptarray: array of index creation options
+</pre>
+<p>$idxoptarray is similar to $taboptarray in that index specific information can be embedded in the array. Other options include:</p>
+<pre>
+  CLUSTERED     Create clustered index (only mssql)
+  BITMAP        Create bitmap index (only oci8)
+  UNIQUE        Make unique index
+  FULLTEXT      Make fulltext index (only mysql)
+  HASH          Create hash index (only postgres)
+  DROP          Drop legacy index
+</pre>
+
+<h4>function DropIndexSQL ($idxname, $tabname = NULL)</h4>
+<p>Returns the SQL to drop the specified index.</p>
+
+<h4>function AddColumnSQL($tabname, $flds)</h4>
+<p>Add one or more columns. Not guaranteed to work under all situations.</p>
+
+<h4>function AlterColumnSQL($tabname, $flds)</h4>
+<p>Warning, not all databases support this feature.</p>
+
+<h4>function DropColumnSQL($tabname, $flds)</h4>
+<p>Drop 1 or more columns.</p>
+
+<h4>function SetSchema($schema)</h4>
+<p>Set the schema.</p>
+
+<h4>function &amp;MetaTables()</h4>
+<h4>function &amp;MetaColumns($tab, $upper=true, $schema=false)</h4>
+<h4>function &amp;MetaPrimaryKeys($tab,$owner=false,$intkey=false)</h4>
+<h4>function &amp;MetaIndexes($table, $primary = false, $owner = false)</h4>
+<p>These functions are wrappers for the corresponding functions in the connection object.  However, the table names will be autoquoted by the TableName function (see below) before being passed to the connection object.</p>
+
+<h4>function NameQuote($name = NULL)</h4>
+<p>If the provided name is quoted with backquotes (`) or contains special characters, returns the name quoted with the appropriate quote character, otherwise the name is returned unchanged.</p>
+
+<h4>function TableName($name)</h4>
+<p>The same as NameQuote, but will prepend the current schema if specified</p>
+
+<h4>function MetaType($t,$len=-1,$fieldobj=false)</h4>
+<h4>function ActualType($meta)</h4>
+<p>Convert between database-independent 'Meta' and database-specific 'Actual' type codes.</p>
+
+<h4>function ExecuteSQLArray($sqlarray, $contOnError = true)</h4>
+<pre>
+  RETURNS:      0 if failed, 1 if executed all but with errors, 2 if executed successfully
+  $sqlarray:    an array of strings with sql code (no semicolon at the end of string)
+  $contOnError: if true, then continue executing even if error occurs
+</pre>
+<p>Executes an array of SQL strings returned by CreateTableSQL or CreateIndexSQL.</p>
+
+<hr />
+
+<a name=xmlschema></a>
+<h2>ADOdb XML Schema (AXMLS)</h2>
+<p>This is a class contributed by Richard Tango-Lowy and Dan Cech that allows the user to quickly
+and easily build a database using the excellent ADODB database library and a simple XML formatted file.
+You can <a href=http://sourceforge.net/projects/adodb-xmlschema/>download the latest version of AXMLS here</a>.</p>
+
+<h3>Quick Start</h3>
+<p>First, create an XML database schema. Let's call it "schema.xml:"</p>
+<pre>
+  &lt;?xml version="1.0"?&gt;
+  &lt;schema version=&quot;0.2&quot;&gt;
+    &lt;table name="mytable"&gt;
+      &lt;field name="row1" type="I"&gt;
+        &lt;descr&gt;An integer row that's a primary key and autoincrements&lt;/descr&gt;
+        &lt;KEY/&gt;
+        &lt;AUTOINCREMENT/&gt;
+      &lt;/field&gt;
+      &lt;field name="row2" type="C" size="16"&gt;
+        &lt;descr&gt;A 16 character varchar row that can't be null&lt;/descr&gt;
+        &lt;NOTNULL/&gt;
+      &lt;/field&gt;
+      &lt;index name=&quot;myindex&quot;&gt;
+        &lt;col&gt;row1&lt;/col&gt;
+        &lt;col&gt;row2&lt;/col&gt;
+      &lt;/index&gt;
+    &lt;/table&gt;
+    &lt;sql&gt;
+      &lt;descr&gt;SQL to be executed only on specific platforms&lt;/descr&gt;
+      &lt;query platform="postgres|postgres7"&gt;
+        insert into mytable ( row1, row2 ) values ( 12, 'stuff' )
+      &lt;/query&gt;
+      &lt;query platform="mysql"&gt;
+        insert into mytable ( row1, row2 ) values ( 12, 'different stuff' )
+      &lt;/query&gt;
+    &lt;/sql&gt;
+  &lt;/schema&gt;
+</pre>
+
+<p>Create a new database using the appropriate tool for your platform.<br />
+Executing the following PHP code will create the a <i>mytable</i> and <i>myindex</i>
+in the database and insert one row into <i>mytable</i> if the platform is postgres or mysql.</p>
+
+<pre>
+  include_once('/path/to/adodb.inc.php');
+  include_once('/path/to/adodb-xmlschema.inc.php');
+
+  <font color="#006600">// To build the schema, start by creating a normal ADOdb connection:</font>
+  $db->NewADOConnection( 'mysql' );
+  $db->Connect( ... );
+
+  <font color="#006600">// Create the schema object and build the query array.</font>
+  $schema = new <b>adoSchema</b>( $db );
+
+  <font color="#006600">// Optionally, set a prefix for newly-created tables. In this example
+  // the prefix "myprefix_" will result in a table named "myprefix_tablename".</font>
+  $schema-><b>SetPrefix</b>( 'myprefix_' );
+
+  <font color="#006600">// Build the SQL array</font>
+  $schema-><b>ParseSchema</b>( 'schema.xml' );
+
+  <font color="#006600">// Execute the SQL on the database</font>
+  $result = $schema-><b>ExecuteSchema</b>();
+
+  <font color="#006600">// Finally, clean up after the XML parser
+  // (PHP won't do this for you!)</font>
+  $schema-><b>Destroy</b>();
+</pre>
+
+
+<h3>Using AXMLS in Your 
+                       Application</h3>
+       
+       <p>
+There are two steps involved in using 
+                               AXMLS in your application: first, 
+                               you must create a schema, or XML representation of your 
+                               database, and second, you must create the PHP code that will 
+                               parse and execute the schema.</p>
+               <p>Let's begin with a schema that describes a typical, if simplistic 
+                       user management table for an application.</p>
+               <pre class="listing"><pre>
+&lt;?xml version=&quot;1.0&quot;?&gt;
+&lt;schema version=&quot;0.2&quot;&gt;
+
+  &lt;table name=&quot;users&quot;&gt;
+    &lt;desc&gt;A typical users table for our application.&lt;/desc&gt;
+    &lt;field name=&quot;userId&quot; type=&quot;I&quot;&gt;
+      &lt;descr&gt;A unique ID assigned to each user.&lt;/descr&gt;
+      &lt;KEY/&gt;
+      &lt;AUTOINCREMENT/&gt;
+    &lt;/field&gt;
+    
+    &lt;field name=&quot;userName&quot; type=&quot;C&quot; size=&quot;16&quot;&gt;&lt;NOTNULL/&gt;&lt;/field&gt;
+    
+    &lt;index name=&quot;userName&quot;&gt;
+      &lt;descr&gt;Put a unique index on the user name&lt;/descr&gt;
+      &lt;col&gt;userName&lt;/col&gt;
+      &lt;UNIQUE/&gt;
+    &lt;/index&gt;
+  &lt;/table&gt;
+  
+  &lt;sql&gt;
+    &lt;descr&gt;Insert some data into the users table.&lt;/descr&gt;
+    &lt;query&gt;insert into users (userName) values ( 'admin' )&lt;/query&gt;
+    &lt;query&gt;insert into users (userName) values ( 'Joe' )&lt;/query&gt;
+  &lt;/sql&gt;
+&lt;/schema&gt;                        
+</pre></pre>
+               <p>Let's take a detailed look at this schema.</p>
+               <p>The opening &lt;?xml version=&quot;1.0&quot;?&gt; tag is 
+                                       required by XML. The &lt;schema&gt; tag 
+                                       tells the parser that the enclosed markup defines an XML 
+                                       schema. The version=&quot;0.2&quot; attribute sets 
+                                       <em>the version of the AXMLS DTD used by the XML 
+                                       schema.</em> <p>All versions of AXMLS prior 
+                                       to version 1.0 have a schema version of &quot;0.1&quot;. The current 
+                                       schema version is &quot;0.2&quot;.</p></p>
+                               <pre class="listing"><pre>
+&lt;?xml version=&quot;1.0&quot;?&gt;
+&lt;schema version=&quot;0.2&quot;&gt;
+  ...
+&lt;/schema&gt;
+</pre></pre>
+                       <p>Next we define one or more tables. A table consists of a 
+                                       fields (and other objects) enclosed by 
+                                       &lt;table&gt; tags. The 
+                                       name=&quot;&quot; attribute specifies the name of 
+                                       the table that will be created in the database.</p>
+                               <pre class="listing"><pre>
+&lt;table name=&quot;users&quot;&gt;
+
+    &lt;desc&gt;A typical users table for our application.&lt;/desc&gt;
+    &lt;field name=&quot;userId&quot; type=&quot;I&quot;&gt;
+      &lt;descr&gt;A unique ID assigned to each user.&lt;/descr&gt;
+      &lt;KEY/&gt;
+      &lt;AUTOINCREMENT/&gt;
+    &lt;/field&gt;
+    
+    &lt;field name=&quot;userName&quot; type=&quot;C&quot; size=&quot;16&quot;&gt;&lt;NOTNULL/&gt;&lt;/field&gt;
+    
+&lt;/table&gt;
+</pre></pre>
+                               <p>This table is called &quot;users&quot; and has a description and 
+                                       two fields. The description is optional, and is currently 
+                                       only for your own information; it is not applied to the 
+                                       database.</p>
+                               <p>The first &lt;field&gt; tag will create 
+                                       a field named &quot;userId&quot; of type &quot;I&quot;, or integer. (See the 
+                                       ADOdb Data Dictionary 
+                                       documentation for a list of valid types.) This 
+                                       &lt;field&gt; tag encloses two special 
+                                       field options: &lt;KEY/&gt;, which 
+                                       specifies this field as a primary key, and 
+                                       &lt;AUTOINCREMENT/&gt;, which specifies 
+                                       that the database engine should automatically fill this 
+                                       field with the next available value when a new row is 
+                                       inserted.</p>
+                               <p>The second &lt;field&gt; tag will create 
+                                       a field named &quot;userName&quot; of type &quot;C&quot;, or character, and of 
+                                       length 16 characters. The &lt;NOTNULL/&gt; 
+                                       option specifies that this field does not allow 
+                                       NULLs.</p>
+                       <p>There are two ways to add indexes to a table. The 
+                                       simplest is to mark a field with the 
+                                       &lt;KEY/&gt; option as described above; a 
+                                       primary key is a unique index. The second and more powerful 
+                                       method uses the &lt;index&gt; tags.</p>
+                               <pre class="listing"><pre>
+&lt;table name=&quot;users&quot;&gt;
+  ...
+    
+  &lt;index name=&quot;userName&quot;&gt;
+    &lt;descr&gt;Put a unique index on the user name&lt;/descr&gt;
+    &lt;col&gt;userName&lt;/col&gt;
+    &lt;UNIQUE/&gt;
+  &lt;/index&gt;
+    
+&lt;/table&gt;
+</pre></pre>
+                               <p>The &lt;index&gt; tag specifies that an 
+                                       index should be created on the enclosing table. The 
+                                       name=&quot;&quot; attribute provides the name of the 
+                                       index that will be created in the database. The 
+                                       description, as above, is for your information only. The 
+                                       &lt;col&gt; tags list each column that 
+                                       will be included in the index. Finally, the 
+                                       &lt;UNIQUE/&gt; tag specifies that this 
+                                       will be created as a unique index.</p>
+                       <p>Finally, AXMLS allows you to include arbitrary SQL that 
+                                       will be applied to the database when the schema is 
+                                       executed.</p>
+                               <pre class="listing"><pre>
+&lt;sql&gt;
+  &lt;descr&gt;Insert some data into the users table.&lt;/descr&gt;
+  &lt;query&gt;insert into users (userName) values ( 'admin' )&lt;/query&gt;
+  &lt;query&gt;insert into users (userName) values ( 'Joe' )&lt;/query&gt;
+&lt;/sql&gt;
+</pre></pre>
+                               <p>The &lt;sql&gt; tag encloses any number 
+                                       of SQL queries that you define for your own use.</p>
+               <p>Now that we've defined an XML schema, you need to know how to 
+                       apply it to your database. Here's a simple PHP script that shows 
+                       how to load the schema.</p>
+               <p><pre class="listing"><pre>
+&lt;?PHP
+/* You must tell the script where to find the ADOdb and
+ * the AXMLS libraries.
+ */
+require( &quot;path_to_adodb/adodb.inc.php&quot;);
+require( &quot;path_to_adodb/adodb-xmlschema.inc.php&quot; );
+
+/* Configuration information. Define the schema filename,
+ * RDBMS platform (see the ADODB documentation for valid
+ * platform names), and database connection information here.
+ */
+$schemaFile = 'example.xml';
+$platform = 'mysql';
+$dbHost = 'localhost';
+$dbName = 'database';
+$dbUser = 'username';
+$dbPassword = 'password';
+
+/* Start by creating a normal ADODB connection.
+ */
+$db = ADONewConnection( $platform );
+$db-&gt;Connect( $dbHost, $dbUser, $dbPassword, $dbName );
+
+/* Use the database connection to create a new adoSchema object.
+ */
+$schema = new adoSchema( $db );
+
+/* Call ParseSchema() to build SQL from the XML schema file.
+ * Then call ExecuteSchema() to apply the resulting SQL to 
+ * the database.
+ */
+$sql = $schema-&gt;ParseSchema( $schemaFile );
+$result = $schema-&gt;ExecuteSchema();
+?&gt;
+</pre></pre></p>
+               <p>Let's look at each part of the example in turn. After you 
+                       manually create the database, there are three steps required to 
+                       load (or upgrade) your schema.</p>
+               <p>First, create a normal ADOdb connection. The variables 
+                                       and values here should be those required to connect to your 
+                                       database.</p>
+                               <pre class="listing"><pre>
+$db = ADONewConnection( 'mysql' );
+$db-&gt;Connect( 'host', 'user', 'password', 'database' );
+</pre></pre>
+                       <p>Second, create the adoSchema object that load and 
+                                       manipulate your schema. You must pass an ADOdb database 
+                                       connection object in order to create the adoSchema 
+                                       object.</p>
+                               <pre class="listing"><pre>
+$schema = new adoSchema( $db );
+</pre></pre>
+                       <p>Third, call ParseSchema() to parse the 
+                                       schema and then ExecuteSchema() to apply 
+                                       it to the database. You must pass 
+                                       ParseSchema() the path and filename of 
+                                       your schema file.</p>
+                               <pre class="listing"><pre>
+$schema-&gt;ParseSchema( $schemaFile ); 
+$schema-&gt;ExecuteSchema(); 
+</pre></pre>
+               <p>Execute the above code and then log into your database. If you've 
+                       done all this right, you should see your tables, indexes, and 
+                       SQL.</p>
+               <p>You can find the source files for this tutorial in the 
+                       examples directory as 
+                       tutorial_shema.xml and 
+                       tutorial.php. See the class documentation for 
+                       a more detailed description of the adoSchema methods, including 
+                       methods and schema elements that are not described in this 
+                       tutorial.</p>
+
+<H3>XML Schema Format:</H3>
+<P>(See <a href="xmlschema.dtd">xmlschema.dtd</a> for the full specification)</P>
+<PRE>
+  &lt;?xml version="1.0"?&gt;
+  &lt;schema version=&quot;0.2&quot;&gt;
+    &lt;table name="tablename" platform="platform1|platform2|..."&gt;
+      &lt;descr&gt;Optional description&lt;/descr&gt;
+      &lt;field name="fieldname" type="datadict_type" size="size"&gt;
+        &lt;KEY/&gt;
+        &lt;NOTNULL/&gt;
+        &lt;AUTOINCREMENT/&gt;
+        &lt;DEFAULT value="value"/&gt;
+      &lt;/field&gt;
+      <i> ... more fields</i>
+      &lt;index name="indexname" platform="platform1|platform2|..."&gt;
+        &lt;descr&gt;Optional description&lt;/descr&gt;
+        &lt;col&gt;fieldname&lt;/col&gt;
+        <i> ... more columns</i>
+      &lt;/index&gt;
+      <i> ... more indexes</i>
+    &lt;/table&gt;
+    <i> ... more tables</i>
+
+    &lt;sql platform="platform1|platform2|..."&gt;
+      &lt;descr&gt;Optional description&lt;/descr&gt;
+      &lt;query platform="platform1|platform2|..."&gt;SQL query&lt;/query&gt;
+      <i> ... more queries</i>
+    &lt;/sql&gt;
+    <i> ... more SQL</i>
+  &lt;/schema&gt;
+</pre>
+
+<h3>Upgrading</h3>
+If your schema version is older, than XSLT is used to transform the schema to the newest version. 
+This means that if you are using an older XML schema format,  you need to have the XSLT extension installed.
+If you do not want to require your users to have the XSLT extension installed, make sure you 
+modify your XML schema to conform to the latest version.
+<hr />
+
+<address>If you have any questions or comments, please email them to Richard at richtl#arscognita.com.
+</address>
+
+</body>
+</html>
\ No newline at end of file
index bfcaa774338b696328c017be93062adf5a35370c..a7883cdb67998e0e94135601c5db933f8db0cbc8 100644 (file)
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\r
-\r
-<html>\r
-<head>\r
-       <title>ADOdb Performance Monitoring Library</title>\r
-</head>\r
-\r
-<body>\r
-<h3>The ADOdb Performance Monitoring Library</h3>\r
-<p>V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my)</p>\r
-<p><font size="1">This software is dual licensed using BSD-Style and LGPL. This \r
-  means you can use it in compiled proprietary and commercial products.</font></p>\r
-  <p>Useful ADOdb links:  <a href=http://php.weblogs.com/adodb?perf=1>Download</a> &nbsp; <a href=http://php.weblogs.com/adodb_manual?perf=1>Other Docs</a>\r
-<h3>Introduction</h3>\r
-<p>This module, part of the ADOdb package, provides both CLI and HTML interfaces \r
-  for viewing key performance indicators of your database. This is very useful \r
-  because web apps such as the popular phpMyAdmin currently do not provide effective \r
-  database health monitoring tools. The module provides the following: \r
-<ul>\r
-  <li>A quick health check of your database server using <code>$perf->HealthCheck()</code> \r
-    or <code>$perf->HealthCheckCLI()</code>. \r
-  <li>User interface for performance monitoring, <code>$perf-&gt;UI()</code>. \r
-    This UI displays: \r
-    <ul>\r
-      <li>the health check, </li>\r
-      <li>all SQL logged and their query plans, </li>\r
-      <li>a list of all tables in the current database</li>\r
-      <li>an interface to continiously poll the server for key performance indicators \r
-        such as CPU, Hit Ratio, Disk I/O</li>\r
-    </ul>\r
-  <li>Gives you an API to build database monitoring tools for a server farm, for \r
-    example calling <code>$perf->DBParameter('data cache hit ratio')</code> returns \r
-    this very important statistic in a database independant manner. \r
-</ul>\r
-<p>ADOdb also has the ability to log all SQL executed, using <a href=docs-adodb.htm#logsql>LogSQL</a>. \r
-  All SQL logged can be analyzed through the performance monitor <a href=#ui>UI</a>. \r
-  In the <i>View SQL</i> mode, we categorize the SQL into 3 types:\r
-<ul>\r
-  <li><b>Suspicious SQL</b>: queries with high average execution times, and are potential \r
-    candidates for rewriting</li>\r
-  <li><b>Expensive SQL</b>: queries with high total execution times (#executions * avg \r
-    execution time). Optimizing these queries will reduce your database server \r
-    load.</li>\r
-  <li><b>Invalid SQL</b>: queries that generate errors.</li>\r
-</ul>\r
-<p>Each query is hyperlinked to a description of the query plan, and every PHP \r
-  script that executed that query is also shown.</p>\r
-<p>Please note that the information presented is a very basic database health \r
-  check, and does not provide a complete overview of database performance. Although \r
-  some attempt has been made to make it work across multiple databases in the \r
-  same way, it is impossible to do so. For the health check, we do try to display \r
-  the following key database parameters for all drivers:</p>\r
-<ul>\r
-  <li><b>data cache size</b> - The amount of memory allocated to the cache.</li>\r
-  <li><b>data cache hit ratio</b> - A measure of how effective the cache is, as a percentage. \r
-  The higher, the better.</li>\r
-  <li><b>current connections</b> - The number of sessions currently connected to the \r
-    database. </li>\r
-</ul>\r
-<p>You will need to connect to the database as an administrator to view most of \r
-  the parameters. </p>\r
-<p>Code improvements as very welcome, particularly adding new database parameters \r
-  and automated tuning hints.</p><a name=usage></a>\r
-<h3>Usage</h3>\r
-<p>Currently, the following drivers: <em>mysql</em>, <em>postgres</em>, <em>oci8</em>, \r
-  <em>mssql</em>, <i>informix</i> and <em>db2</em> are supported. To create a \r
-  new performance monitor, call NewPerfMonitor( ) as demonstrated below: </p>\r
-<pre>\r
-&lt;?php\r
-include_once('adodb.inc.php');\r
-session_start(); <font color="#006600"># session variables required for monitoring</font>\r
-$conn = ADONewConnection($driver);\r
-$conn-&gt;Connect($server,$user,$pwd,$db);\r
-$perf =&amp; NewPerfMonitor($conn);\r
-$perf-&gt;UI($pollsecs=5);<font color="#006600"></font>\r
-?>\r
-</pre>\r
-<p>It is also possible to retrieve a single database parameter:</p>\r
-<pre>$size = $perf->DBParameter('data cache size');\r
-</pre>\r
-<p>\r
-Thx to Fernando Ortiz for the informix module. \r
-<h3>Methods</h3><a name=ui></a>\r
-<p><font face="Courier New, Courier, mono">function <b>UI($pollsecs=5)</b></font></p>\r
-<p>Creates a web-based user interface for performance monitoring. When you click on Poll, \r
-server statistics will be displayed every $pollsecs seconds.  See <a href="#usage">Usage</a> \r
-  above. Sample output follows below:</p>\r
-\r
-<table border=1 width=100% bgcolor=lightyellow><tr>\r
-    <td> <b><a href=http://php.weblogs.com/adodb?perf=1>ADOdb</a> Performance \r
-      Monitor</b> for localhost, db=test<br>\r
-      <font size=-1>PostgreSQL 7.3.2 on i686-pc-cygwin, compiled by GCC gcc (GCC) \r
-      3.2 20020927 (prerelease)</font></tr>\r
-         <tr><td>\r
-       <a href=#>Performance Stats</a> &nbsp; <a href=#>View SQL</a>\r
-        &nbsp; <a href=#>View Tables</a> &nbsp; <a href=#>Poll Stats</a></tr></table><table border=1 bgcolor=white><tr><td colspan=3><h3>postgres7</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>statistics collector</td><td>TRUE</td><td>Value must be TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i> and <i>stats_block_level</i> must be set to true in postgresql.conf)</td></tr>\r
-<tr><td>data cache hit ratio</td><td>99.7967555299239</td><td>&nbsp;</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data reads</td><td>125</td><td>&nbsp;  </td></tr>\r
-<tr><td>data writes</td><td>21.78125000000000000</td><td>Count of inserts/updates/deletes * coef</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Data Cache</i> &nbsp;</td></tr><tr><td>data cache buffers</td><td>640</td><td>Number of cache buffers. <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic>Tuning</a></td></tr>\r
-<tr><td>cache blocksize</td><td>8192</td><td>(estimate)</td></tr>\r
-<tr><td>data cache size</td><td>5M</td><td>&nbsp;</td></tr>\r
-<tr><td>operating system cache size</td><td>80M</td><td>(effective cache size)</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Memory Usage</i> &nbsp;</td></tr><tr><td>sort buffer size</td><td>1M</td><td>Size of sort buffer (per query)</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i> &nbsp;</td></tr><tr><td>current connections</td><td>0</td><td>&nbsp;</td></tr>\r
-<tr><td>max connections</td><td>32</td><td>&nbsp;</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Parameters</i> &nbsp;</td></tr><tr><td>rollback buffers</td><td>8</td><td>WAL buffers</td></tr>\r
-<tr><td>random page cost</td><td>4</td><td>Cost of doing a seek (default=4). See <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#less>random_page_cost</a></td></tr>\r
-</table>\r
-<p><font face="Courier New, Courier, mono">function <b>HealthCheck</b>()</font></p> \r
-<p>Returns database health check parameters as a HTML table. You will need to \r
-  echo or print the output of this function,</p>\r
-<p><font face="Courier New, Courier, mono">function <b>HealthCheckCLI</b>()</font></p>\r
-<p>Returns database health check parameters formatted for a command line interface. \r
-  You will need to echo or print the output of this function. Sample output for \r
-  mysql:</p>\r
-<pre>\r
--- Ratios -- \r
-          MyISAM cache hit ratio => 56.5635738832 \r
-          InnoDB cache hit ratio => 0 \r
-             sql cache hit ratio => 0 \r
- -- IO -- \r
-                      data reads => 2622 \r
-                     data writes => 2415.5 \r
- -- Data Cache -- \r
-          MyISAM data cache size => 512K \r
-             BDB data cache size => 8388600\r
-          InnoDB data cache size => 8M\r
- -- Memory Pools -- \r
-                read buffer size => 131072 \r
-                sort buffer size => 65528 \r
-                     table cache => 4 \r
- -- Connections -- \r
-             current connections => 3\r
-                 max connections => 100</pre>\r
-<p><font face="Courier New, Courier, mono">function <b>Poll</b>($pollSecs=5) \r
-  </font> \r
-<p> Run in infinite loop, displaying the following information every $pollSecs. \r
-  This will not work properly if output buffering is enabled. \r
-  In the example below, $pollSecs=3:\r
-<pre>\r
-Accumulating statistics...\r
- Time   WS-CPU%   Hit%   Sess        Reads/s          Writes/s\r
-11:08:30    0.7  56.56      1         0.0000            0.0000\r
-11:08:33    1.8  56.56      2         0.0000            0.0000\r
-11:08:36   11.1  56.55      3         2.5000            0.0000\r
-11:08:39    9.8  56.55      2         3.1121            0.0000\r
-11:08:42    2.8  56.55      1         0.0000            0.0000\r
-11:08:45    7.4  56.55      2         0.0000            1.5000\r
-</pre>\r
-<p><b>WS-CPU%</b> is the Web Server CPU load of the server that PHP is running \r
-  from (eg. the database client), and not the database. The <b>Hit%</b> is the \r
-  data cache hit ratio. <b>Sess</b> is the current number of sessions connected \r
-  to the database. If you are using persistent connections, this should not change \r
-  much. The <b>Reads/s</b> and <b>Writes/s</b> are synthetic values to give the \r
-  viewer a rough guide to I/O, and are not to be taken literally. \r
-<p><font face="Courier New, Courier, mono">function <b>SuspiciousSQL</b>($numsql=10)</font></p>\r
-<p>Returns SQL which have high average execution times as a HTML table. Each sql statement\r
-is hyperlinked to a new window which details the execution plan and the scripts that execute this SQL.\r
-<p> The number of statements returned is determined by $numsql. Data is taken from the adodb_logsql table, where the sql statements are logged when\r
-$connection->LogSQL(true) is enabled. The adodb_logsql table is populated using <a href=docs-adodb.htm#logsql>$conn->LogSQL</a>.\r
-<p>For Oracle, Ixora Suspicious SQL returns a list of SQL statements that are most cache intensive as a HTML table. \r
-  These are data intensive SQL statements that could benefit most from tuning. \r
\r
-<p><font face="Courier New, Courier, mono">function <b>ExpensiveSQL</b>($numsql=10)</font></p>\r
-<p>Returns SQL whose total execution time (avg time * #executions) is high as a HTML table. Each sql statement\r
-is hyperlinked to a new window which details the execution plan and the scripts that execute this SQL.\r
-<p> The number of statements returned is determined by $numsql. Data is taken from the adodb_logsql table, where the sql statements are logged when\r
-$connection->LogSQL(true) is enabled. The adodb_logsql table is populated using <a href=docs-adodb.htm#logsql>$conn->LogSQL</a>.\r
-\r
-<p>For Oracle, Ixora Expensive SQL returns a list of SQL statements that are taking the most CPU load \r
-when run.\r
-<p><font face="Courier New, Courier, mono">function <b>InvalidSQL</b>($numsql=10)</font></p>\r
-<p>Returns a list of invalid SQL as an HTML table.\r
-<p>Data is taken from the adodb_logsql table, where the sql statements are logged when\r
-$connection->LogSQL(true) is enabled.\r
-<p><font face="Courier New, Courier, mono">function <b>Tables</b>($orderby=1)</font></p>\r
-<p>Returns information on all tables in a database, with the first two fields \r
-  containing the table name and table size, the remaining fields depend on the \r
-  database driver. If $orderby is set to 1, it will sort by name. If $orderby \r
-  is set to 2, then it will sort by table size. Some database drivers (mssql and \r
-  mysql) will ignore the $orderby clause. For postgresql, the information is up-to-date \r
-  since the last <i>vacuum</i>. Not supported currently for db2.</p>\r
-<h3>Raw Functions</h3>\r
-<p>Raw functions return values without any formatting.</p>\r
-<p><font face="Courier New, Courier, mono">function <b>DBParameter</b>($paramname)</font></p>\r
-<p>Returns the value of a database parameter, such as $this-&gt;DBParameter(&quot;data \r
-  cache size&quot;).</p>\r
-<p><font face="Courier New, Courier, mono">function <b>CPULoad</b>()</font></p>\r
-<p>Returns the CPU load of the database client (NOT THE SERVER) as a percentage. \r
-  Only works for Linux and Windows. For Windows, WMI must be available.</p>\r
-<h3>Format of $settings Property</h3>\r
-<p> To create new database parameters, you need to understand $settings. The $settings \r
-  data structure is an associative array. Each element of the array defines a \r
-  database parameter. The key is the name of the database parameter. If no key is defined,\r
-  then it is assumed to be a section break, and the value is the name of the section break.\r
-  If this is too confusing, looking at the source code will help a lot!</p>\r
-<p> Each database parameter is itself an array consisting of the following elements:</p>\r
-<ol start="0">\r
-  <li> Category code, used to group related db parameters. If the category code is 'HIDE', then\r
-the database parameter is not shown when HTML() is called. <br>\r
-  </li>\r
-  <li> either \r
-    <ol type="a">\r
-      <li>sql string to retrieve value, eg. "select value from v\$parameter where \r
-        name='db_block_size'", </li>\r
-      <li>array holding sql string and field to look for, e.g. array('show variables','table_cache'); \r
-        optional 3rd parameter is the $rs-&gt;fields[$index] to use (otherwise \r
-        $index=1), and optional 4th parameter is a constant to multiply the result \r
-        with (typically 100 for percentage calculations),</li>\r
-      <li>a string prefixed by =, then a PHP method of the class is invoked, e.g. \r
-        to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue', \r
-        <br>\r
-      </li>\r
-    </ol>\r
-  </li>\r
-  <li> Description of database parameter. If description begins with an =, then \r
-    it is interpreted as a method call, just as in (1c) above, taking one parameter, \r
-    the current value. E.g. '=GetIndexDescription' will invoke $this->GetIndexDescription($val). \r
-    This is useful for generating tuning suggestions. For an example, see WarnCacheRatio().</li>\r
-</ol>\r
-<p>Example from MySQL, table_cache database parameter:</p>\r
-<pre>'table cache' =&gt; array('CACHE',            # category code\r
-   array(&quot;show variables&quot;, 'table_cache'), # array (type 1b)\r
-   'Number of tables to keep open'),       # description</pre>\r
-<h3>Example Health Check Output</h3>\r
-<p><a href="#db2">db2</a> <a href=#informix>informix</a> <a href="#mysql">mysql</a> <a href="#mssql">mssql</a> \r
-  <a href="#oci8">oci8</a> <a href="#postgres">postgres</a></p>\r
-<p><a name=db2></a></p>\r
-<table border=1 bgcolor=white>\r
-  <tr> \r
-    <td colspan=3> <h3>db2</h3></td>\r
-  </tr>\r
-  <tr> \r
-    <td><b>Parameter</b></td>\r
-    <td><b>Value</b></td>\r
-    <td><b>Description</b></td>\r
-  </tr>\r
-  <tr bgcolor=#F0F0F0> \r
-    <td colspan=3><i>Ratios</i> &nbsp;</td>\r
-  </tr>\r
-  <tr bgcolor=#FFFFFF> \r
-    <td>data cache hit ratio</td>\r
-    <td>0 &nbsp; </td>\r
-    <td>&nbsp;</td>\r
-  </tr>\r
-  <tr bgcolor=#F0F0F0>\r
-    <td colspan=3><i>Data Cache</i></td>\r
-  </tr>\r
-  <tr bgcolor=#FFFFFF> \r
-    <td>data cache buffers</td>\r
-    <td>250 &nbsp; </td>\r
-    <td>See <a href=http://www7b.boulder.ibm.com/dmdd/library/techarticle/anshum/0107anshum.html#bufferpoolsize>tuning \r
-      reference</a>.</td>\r
-  </tr>\r
-  <tr bgcolor=#FFFFFF> \r
-    <td>cache blocksize</td>\r
-    <td>4096 &nbsp; </td>\r
-    <td>&nbsp;</td>\r
-  </tr>\r
-  <tr bgcolor=#FFFFFF> \r
-    <td>data cache size</td>\r
-    <td>1000K &nbsp; </td>\r
-    <td>&nbsp;</td>\r
-  </tr>\r
-  <tr bgcolor=#F0F0F0> \r
-    <td colspan=3><i>Connections</i></td>\r
-  </tr>\r
-  <tr bgcolor=#FFFFFF> \r
-    <td>current connections</td>\r
-    <td>2 &nbsp; </td>\r
-    <td>&nbsp;</td>\r
-  </tr>\r
-</table>\r
-<p>&nbsp;<p>\r
-<a name=informix></a>\r
-<table border=1 bgcolor=white><tr><td\r
-colspan=3><h3>informix</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Val\r
-ue</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td\r
-colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>data cache hit\r
-ratio</td><td>95.89</td><td>&nbsp;</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data\r
-reads</td><td>1883884</td><td>Page reads</td></tr>\r
-<tr><td>data writes</td><td>1716724</td><td>Page writes</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i>\r
-&nbsp;</td></tr><tr><td>current connections</td><td>263.0</td><td>Number of\r
-sessions</td></tr>\r
-</table>\r
-\r
-\r
-<p>&nbsp;</p>\r
-<p><a name=mysql id="mysql"></a></p><table border=1 bgcolor=white><tr><td colspan=3><h3>mysql</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>MyISAM cache hit ratio</td><td>56.5658301822</td><td><font color=red><b>Cache ratio should be at least 90%</b></font></td></tr>\r
-<tr><td>InnoDB cache hit ratio</td><td>0</td><td><font color=red><b>Cache ratio should be at least 90%</b></font></td></tr>\r
-<tr><td>sql cache hit ratio</td><td>0</td><td>&nbsp;</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data reads</td><td>2622</td><td>Number of selects (Key_reads is not accurate)</td></tr>\r
-<tr><td>data writes</td><td>2415.5</td><td>Number of inserts/updates/deletes * coef (Key_writes is not accurate)</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Data Cache</i> &nbsp;</td></tr><tr><td>MyISAM data cache size</td><td>512K</td><td>&nbsp;</td></tr>\r
-<tr><td>BDB data cache size</td><td>8388600</td><td>&nbsp;</td></tr>\r
-<tr><td>InnoDB data cache size</td><td>8M</td><td>&nbsp;</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Memory Pools</i> &nbsp;</td></tr><tr><td>read buffer size</td><td>131072</td><td>(per session)</td></tr>\r
-<tr><td>sort buffer size</td><td>65528</td><td>Size of sort buffer (per session)</td></tr>\r
-<tr><td>table cache</td><td>4</td><td>Number of tables to keep open</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i> &nbsp;</td></tr><tr><td>current connections</td><td>3</td><td>&nbsp;</td></tr>\r
-<tr><td>max connections</td><td>100</td><td>&nbsp;</td></tr>\r
-</table>\r
-<p>&nbsp;</p>\r
-<p><a name=mssql id="mssql"></a></p>\r
-\r
-<table border=1 bgcolor=white><tr><td colspan=3><h3>mssql</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>data cache hit ratio</td><td>99.9999694824</td><td>&nbsp;</td></tr>\r
-<tr><td>prepared sql hit ratio</td><td>99.7738579828</td><td>&nbsp;</td></tr>\r
-<tr><td>adhoc sql hit ratio</td><td>98.4540169133</td><td>&nbsp;</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data reads</td><td>2858</td><td>&nbsp;  </td></tr>\r
-<tr><td>data writes</td><td>1438</td><td>&nbsp;  </td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Data Cache</i> &nbsp;</td></tr><tr><td>data cache size</td><td>4362</td><td>in K</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i> &nbsp;</td></tr><tr><td>current connections</td><td>14</td><td>&nbsp;</td></tr>\r
-<tr><td>max connections</td><td>32767</td><td>&nbsp;</td></tr>\r
-</table>\r
-\r
-<p>&nbsp;</p>\r
-<p><a name=oci8 id="oci8"></a></p>\r
-<table border=1 bgcolor=white><tr><td colspan=3><h3>oci8</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>data cache hit ratio</td><td>96.98</td><td>&nbsp;</td></tr>\r
-<tr><td>sql cache hit ratio</td><td>99.96</td><td>&nbsp;</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data reads</td><td>842938</td><td>&nbsp;  </td></tr>\r
-<tr><td>data writes</td><td>16852</td><td>&nbsp;  </td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Data Cache</i> &nbsp;</td></tr><tr><td>data cache buffers</td><td>3072</td><td>Number of cache buffers</td></tr>\r
-<tr><td>data cache blocksize</td><td>8192</td><td>&nbsp;</td></tr>\r
-<tr><td>data cache size</td><td>48M</td><td>shared_pool_size</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Memory Pools</i> &nbsp;</td></tr><tr><td>java pool size</td><td>0</td><td>java_pool_size</td></tr>\r
-<tr><td>sort buffer size</td><td>512K</td><td>sort_area_size (per query)</td></tr>\r
-<tr><td>user session buffer size</td><td>8M</td><td>large_pool_size</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i> &nbsp;</td></tr><tr><td>current connections</td><td>1</td><td>&nbsp;</td></tr>\r
-<tr><td>max connections</td><td>170</td><td>&nbsp;</td></tr>\r
-<tr><td>data cache utilization ratio</td><td>88.46</td><td>Percentage of data cache actually in use</td></tr>\r
-<tr><td>user cache utilization ratio</td><td>91.76</td><td>Percentage of user cache (large_pool) actually in use</td></tr>\r
-<tr><td>rollback segments</td><td>11</td><td>&nbsp;</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Transactions</i> &nbsp;</td></tr><tr><td>peak transactions</td><td>24</td><td>Taken from high-water-mark</td></tr>\r
-<tr><td>max transactions</td><td>187</td><td>max transactions / rollback segments < 3.5 (or transactions_per_rollback_segment)</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Parameters</i> &nbsp;</td></tr><tr><td>cursor sharing</td><td>EXACT</td><td>Cursor reuse strategy. Recommended is FORCE (8i+) or SIMILAR (9i+). See <a href=http://www.praetoriate.com/oracle_tips_cursor_sharing.htm>cursor_sharing</a>.</td></tr>\r
-<tr><td>index cache cost</td><td>0</td><td>% of indexed data blocks expected in the cache.\r
-                       Recommended is 20-80. Default is 0. See <a href=http://www.dba-oracle.com/oracle_tips_cbo_part1.htm>optimizer_index_caching</a>.</td></tr>\r
-<tr><td>random page cost</td><td>100</td><td>Recommended is 10-50 for TP, and 50 for data warehouses. Default is 100. See <a href=http://www.dba-oracle.com/oracle_tips_cost_adj.htm>optimizer_index_cost_adj</a>. </td></tr>\r
-</table>\r
-<h3>Suspicious SQL</h3>\r
-\r
-<table border=1 bgcolor=white><tr><td><b>LOAD</b></td><td><b>EXECUTES</b></td><td><b>SQL_TEXT</b></td></tr>\r
-<tr><td align=right>  .73%</td><td align=right>89</td><td>select u.name, o.name, t.spare1, t.pctfree$    from sys.obj$ o, sys.user$ u, sys.tab$ t    where  (bitand(t.trigflag, 1048576) = 1048576) and           o.obj#=t.obj# and o.owner# = u.user# select i.obj#, i.flags, u.name, o.name     from sys.obj$ o, sys.user$ u, sys.ind$ i    where  (bitand(i.flags, 256) = 256 or bitand(i.flags, 512) = 512) and           (not((i.type# = 9) and bitand(i.flags,8) = 8)) and           o.obj#=i.obj# and o.owner# = u.user# </td></tr>\r
-<tr><td align=right>  .84%</td><td align=right>3</td><td>select /*+ RULE */ distinct tabs.table_name, tabs.owner , partitioned, iot_type  , TEMPORARY, table_type, table_type_owner  from DBA_ALL_TABLES tabs  where tabs.owner = :own  </td></tr>\r
-<tr><td align=right> 3.95%</td><td align=right>6</td><td>SELECT round(count(1)*avg(buf.block_size)/1048576) FROM DBA_OBJECTS obj, V$BH bh, dba_segments seg, v$buffer_pool buf WHERE obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner = seg.owner and obj.object_name = seg.segment_name and obj.object_type = seg.segment_type and seg.buffer_pool = buf.name and buf.name = 'DEFAULT'  </td></tr>\r
-<tr><td align=right> 4.50%</td><td align=right>6</td><td>SELECT round(count(1)*avg(tsp.block_size)/1048576) FROM DBA_OBJECTS obj, V$BH bh, dba_segments seg, dba_tablespaces tsp WHERE obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner = seg.owner and obj.object_name = seg.segment_name and obj.object_type = seg.segment_type and seg.tablespace_name = tsp.tablespace_name  </td></tr>\r
-<tr><td align=right>57.34%</td><td align=right>9267</td><td>select t.schema, t.name, t.flags, q.name from system.aq$_queue_tables t, sys.aq$_queue_table_affinities aft,      system.aq$_queues q where aft.table_objno = t.objno and aft.owner_instance = :1 and        q.table_objno = t.objno and q.usage = 0 and       bitand(t.flags, 4+16+32+64+128+256) = 0 for update of t.name, aft.table_objno skip locked </td></tr></table>\r
-\r
-<h3>Expensive SQL</h3>\r
-\r
-<table border=1 bgcolor=white><tr><td><b>LOAD</b></td><td><b>EXECUTES</b></td><td><b>SQL_TEXT</b></td></tr>\r
-<tr><td align=right> 5.24%</td><td align=right>1</td><td>select round(sum(bytes)/1048576) from dba_segments  </td></tr>\r
-<tr><td align=right> 6.89%</td><td align=right>6</td><td>SELECT round(count(1)*avg(buf.block_size)/1048576) FROM DBA_OBJECTS obj, V$BH bh, dba_segments seg, v$buffer_pool buf WHERE obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner = seg.owner and obj.object_name = seg.segment_name and obj.object_type = seg.segment_type and seg.buffer_pool = buf.name and buf.name = 'DEFAULT'  </td></tr>\r
-<tr><td align=right> 7.85%</td><td align=right>6</td><td>SELECT round(count(1)*avg(tsp.block_size)/1048576) FROM DBA_OBJECTS obj, V$BH bh, dba_segments seg, dba_tablespaces tsp WHERE obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner = seg.owner and obj.object_name = seg.segment_name and obj.object_type = seg.segment_type and seg.tablespace_name = tsp.tablespace_name  </td></tr>\r
-<tr><td align=right>33.69%</td><td align=right>89</td><td>select u.name, o.name, t.spare1, t.pctfree$    from sys.obj$ o, sys.user$ u, sys.tab$ t    where  (bitand(t.trigflag, 1048576) = 1048576) and           o.obj#=t.obj# and o.owner# = u.user# </td></tr>\r
-<tr><td align=right>36.44%</td><td align=right>89</td><td>select i.obj#, i.flags, u.name, o.name     from sys.obj$ o, sys.user$ u, sys.ind$ i    where  (bitand(i.flags, 256) = 256 or bitand(i.flags, 512) = 512) and           (not((i.type# = 9) and bitand(i.flags,8) = 8)) and           o.obj#=i.obj# and o.owner# = u.user# </td></tr></table>\r
-\r
-<p><a name=postgres id="postgres"></a></p>\r
-\r
-<table border=1 bgcolor=white><tr><td colspan=3><h3>postgres7</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>statistics collector</td><td>FALSE</td><td>Must be set to TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i> and <i>stats_block_level</i> must be set to true in postgresql.conf)</td></tr>\r
-<tr><td>data cache hit ratio</td><td>99.9666031916603</td><td>&nbsp;</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data reads</td><td>15</td><td>&nbsp;  </td></tr>\r
-<tr><td>data writes</td><td>0.000000000000000000</td><td>Count of inserts/updates/deletes * coef</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Data Cache</i> &nbsp;</td></tr><tr><td>data cache buffers</td><td>1280</td><td>Number of cache buffers. <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic>Tuning</a></td></tr>\r
-<tr><td>cache blocksize</td><td>8192</td><td>(estimate)</td></tr>\r
-<tr><td>data cache size</td><td>10M</td><td>&nbsp;</td></tr>\r
-<tr><td>operating system cache size</td><td>80000K</td><td>(effective cache size)</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Memory Pools</i> &nbsp;</td></tr><tr><td>sort buffer size</td><td>1M</td><td>Size of sort buffer (per query)</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i> &nbsp;</td></tr><tr><td>current connections</td><td>13</td><td>&nbsp;</td></tr>\r
-<tr><td>max connections</td><td>32</td><td>&nbsp;</td></tr>\r
-<tr bgcolor=#F0F0F0><td colspan=3><i>Parameters</i> &nbsp;</td></tr><tr><td>rollback buffers</td><td>8</td><td>WAL buffers</td></tr>\r
-<tr><td>random page cost</td><td>4</td><td>Cost of doing a seek (default=4). See <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#less>random_page_cost</a></td></tr>\r
-</table>\r
-\r
-</body>\r
-</html>\r
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+
+<html>
+<head>
+       <title>ADOdb Performance Monitoring Library</title>
+</head>
+
+<body>
+<h3>The ADOdb Performance Monitoring Library</h3>
+<p>V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my)</p>
+<p><font size="1">This software is dual licensed using BSD-Style and LGPL. This 
+  means you can use it in compiled proprietary and commercial products.</font></p>
+  <p>Useful ADOdb links:  <a href=http://php.weblogs.com/adodb?perf=1>Download</a> &nbsp; <a href=http://php.weblogs.com/adodb_manual?perf=1>Other Docs</a>
+<h3>Introduction</h3>
+<p>This module, part of the ADOdb package, provides both CLI and HTML interfaces 
+  for viewing key performance indicators of your database. This is very useful 
+  because web apps such as the popular phpMyAdmin currently do not provide effective 
+  database health monitoring tools. The module provides the following: 
+<ul>
+  <li>A quick health check of your database server using <code>$perf->HealthCheck()</code> 
+    or <code>$perf->HealthCheckCLI()</code>. 
+  <li>User interface for performance monitoring, <code>$perf-&gt;UI()</code>. 
+    This UI displays: 
+    <ul>
+      <li>the health check, </li>
+      <li>all SQL logged and their query plans, </li>
+      <li>a list of all tables in the current database</li>
+      <li>an interface to continiously poll the server for key performance indicators 
+        such as CPU, Hit Ratio, Disk I/O</li>
+               <li>a form where you can enter and run SQL interactively.</li>
+    </ul>
+  <li>Gives you an API to build database monitoring tools for a server farm, for 
+    example calling <code>$perf->DBParameter('data cache hit ratio')</code> returns 
+    this very important statistic in a database independant manner. 
+</ul>
+<p>ADOdb also has the ability to log all SQL executed, using <a href=docs-adodb.htm#logsql>LogSQL</a>. 
+  All SQL logged can be analyzed through the performance monitor <a href=#ui>UI</a>. 
+  In the <i>View SQL</i> mode, we categorize the SQL into 3 types:
+<ul>
+  <li><b>Suspicious SQL</b>: queries with high average execution times, and are potential 
+    candidates for rewriting</li>
+  <li><b>Expensive SQL</b>: queries with high total execution times (#executions * avg 
+    execution time). Optimizing these queries will reduce your database server 
+    load.</li>
+  <li><b>Invalid SQL</b>: queries that generate errors.</li>
+</ul>
+<p>Each query is hyperlinked to a description of the query plan, and every PHP 
+  script that executed that query is also shown.</p>
+<p>Please note that the information presented is a very basic database health 
+  check, and does not provide a complete overview of database performance. Although 
+  some attempt has been made to make it work across multiple databases in the 
+  same way, it is impossible to do so. For the health check, we do try to display 
+  the following key database parameters for all drivers:</p>
+<ul>
+  <li><b>data cache size</b> - The amount of memory allocated to the cache.</li>
+  <li><b>data cache hit ratio</b> - A measure of how effective the cache is, as a percentage. 
+  The higher, the better.</li>
+  <li><b>current connections</b> - The number of sessions currently connected to the 
+    database. </li>
+</ul>
+<p>You will need to connect to the database as an administrator to view most of 
+  the parameters. </p>
+<p>Code improvements as very welcome, particularly adding new database parameters 
+  and automated tuning hints.</p><a name=usage></a>
+<h3>Usage</h3>
+<p>Currently, the following drivers: <em>mysql</em>, <em>postgres</em>, <em>oci8</em>, 
+  <em>mssql</em>, <i>informix</i> and <em>db2</em> are supported. To create a 
+  new performance monitor, call NewPerfMonitor( ) as demonstrated below: </p>
+<pre>
+&lt;?php
+include_once('adodb.inc.php');
+session_start(); <font color="#006600"># session variables required for monitoring</font>
+$conn = ADONewConnection($driver);
+$conn-&gt;Connect($server,$user,$pwd,$db);
+$perf =&amp; NewPerfMonitor($conn);
+$perf-&gt;UI($pollsecs=5);<font color="#006600"></font>
+?>
+</pre>
+<p>It is also possible to retrieve a single database parameter:</p>
+<pre>$size = $perf->DBParameter('data cache size');
+</pre>
+<p>
+Thx to Fernando Ortiz for the informix module. 
+<h3>Methods</h3><a name=ui></a>
+<p><font face="Courier New, Courier, mono">function <b>UI($pollsecs=5)</b></font></p>
+<p>Creates a web-based user interface for performance monitoring. When you click on Poll, 
+server statistics will be displayed every $pollsecs seconds.  See <a href="#usage">Usage</a> 
+  above. 
+  <p>Since 4.11, we allow users to enter and run SQL interactively via the "Run SQL" link. To disable
+  this for security reasons, set this constant before calling $perf->UI().
+  <p>
+    <pre>define('ADODB_PERF_NO_RUN_SQL',1);</pre>
+  
+ <p>Sample output follows below:</p>
+
+<table border=1 width=100% bgcolor=lightyellow><tr>
+    <td> <b><a href=http://php.weblogs.com/adodb?perf=1>ADOdb</a> Performance 
+      Monitor</b> for localhost, db=test<br>
+      <font size=-1>PostgreSQL 7.3.2 on i686-pc-cygwin, compiled by GCC gcc (GCC) 
+      3.2 20020927 (prerelease)</font></tr>
+         <tr><td>
+       <a href=#>Performance Stats</a> &nbsp; <a href=#>View SQL</a>
+        &nbsp; <a href=#>View Tables</a> &nbsp; <a href=#>Poll Stats</a></tr></table><table border=1 bgcolor=white><tr><td colspan=3><h3>postgres7</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>statistics collector</td><td>TRUE</td><td>Value must be TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i> and <i>stats_block_level</i> must be set to true in postgresql.conf)</td></tr>
+<tr><td>data cache hit ratio</td><td>99.7967555299239</td><td>&nbsp;</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data reads</td><td>125</td><td>&nbsp;  </td></tr>
+<tr><td>data writes</td><td>21.78125000000000000</td><td>Count of inserts/updates/deletes * coef</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Data Cache</i> &nbsp;</td></tr><tr><td>data cache buffers</td><td>640</td><td>Number of cache buffers. <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic>Tuning</a></td></tr>
+<tr><td>cache blocksize</td><td>8192</td><td>(estimate)</td></tr>
+<tr><td>data cache size</td><td>5M</td><td>&nbsp;</td></tr>
+<tr><td>operating system cache size</td><td>80M</td><td>(effective cache size)</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Memory Usage</i> &nbsp;</td></tr><tr><td>sort buffer size</td><td>1M</td><td>Size of sort buffer (per query)</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i> &nbsp;</td></tr><tr><td>current connections</td><td>0</td><td>&nbsp;</td></tr>
+<tr><td>max connections</td><td>32</td><td>&nbsp;</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Parameters</i> &nbsp;</td></tr><tr><td>rollback buffers</td><td>8</td><td>WAL buffers</td></tr>
+<tr><td>random page cost</td><td>4</td><td>Cost of doing a seek (default=4). See <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#less>random_page_cost</a></td></tr>
+</table>
+<p><font face="Courier New, Courier, mono">function <b>HealthCheck</b>()</font></p> 
+<p>Returns database health check parameters as a HTML table. You will need to 
+  echo or print the output of this function,</p>
+<p><font face="Courier New, Courier, mono">function <b>HealthCheckCLI</b>()</font></p>
+<p>Returns database health check parameters formatted for a command line interface. 
+  You will need to echo or print the output of this function. Sample output for 
+  mysql:</p>
+<pre>
+-- Ratios -- 
+          MyISAM cache hit ratio => 56.5635738832 
+          InnoDB cache hit ratio => 0 
+             sql cache hit ratio => 0 
+ -- IO -- 
+                      data reads => 2622 
+                     data writes => 2415.5 
+ -- Data Cache -- 
+          MyISAM data cache size => 512K 
+             BDB data cache size => 8388600
+          InnoDB data cache size => 8M
+ -- Memory Pools -- 
+                read buffer size => 131072 
+                sort buffer size => 65528 
+                     table cache => 4 
+ -- Connections -- 
+             current connections => 3
+                 max connections => 100</pre>
+<p><font face="Courier New, Courier, mono">function <b>Poll</b>($pollSecs=5) 
+  </font> 
+<p> Run in infinite loop, displaying the following information every $pollSecs. 
+  This will not work properly if output buffering is enabled. 
+  In the example below, $pollSecs=3:
+<pre>
+Accumulating statistics...
+ Time   WS-CPU%   Hit%   Sess        Reads/s          Writes/s
+11:08:30    0.7  56.56      1         0.0000            0.0000
+11:08:33    1.8  56.56      2         0.0000            0.0000
+11:08:36   11.1  56.55      3         2.5000            0.0000
+11:08:39    9.8  56.55      2         3.1121            0.0000
+11:08:42    2.8  56.55      1         0.0000            0.0000
+11:08:45    7.4  56.55      2         0.0000            1.5000
+</pre>
+<p><b>WS-CPU%</b> is the Web Server CPU load of the server that PHP is running 
+  from (eg. the database client), and not the database. The <b>Hit%</b> is the 
+  data cache hit ratio. <b>Sess</b> is the current number of sessions connected 
+  to the database. If you are using persistent connections, this should not change 
+  much. The <b>Reads/s</b> and <b>Writes/s</b> are synthetic values to give the 
+  viewer a rough guide to I/O, and are not to be taken literally. 
+<p><font face="Courier New, Courier, mono">function <b>SuspiciousSQL</b>($numsql=10)</font></p>
+<p>Returns SQL which have high average execution times as a HTML table. Each sql statement
+is hyperlinked to a new window which details the execution plan and the scripts that execute this SQL.
+<p> The number of statements returned is determined by $numsql. Data is taken from the adodb_logsql table, where the sql statements are logged when
+$connection->LogSQL(true) is enabled. The adodb_logsql table is populated using <a href=docs-adodb.htm#logsql>$conn->LogSQL</a>.
+<p>For Oracle, Ixora Suspicious SQL returns a list of SQL statements that are most cache intensive as a HTML table. 
+  These are data intensive SQL statements that could benefit most from tuning. 
+<p><font face="Courier New, Courier, mono">function <b>ExpensiveSQL</b>($numsql=10)</font></p>
+<p>Returns SQL whose total execution time (avg time * #executions) is high as a HTML table. Each sql statement
+is hyperlinked to a new window which details the execution plan and the scripts that execute this SQL.
+<p> The number of statements returned is determined by $numsql. Data is taken from the adodb_logsql table, where the sql statements are logged when
+$connection->LogSQL(true) is enabled. The adodb_logsql table is populated using <a href=docs-adodb.htm#logsql>$conn->LogSQL</a>.
+
+<p>For Oracle, Ixora Expensive SQL returns a list of SQL statements that are taking the most CPU load 
+when run.
+<p><font face="Courier New, Courier, mono">function <b>InvalidSQL</b>($numsql=10)</font></p>
+<p>Returns a list of invalid SQL as an HTML table.
+<p>Data is taken from the adodb_logsql table, where the sql statements are logged when
+$connection->LogSQL(true) is enabled.
+<p><font face="Courier New, Courier, mono">function <b>Tables</b>($orderby=1)</font></p>
+<p>Returns information on all tables in a database, with the first two fields 
+  containing the table name and table size, the remaining fields depend on the 
+  database driver. If $orderby is set to 1, it will sort by name. If $orderby 
+  is set to 2, then it will sort by table size. Some database drivers (mssql and 
+  mysql) will ignore the $orderby clause. For postgresql, the information is up-to-date 
+  since the last <i>vacuum</i>. Not supported currently for db2.</p>
+<h3>Raw Functions</h3>
+<p>Raw functions return values without any formatting.</p>
+<p><font face="Courier New, Courier, mono">function <b>DBParameter</b>($paramname)</font></p>
+<p>Returns the value of a database parameter, such as $this-&gt;DBParameter(&quot;data 
+  cache size&quot;).</p>
+<p><font face="Courier New, Courier, mono">function <b>CPULoad</b>()</font></p>
+<p>Returns the CPU load of the database client (NOT THE SERVER) as a percentage. 
+  Only works for Linux and Windows. For Windows, WMI must be available.</p>
+<h3>Format of $settings Property</h3>
+<p> To create new database parameters, you need to understand $settings. The $settings 
+  data structure is an associative array. Each element of the array defines a 
+  database parameter. The key is the name of the database parameter. If no key is defined,
+  then it is assumed to be a section break, and the value is the name of the section break.
+  If this is too confusing, looking at the source code will help a lot!</p>
+<p> Each database parameter is itself an array consisting of the following elements:</p>
+<ol start="0">
+  <li> Category code, used to group related db parameters. If the category code is 'HIDE', then
+the database parameter is not shown when HTML() is called. <br>
+  </li>
+  <li> either 
+    <ol type="a">
+      <li>sql string to retrieve value, eg. "select value from v\$parameter where 
+        name='db_block_size'", </li>
+      <li>array holding sql string and field to look for, e.g. array('show variables','table_cache'); 
+        optional 3rd parameter is the $rs-&gt;fields[$index] to use (otherwise 
+        $index=1), and optional 4th parameter is a constant to multiply the result 
+        with (typically 100 for percentage calculations),</li>
+      <li>a string prefixed by =, then a PHP method of the class is invoked, e.g. 
+        to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue', 
+        <br>
+      </li>
+    </ol>
+  </li>
+  <li> Description of database parameter. If description begins with an =, then 
+    it is interpreted as a method call, just as in (1c) above, taking one parameter, 
+    the current value. E.g. '=GetIndexDescription' will invoke $this->GetIndexDescription($val). 
+    This is useful for generating tuning suggestions. For an example, see WarnCacheRatio().</li>
+</ol>
+<p>Example from MySQL, table_cache database parameter:</p>
+<pre>'table cache' =&gt; array('CACHE',            # category code
+   array(&quot;show variables&quot;, 'table_cache'), # array (type 1b)
+   'Number of tables to keep open'),       # description</pre>
+<h3>Example Health Check Output</h3>
+<p><a href="#db2">db2</a> <a href=#informix>informix</a> <a href="#mysql">mysql</a> <a href="#mssql">mssql</a> 
+  <a href="#oci8">oci8</a> <a href="#postgres">postgres</a></p>
+<p><a name=db2></a></p>
+<table border=1 bgcolor=white>
+  <tr> 
+    <td colspan=3> <h3>db2</h3></td>
+  </tr>
+  <tr> 
+    <td><b>Parameter</b></td>
+    <td><b>Value</b></td>
+    <td><b>Description</b></td>
+  </tr>
+  <tr bgcolor=#F0F0F0> 
+    <td colspan=3><i>Ratios</i> &nbsp;</td>
+  </tr>
+  <tr bgcolor=#FFFFFF> 
+    <td>data cache hit ratio</td>
+    <td>0 &nbsp; </td>
+    <td>&nbsp;</td>
+  </tr>
+  <tr bgcolor=#F0F0F0>
+    <td colspan=3><i>Data Cache</i></td>
+  </tr>
+  <tr bgcolor=#FFFFFF> 
+    <td>data cache buffers</td>
+    <td>250 &nbsp; </td>
+    <td>See <a href=http://www7b.boulder.ibm.com/dmdd/library/techarticle/anshum/0107anshum.html#bufferpoolsize>tuning 
+      reference</a>.</td>
+  </tr>
+  <tr bgcolor=#FFFFFF> 
+    <td>cache blocksize</td>
+    <td>4096 &nbsp; </td>
+    <td>&nbsp;</td>
+  </tr>
+  <tr bgcolor=#FFFFFF> 
+    <td>data cache size</td>
+    <td>1000K &nbsp; </td>
+    <td>&nbsp;</td>
+  </tr>
+  <tr bgcolor=#F0F0F0> 
+    <td colspan=3><i>Connections</i></td>
+  </tr>
+  <tr bgcolor=#FFFFFF> 
+    <td>current connections</td>
+    <td>2 &nbsp; </td>
+    <td>&nbsp;</td>
+  </tr>
+</table>
+<p>&nbsp;<p>
+<a name=informix></a>
+<table border=1 bgcolor=white><tr><td
+colspan=3><h3>informix</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Val
+ue</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td
+colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>data cache hit
+ratio</td><td>95.89</td><td>&nbsp;</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data
+reads</td><td>1883884</td><td>Page reads</td></tr>
+<tr><td>data writes</td><td>1716724</td><td>Page writes</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i>
+&nbsp;</td></tr><tr><td>current connections</td><td>263.0</td><td>Number of
+sessions</td></tr>
+</table>
+
+
+<p>&nbsp;</p>
+<p><a name=mysql id="mysql"></a></p><table border=1 bgcolor=white><tr><td colspan=3><h3>mysql</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>MyISAM cache hit ratio</td><td>56.5658301822</td><td><font color=red><b>Cache ratio should be at least 90%</b></font></td></tr>
+<tr><td>InnoDB cache hit ratio</td><td>0</td><td><font color=red><b>Cache ratio should be at least 90%</b></font></td></tr>
+<tr><td>sql cache hit ratio</td><td>0</td><td>&nbsp;</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data reads</td><td>2622</td><td>Number of selects (Key_reads is not accurate)</td></tr>
+<tr><td>data writes</td><td>2415.5</td><td>Number of inserts/updates/deletes * coef (Key_writes is not accurate)</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Data Cache</i> &nbsp;</td></tr><tr><td>MyISAM data cache size</td><td>512K</td><td>&nbsp;</td></tr>
+<tr><td>BDB data cache size</td><td>8388600</td><td>&nbsp;</td></tr>
+<tr><td>InnoDB data cache size</td><td>8M</td><td>&nbsp;</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Memory Pools</i> &nbsp;</td></tr><tr><td>read buffer size</td><td>131072</td><td>(per session)</td></tr>
+<tr><td>sort buffer size</td><td>65528</td><td>Size of sort buffer (per session)</td></tr>
+<tr><td>table cache</td><td>4</td><td>Number of tables to keep open</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i> &nbsp;</td></tr><tr><td>current connections</td><td>3</td><td>&nbsp;</td></tr>
+<tr><td>max connections</td><td>100</td><td>&nbsp;</td></tr>
+</table>
+<p>&nbsp;</p>
+<p><a name=mssql id="mssql"></a></p>
+
+<table border=1 bgcolor=white><tr><td colspan=3><h3>mssql</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>data cache hit ratio</td><td>99.9999694824</td><td>&nbsp;</td></tr>
+<tr><td>prepared sql hit ratio</td><td>99.7738579828</td><td>&nbsp;</td></tr>
+<tr><td>adhoc sql hit ratio</td><td>98.4540169133</td><td>&nbsp;</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data reads</td><td>2858</td><td>&nbsp;  </td></tr>
+<tr><td>data writes</td><td>1438</td><td>&nbsp;  </td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Data Cache</i> &nbsp;</td></tr><tr><td>data cache size</td><td>4362</td><td>in K</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i> &nbsp;</td></tr><tr><td>current connections</td><td>14</td><td>&nbsp;</td></tr>
+<tr><td>max connections</td><td>32767</td><td>&nbsp;</td></tr>
+</table>
+
+<p>&nbsp;</p>
+<p><a name=oci8 id="oci8"></a></p>
+<table border=1 bgcolor=white><tr><td colspan=3><h3>oci8</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>data cache hit ratio</td><td>96.98</td><td>&nbsp;</td></tr>
+<tr><td>sql cache hit ratio</td><td>99.96</td><td>&nbsp;</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data reads</td><td>842938</td><td>&nbsp;  </td></tr>
+<tr><td>data writes</td><td>16852</td><td>&nbsp;  </td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Data Cache</i> &nbsp;</td></tr><tr><td>data cache buffers</td><td>3072</td><td>Number of cache buffers</td></tr>
+<tr><td>data cache blocksize</td><td>8192</td><td>&nbsp;</td></tr>
+<tr><td>data cache size</td><td>48M</td><td>shared_pool_size</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Memory Pools</i> &nbsp;</td></tr><tr><td>java pool size</td><td>0</td><td>java_pool_size</td></tr>
+<tr><td>sort buffer size</td><td>512K</td><td>sort_area_size (per query)</td></tr>
+<tr><td>user session buffer size</td><td>8M</td><td>large_pool_size</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i> &nbsp;</td></tr><tr><td>current connections</td><td>1</td><td>&nbsp;</td></tr>
+<tr><td>max connections</td><td>170</td><td>&nbsp;</td></tr>
+<tr><td>data cache utilization ratio</td><td>88.46</td><td>Percentage of data cache actually in use</td></tr>
+<tr><td>user cache utilization ratio</td><td>91.76</td><td>Percentage of user cache (large_pool) actually in use</td></tr>
+<tr><td>rollback segments</td><td>11</td><td>&nbsp;</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Transactions</i> &nbsp;</td></tr><tr><td>peak transactions</td><td>24</td><td>Taken from high-water-mark</td></tr>
+<tr><td>max transactions</td><td>187</td><td>max transactions / rollback segments < 3.5 (or transactions_per_rollback_segment)</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Parameters</i> &nbsp;</td></tr><tr><td>cursor sharing</td><td>EXACT</td><td>Cursor reuse strategy. Recommended is FORCE (8i+) or SIMILAR (9i+). See <a href=http://www.praetoriate.com/oracle_tips_cursor_sharing.htm>cursor_sharing</a>.</td></tr>
+<tr><td>index cache cost</td><td>0</td><td>% of indexed data blocks expected in the cache.
+                       Recommended is 20-80. Default is 0. See <a href=http://www.dba-oracle.com/oracle_tips_cbo_part1.htm>optimizer_index_caching</a>.</td></tr>
+<tr><td>random page cost</td><td>100</td><td>Recommended is 10-50 for TP, and 50 for data warehouses. Default is 100. See <a href=http://www.dba-oracle.com/oracle_tips_cost_adj.htm>optimizer_index_cost_adj</a>. </td></tr>
+</table>
+<h3>Suspicious SQL</h3>
+
+<table border=1 bgcolor=white><tr><td><b>LOAD</b></td><td><b>EXECUTES</b></td><td><b>SQL_TEXT</b></td></tr>
+<tr><td align=right>  .73%</td><td align=right>89</td><td>select u.name, o.name, t.spare1, t.pctfree$    from sys.obj$ o, sys.user$ u, sys.tab$ t    where  (bitand(t.trigflag, 1048576) = 1048576) and           o.obj#=t.obj# and o.owner# = u.user# select i.obj#, i.flags, u.name, o.name     from sys.obj$ o, sys.user$ u, sys.ind$ i    where  (bitand(i.flags, 256) = 256 or bitand(i.flags, 512) = 512) and           (not((i.type# = 9) and bitand(i.flags,8) = 8)) and           o.obj#=i.obj# and o.owner# = u.user# </td></tr>
+<tr><td align=right>  .84%</td><td align=right>3</td><td>select /*+ RULE */ distinct tabs.table_name, tabs.owner , partitioned, iot_type  , TEMPORARY, table_type, table_type_owner  from DBA_ALL_TABLES tabs  where tabs.owner = :own  </td></tr>
+<tr><td align=right> 3.95%</td><td align=right>6</td><td>SELECT round(count(1)*avg(buf.block_size)/1048576) FROM DBA_OBJECTS obj, V$BH bh, dba_segments seg, v$buffer_pool buf WHERE obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner = seg.owner and obj.object_name = seg.segment_name and obj.object_type = seg.segment_type and seg.buffer_pool = buf.name and buf.name = 'DEFAULT'  </td></tr>
+<tr><td align=right> 4.50%</td><td align=right>6</td><td>SELECT round(count(1)*avg(tsp.block_size)/1048576) FROM DBA_OBJECTS obj, V$BH bh, dba_segments seg, dba_tablespaces tsp WHERE obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner = seg.owner and obj.object_name = seg.segment_name and obj.object_type = seg.segment_type and seg.tablespace_name = tsp.tablespace_name  </td></tr>
+<tr><td align=right>57.34%</td><td align=right>9267</td><td>select t.schema, t.name, t.flags, q.name from system.aq$_queue_tables t, sys.aq$_queue_table_affinities aft,      system.aq$_queues q where aft.table_objno = t.objno and aft.owner_instance = :1 and        q.table_objno = t.objno and q.usage = 0 and       bitand(t.flags, 4+16+32+64+128+256) = 0 for update of t.name, aft.table_objno skip locked </td></tr></table>
+
+<h3>Expensive SQL</h3>
+
+<table border=1 bgcolor=white><tr><td><b>LOAD</b></td><td><b>EXECUTES</b></td><td><b>SQL_TEXT</b></td></tr>
+<tr><td align=right> 5.24%</td><td align=right>1</td><td>select round(sum(bytes)/1048576) from dba_segments  </td></tr>
+<tr><td align=right> 6.89%</td><td align=right>6</td><td>SELECT round(count(1)*avg(buf.block_size)/1048576) FROM DBA_OBJECTS obj, V$BH bh, dba_segments seg, v$buffer_pool buf WHERE obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner = seg.owner and obj.object_name = seg.segment_name and obj.object_type = seg.segment_type and seg.buffer_pool = buf.name and buf.name = 'DEFAULT'  </td></tr>
+<tr><td align=right> 7.85%</td><td align=right>6</td><td>SELECT round(count(1)*avg(tsp.block_size)/1048576) FROM DBA_OBJECTS obj, V$BH bh, dba_segments seg, dba_tablespaces tsp WHERE obj.object_id = bh.objd AND obj.owner != 'SYS' and obj.owner = seg.owner and obj.object_name = seg.segment_name and obj.object_type = seg.segment_type and seg.tablespace_name = tsp.tablespace_name  </td></tr>
+<tr><td align=right>33.69%</td><td align=right>89</td><td>select u.name, o.name, t.spare1, t.pctfree$    from sys.obj$ o, sys.user$ u, sys.tab$ t    where  (bitand(t.trigflag, 1048576) = 1048576) and           o.obj#=t.obj# and o.owner# = u.user# </td></tr>
+<tr><td align=right>36.44%</td><td align=right>89</td><td>select i.obj#, i.flags, u.name, o.name     from sys.obj$ o, sys.user$ u, sys.ind$ i    where  (bitand(i.flags, 256) = 256 or bitand(i.flags, 512) = 512) and           (not((i.type# = 9) and bitand(i.flags,8) = 8)) and           o.obj#=i.obj# and o.owner# = u.user# </td></tr></table>
+
+<p><a name=postgres id="postgres"></a></p>
+
+<table border=1 bgcolor=white><tr><td colspan=3><h3>postgres7</h3></td></tr><tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr><tr bgcolor=#F0F0F0><td colspan=3><i>Ratios</i> &nbsp;</td></tr><tr><td>statistics collector</td><td>FALSE</td><td>Must be set to TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i> and <i>stats_block_level</i> must be set to true in postgresql.conf)</td></tr>
+<tr><td>data cache hit ratio</td><td>99.9666031916603</td><td>&nbsp;</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>IO</i> &nbsp;</td></tr><tr><td>data reads</td><td>15</td><td>&nbsp;  </td></tr>
+<tr><td>data writes</td><td>0.000000000000000000</td><td>Count of inserts/updates/deletes * coef</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Data Cache</i> &nbsp;</td></tr><tr><td>data cache buffers</td><td>1280</td><td>Number of cache buffers. <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic>Tuning</a></td></tr>
+<tr><td>cache blocksize</td><td>8192</td><td>(estimate)</td></tr>
+<tr><td>data cache size</td><td>10M</td><td>&nbsp;</td></tr>
+<tr><td>operating system cache size</td><td>80000K</td><td>(effective cache size)</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Memory Pools</i> &nbsp;</td></tr><tr><td>sort buffer size</td><td>1M</td><td>Size of sort buffer (per query)</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Connections</i> &nbsp;</td></tr><tr><td>current connections</td><td>13</td><td>&nbsp;</td></tr>
+<tr><td>max connections</td><td>32</td><td>&nbsp;</td></tr>
+<tr bgcolor=#F0F0F0><td colspan=3><i>Parameters</i> &nbsp;</td></tr><tr><td>rollback buffers</td><td>8</td><td>WAL buffers</td></tr>
+<tr><td>random page cost</td><td>4</td><td>Cost of doing a seek (default=4). See <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#less>random_page_cost</a></td></tr>
+</table>
+
+</body>
+</html>
index 04204789a62fc520cc5f2bd4af74a81dcf582598..1ae6bbe8a31c1302daf74b625308045f613973fd 100644 (file)
-<html>\r
-<head>\r
-<title>ADODB Session Management Manual</title>\r
-<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">\r
-<XSTYLE\r
-    body,td {font-family:Arial,Helvetica,sans-serif;font-size:11pt}\r
-    pre {font-size:9pt}\r
-    .toplink {font-size:8pt}\r
-    />\r
-</head>    \r
-<body bgcolor="#FFFFFF">\r
-<h3>ADODB Session Management Manual</h3>\r
-<p>\r
-V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my)\r
-<p> <font size=1>This software is dual licensed using BSD-Style and LGPL. This \r
-  means you can use it in compiled proprietary and commercial products. </font> \r
-<p>Useful ADOdb links:  <a href=http://php.weblogs.com/adodb>Download</a> &nbsp; <a href=http://php.weblogs.com/adodb_manual>Other Docs</a>\r
-\r
-<h3>Introduction</h3>\r
-<p> \r
-We store state information specific to a user or web client in session variables. These session variables \r
- persist throughout a session, as the user moves from page to page. \r
-<p>\r
-To use session variables, call session_start() at the beginning of your web page, \r
-before your HTTP headers are sent. Then for every variable you want to keep alive \r
-for the duration of the session, call session_register($variable_name). By default, \r
-the session handler will keep track of the session by using a cookie. You can save objects\r
- or arrays in session variables also.\r
-<p>The default method of storing sessions is to store it in a file. However if \r
-  you have special needs such as you:\r
-<ul>\r
-  <li>Have multiple web servers that need to share session info</li>\r
-  <li>Need to do special processing of each session</li>\r
-  <li>Require notification when a session expires</li>\r
-</ul>\r
-<p>Then the ADOdb session handler provides you with the above additional capabilities \r
-  by storing the session information as records in a database table that can be \r
-  shared across multiple servers. \r
-<p><b>Important Upgrade Notice:</b> Since ADOdb 4.05, the session files have been moved to its own folder, adodb/session. This is a rewrite\r
-of the session code by Ross Smith. The old session code is in adodb/session/old. \r
-<h4>ADOdb Session Handler Features</h4>\r
-<ul>\r
-<li>Ability to define a notification function that is called when a session expires. Typically\r
-used to detect session logout and release global resources.\r
-<li>Optimization of database writes. We crc32 the session data and only perform an update\r
-to the session data if there is a data change.\r
-<li>Support for large amounts of session data with CLOBs (see adodb-session-clob.php). Useful\r
-for Oracle.\r
-<li>Support for encrypted session data, see adodb-cryptsession.inc.php. Enabling encryption \r
-is simply a matter of including adodb-cryptsession.inc.php instead of adodb-session.inc.php.\r
-</ul>\r
-<h3>Setup</h3>\r
-<p>There are 3 session management files that you can use:\r
-<pre>\r
-adodb-session.php        : The default\r
-adodb-session-clob.php   : Use this if you are storing DATA in clobs\r
-adodb-cryptsession.php   : Use this if you want to store encrypted session data in the database\r
-\r
-<strong>Examples</strong>\r
- <font color=#004040>\r
-    include('adodb/adodb.inc.php');\r
-    \r
-<b>    $ADODB_SESSION_DRIVER='mysql';\r
-    $ADODB_SESSION_CONNECT='localhost';\r
-    $ADODB_SESSION_USER ='scott';\r
-    $ADODB_SESSION_PWD ='tiger';\r
-    $ADODB_SESSION_DB ='sessiondb';</b>\r
-    \r
-    <b>include('adodb/session/adodb-session.php');</b>\r
-    session_start();\r
-    \r
-    #\r
-    # Test session vars, the following should increment on refresh\r
-    #\r
-    $_SESSION['AVAR'] += 1;\r
-    print "&lt;p>\$_SESSION['AVAR']={$_SESSION['AVAR']}&lt;/p>";\r
-</font>\r
-To force non-persistent connections, call adodb_session_open first before session_start():\r
- <font color=#004040>\r
-    include('adodb/adodb.inc.php');\r
-    \r
-<b>    $ADODB_SESSION_DRIVER='mysql';\r
-    $ADODB_SESSION_CONNECT='localhost';\r
-    $ADODB_SESSION_USER ='scott';\r
-    $ADODB_SESSION_PWD ='tiger';\r
-    $ADODB_SESSION_DB ='sessiondb';</b>\r
-    \r
-    <b>include('adodb/session/adodb-session.php');\r
-    adodb_sess_open(false,false,false);</b>\r
-    session_start();\r
- </font color=#004040>\r
-To use a encrypted sessions, simply replace the file:\r
- <font color=#004040>\r
-    include('adodb/adodb.inc.php');\r
-    \r
-<b>    $ADODB_SESSION_DRIVER='mysql';\r
-    $ADODB_SESSION_CONNECT='localhost';\r
-    $ADODB_SESSION_USER ='scott';\r
-    $ADODB_SESSION_PWD ='tiger';\r
-    $ADODB_SESSION_DB ='sessiondb';\r
-    \r
-    include('adodb/session/adodb-cryptsession.php');</b>\r
-    session_start();\r
-    </font>\r
-And the same technique for adodb-session-clob.php:\r
- <font color=#004040>\r
-    include('adodb/adodb.inc.php');\r
-    \r
-<b>    $ADODB_SESSION_DRIVER='mysql';\r
-    $ADODB_SESSION_CONNECT='localhost';\r
-    $ADODB_SESSION_USER ='scott';\r
-    $ADODB_SESSION_PWD ='tiger';\r
-    $ADODB_SESSION_DB ='sessiondb';\r
-    \r
-    include('adodb/session/adodb-session-clob.php');</b>\r
-    session_start();\r
-    </font>\r
- <h4>Installation</h4>\r
- 1. Create this table in your database (syntax might vary depending on your db):\r
- <a name=sessiontab></a> <font color=#004040>\r
-  create table sessions (\r
-       SESSKEY char(32) not null,\r
-       EXPIRY int(11) unsigned not null,\r
-       EXPIREREF varchar(64),\r
-       DATA text not null,\r
-      primary key (sesskey)\r
-  );</font>\r
-  \r
-  For the adodb-session-clob.php version, create this:\r
-   <font color=#004040>\r
-    create table sessions (\r
-       SESSKEY char(32) not null,\r
-       EXPIRY int(11) unsigned not null,\r
-       EXPIREREF varchar(64),\r
-       DATA CLOB,\r
-      primary key (sesskey)\r
-  );</font>\r
-\r
-  2. Then define the following parameters. You can either modify\r
-     this file, or define them before this file is included:\r
-      <font color=#004040>\r
-    $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';\r
-    $ADODB_SESSION_CONNECT='server to connect to';\r
-    $ADODB_SESSION_USER ='user';\r
-    $ADODB_SESSION_PWD ='password';\r
-    $ADODB_SESSION_DB ='database';\r
-    $ADODB_SESSION_TBL = 'sessions'; # setting this is optional\r
-       </font>\r
-    When the session is created, $<b>ADODB_SESS_CONN</b> holds the connection object.\r
-    \r
-  3. Recommended is PHP 4.0.6 or later. There are documented session bugs \r
-  in earlier versions of PHP.\r
-</pre>\r
-\r
-    <h3>Notifications</h3>\r
-<p>If you want to receive notification when a session expires, then\r
-     tag the session record with a <a href="#sessiontab">EXPIREREF</a> tag (see the \r
-    definition of the sessions table above).  Before any session record is deleted,\r
-       ADOdb will call a notification function, passing in the EXPIREREF.\r
-<p>\r
-When a session is first created, we check a global variable $ADODB_SESSION_EXPIRE_NOTIFY.\r
-    This is an array with 2 elements, the first being the name of the session variable\r
-    you would like to store in the EXPIREREF field, and the 2nd is the \r
-    notification function's name.\r
-       <p>\r
-        Suppose we want to be notified when a user's session \r
-    has expired, based on the userid. The user id in the global session variable $USERID.\r
-       The function name is 'NotifyFn'. So we define:\r
-    <pre> <font color=#004040>\r
-        $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');\r
-    </font></pre>\r
-    And when the NotifyFn is called (when the session expires), we pass the $USERID \r
-    as the first parameter, eg. NotifyFn($userid, $sesskey). The session key (which is \r
-       the primary key of the record in the sessions table) is the 2nd parameter.\r
-  <p>\r
-    Here is an example of a Notification function that deletes some records in the database\r
-       and temporary files:\r
-    <pre><font color=#004040>\r
-        function NotifyFn($expireref, $sesskey)\r
-        {\r
-        global $ADODB_SESS_CONN; # the session connection object\r
-\r
-          $user = $ADODB_SESS_CONN->qstr($expireref);\r
-          $ADODB_SESS_CONN->Execute("delete from shopping_cart where user=$user");\r
-          system("rm /work/tmpfiles/$expireref/*");\r
-        }</font>\r
-    </pre>\r
-       <p>\r
\r
-    <p>\r
-    NOTE: If you want to change the EXPIREREF after the session record has been\r
-    created, you will need to modify any session variable to force a database\r
-    record update.\r
-<h4>Compression/Encryption Schemes</h4>\r
-Since ADOdb 4.05, thanks to Ross Smith,  multiple encryption and compression schemes are supported.\r
-  Currently, supported:\r
-<pre>\r
-  MD5Crypt (crypt.inc.php)\r
-  MCrypt\r
-  Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)\r
-  GZip\r
-  BZip2\r
-</pre>\r
-These are stackable. E.g. \r
-<pre>\r
-ADODB_Session::filter(new ADODB_Compress_Bzip2());\r
-ADODB_Session::filter(new ADODB_Encrypt_MD5());\r
-</pre>\r
-will compress and then encrypt the record in the database.\r
-<p>\r
-Also see the <a href=docs-adodb.htm>core ADOdb documentation</a>.\r
-</body>\r
+<html>
+<head>
+<title>ADODB Session Management Manual</title>
+<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+<XSTYLE
+    body,td {font-family:Arial,Helvetica,sans-serif;font-size:11pt}
+    pre {font-size:9pt}
+    .toplink {font-size:8pt}
+    />
+</head>    
+<body bgcolor="#FFFFFF">
+<h3>ADODB Session Management Manual</h3>
+<p>
+V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my)
+<p> <font size=1>This software is dual licensed using BSD-Style and LGPL. This 
+  means you can use it in compiled proprietary and commercial products. </font> 
+<p>Useful ADOdb links:  <a href=http://php.weblogs.com/adodb>Download</a> &nbsp; <a href=http://php.weblogs.com/adodb_manual>Other Docs</a>
+
+<h3>Introduction</h3>
+<p> 
+We store state information specific to a user or web client in session variables. These session variables 
+ persist throughout a session, as the user moves from page to page. 
+<p>
+To use session variables, call session_start() at the beginning of your web page, 
+before your HTTP headers are sent. Then for every variable you want to keep alive 
+for the duration of the session, call session_register($variable_name). By default, 
+the session handler will keep track of the session by using a cookie. You can save objects
+ or arrays in session variables also.
+<p>The default method of storing sessions is to store it in a file. However if 
+  you have special needs such as you:
+<ul>
+  <li>Have multiple web servers that need to share session info</li>
+  <li>Need to do special processing of each session</li>
+  <li>Require notification when a session expires</li>
+</ul>
+<p>Then the ADOdb session handler provides you with the above additional capabilities 
+  by storing the session information as records in a database table that can be 
+  shared across multiple servers. 
+<p><b>Important Upgrade Notice:</b> Since ADOdb 4.05, the session files have been moved to its own folder, adodb/session. This is a rewrite
+of the session code by Ross Smith. The old session code is in adodb/session/old. 
+<h4>ADOdb Session Handler Features</h4>
+<ul>
+<li>Ability to define a notification function that is called when a session expires. Typically
+used to detect session logout and release global resources.
+<li>Optimization of database writes. We crc32 the session data and only perform an update
+to the session data if there is a data change.
+<li>Support for large amounts of session data with CLOBs (see adodb-session-clob.php). Useful
+for Oracle.
+<li>Support for encrypted session data, see adodb-cryptsession.inc.php. Enabling encryption 
+is simply a matter of including adodb-cryptsession.inc.php instead of adodb-session.inc.php.
+</ul>
+<h3>Setup</h3>
+<p>There are 3 session management files that you can use:
+<pre>
+adodb-session.php        : The default
+adodb-session-clob.php   : Use this if you are storing DATA in clobs
+adodb-cryptsession.php   : Use this if you want to store encrypted session data in the database
+
+<strong>Examples</strong>
+ <font color=#004040>
+    include('adodb/adodb.inc.php');
+    
+<b>    $ADODB_SESSION_DRIVER='mysql';
+    $ADODB_SESSION_CONNECT='localhost';
+    $ADODB_SESSION_USER ='scott';
+    $ADODB_SESSION_PWD ='tiger';
+    $ADODB_SESSION_DB ='sessiondb';</b>
+    
+    <b>include('adodb/session/adodb-session.php');</b>
+    session_start();
+    
+    #
+    # Test session vars, the following should increment on refresh
+    #
+    $_SESSION['AVAR'] += 1;
+    print "&lt;p>\$_SESSION['AVAR']={$_SESSION['AVAR']}&lt;/p>";
+</font>
+To force non-persistent connections, call adodb_session_open first before session_start():
+ <font color=#004040>
+    include('adodb/adodb.inc.php');
+    
+<b>    $ADODB_SESSION_DRIVER='mysql';
+    $ADODB_SESSION_CONNECT='localhost';
+    $ADODB_SESSION_USER ='scott';
+    $ADODB_SESSION_PWD ='tiger';
+    $ADODB_SESSION_DB ='sessiondb';</b>
+    
+    <b>include('adodb/session/adodb-session.php');
+    adodb_sess_open(false,false,false);</b>
+    session_start();
+ </font color=#004040>
+To use a encrypted sessions, simply replace the file:
+ <font color=#004040>
+    include('adodb/adodb.inc.php');
+    
+<b>    $ADODB_SESSION_DRIVER='mysql';
+    $ADODB_SESSION_CONNECT='localhost';
+    $ADODB_SESSION_USER ='scott';
+    $ADODB_SESSION_PWD ='tiger';
+    $ADODB_SESSION_DB ='sessiondb';
+    
+    include('adodb/session/adodb-cryptsession.php');</b>
+    session_start();
+    </font>
+And the same technique for adodb-session-clob.php:
+ <font color=#004040>
+    include('adodb/adodb.inc.php');
+    
+<b>    $ADODB_SESSION_DRIVER='mysql';
+    $ADODB_SESSION_CONNECT='localhost';
+    $ADODB_SESSION_USER ='scott';
+    $ADODB_SESSION_PWD ='tiger';
+    $ADODB_SESSION_DB ='sessiondb';
+    
+    include('adodb/session/adodb-session-clob.php');</b>
+    session_start();
+    </font>
+ <h4>Installation</h4>
+ 1. Create this table in your database (syntax might vary depending on your db):
+ <a name=sessiontab></a> <font color=#004040>
+  create table sessions (
+       SESSKEY char(32) not null,
+       EXPIRY int(11) unsigned not null,
+       EXPIREREF varchar(64),
+       DATA text not null,
+      primary key (sesskey)
+  );</font>
+  
+  For the adodb-session-clob.php version, create this:
+   <font color=#004040>
+    create table sessions (
+       SESSKEY char(32) not null,
+       EXPIRY int(11) unsigned not null,
+       EXPIREREF varchar(64),
+       DATA CLOB,
+      primary key (sesskey)
+  );</font>
+
+  2. Then define the following parameters. You can either modify
+     this file, or define them before this file is included:
+      <font color=#004040>
+    $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
+    $ADODB_SESSION_CONNECT='server to connect to';
+    $ADODB_SESSION_USER ='user';
+    $ADODB_SESSION_PWD ='password';
+    $ADODB_SESSION_DB ='database';
+    $ADODB_SESSION_TBL = 'sessions'; # setting this is optional
+       </font>
+    When the session is created, $<b>ADODB_SESS_CONN</b> holds the connection object.
+    
+  3. Recommended is PHP 4.0.6 or later. There are documented session bugs 
+  in earlier versions of PHP.
+</pre>
+
+    <h3>Notifications</h3>
+<p>If you want to receive notification when a session expires, then
+     tag the session record with a <a href="#sessiontab">EXPIREREF</a> tag (see the 
+    definition of the sessions table above).  Before any session record is deleted,
+       ADOdb will call a notification function, passing in the EXPIREREF.
+<p>
+When a session is first created, we check a global variable $ADODB_SESSION_EXPIRE_NOTIFY.
+    This is an array with 2 elements, the first being the name of the session variable
+    you would like to store in the EXPIREREF field, and the 2nd is the 
+    notification function's name.
+       <p>
+        Suppose we want to be notified when a user's session 
+    has expired, based on the userid. The user id in the global session variable $USERID.
+       The function name is 'NotifyFn'. So we define:
+    <pre> <font color=#004040>
+        $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
+    </font></pre>
+    And when the NotifyFn is called (when the session expires), we pass the $USERID 
+    as the first parameter, eg. NotifyFn($userid, $sesskey). The session key (which is 
+       the primary key of the record in the sessions table) is the 2nd parameter.
+  <p>
+    Here is an example of a Notification function that deletes some records in the database
+       and temporary files:
+    <pre><font color=#004040>
+        function NotifyFn($expireref, $sesskey)
+        {
+        global $ADODB_SESS_CONN; # the session connection object
+
+          $user = $ADODB_SESS_CONN->qstr($expireref);
+          $ADODB_SESS_CONN->Execute("delete from shopping_cart where user=$user");
+          system("rm /work/tmpfiles/$expireref/*");
+        }</font>
+    </pre>
+       <p>
+    <p>
+    NOTE: If you want to change the EXPIREREF after the session record has been
+    created, you will need to modify any session variable to force a database
+    record update.
+<h4>Compression/Encryption Schemes</h4>
+Since ADOdb 4.05, thanks to Ross Smith,  multiple encryption and compression schemes are supported.
+  Currently, supported:
+<pre>
+  MD5Crypt (crypt.inc.php)
+  MCrypt
+  Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)
+  GZip
+  BZip2
+</pre>
+These are stackable. E.g. 
+<pre>
+ADODB_Session::filter(new ADODB_Compress_Bzip2());
+ADODB_Session::filter(new ADODB_Encrypt_MD5());
+</pre>
+will compress and then encrypt the record in the database.
+<p>
+Also see the <a href=docs-adodb.htm>core ADOdb documentation</a>.
+</body>
 </html>
\ No newline at end of file
index fca5a8328571c0c27d811de640336ffd33ebb7ba..9e418b7fdeeab2d71a5e4802c568b7dbdf072a0a 100644 (file)
@@ -1,79 +1,79 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. See License.txt. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Microsoft Access data driver. Requires ODBC. Works only on MS Windows.\r
-*/\r
-if (!defined('_ADODB_ODBC_LAYER')) {\r
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
-}\r
- if (!defined('_ADODB_ACCESS')) {\r
-       define('_ADODB_ACCESS',1);\r
-       \r
-class  ADODB_access extends ADODB_odbc {       \r
-       var $databaseType = 'access';\r
-       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE\r
-       var $fmtDate = "#Y-m-d#";\r
-       var $fmtTimeStamp = "#Y-m-d h:i:sA#"; // note not comma\r
-       var $_bindInputArray = false; // strangely enough, setting to true does not work reliably\r
-       var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";\r
-       var $sysTimeStamp = 'NOW';\r
-       var $hasTransactions = false;\r
-       \r
-       function ADODB_access()\r
-       {\r
-       global $ADODB_EXTENSION;\r
-       \r
-               $ADODB_EXTENSION = false;\r
-               $this->ADODB_odbc();\r
-       }\r
-       \r
-       function BeginTrans() { return false;}\r
-       \r
-       function IfNull( $field, $ifNull ) \r
-       {\r
-               return " IIF(IsNull($field), $ifNull, $field) "; // if Access\r
-       }\r
-/*\r
-       function &MetaTables()\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $savem = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $qid = odbc_tables($this->_connectionID);\r
-               $rs = new ADORecordSet_odbc($qid);\r
-               $ADODB_FETCH_MODE = $savem;\r
-               if (!$rs) return false;\r
-               \r
-               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
-               \r
-               $arr = &$rs->GetArray();\r
-               //print_pre($arr);\r
-               $arr2 = array();\r
-               for ($i=0; $i < sizeof($arr); $i++) {\r
-                       if ($arr[$i][2] && $arr[$i][3] != 'SYSTEM TABLE')\r
-                               $arr2[] = $arr[$i][2];\r
-               }\r
-               return $arr2;\r
-       }*/\r
-}\r
-\r
\r
-class  ADORecordSet_access extends ADORecordSet_odbc { \r
-       \r
-       var $databaseType = "access";           \r
-       \r
-       function ADORecordSet_access($id,$mode=false)\r
-       {\r
-               return $this->ADORecordSet_odbc($id,$mode);\r
-       }\r
-}// class\r
-} \r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Microsoft Access data driver. Requires ODBC. Works only on MS Windows.
+*/
+if (!defined('_ADODB_ODBC_LAYER')) {
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+ if (!defined('_ADODB_ACCESS')) {
+       define('_ADODB_ACCESS',1);
+
+class  ADODB_access extends ADODB_odbc {       
+       var $databaseType = 'access';
+       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE
+       var $fmtDate = "#Y-m-d#";
+       var $fmtTimeStamp = "#Y-m-d h:i:sA#"; // note not comma
+       var $_bindInputArray = false; // strangely enough, setting to true does not work reliably
+       var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
+       var $sysTimeStamp = 'NOW';
+       var $hasTransactions = false;
+       
+       function ADODB_access()
+       {
+       global $ADODB_EXTENSION;
+       
+               $ADODB_EXTENSION = false;
+               $this->ADODB_odbc();
+       }
+       
+       function BeginTrans() { return false;}
+       
+       function IfNull( $field, $ifNull ) 
+       {
+               return " IIF(IsNull($field), $ifNull, $field) "; // if Access
+       }
+/*
+       function &MetaTables()
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $savem = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $qid = odbc_tables($this->_connectionID);
+               $rs = new ADORecordSet_odbc($qid);
+               $ADODB_FETCH_MODE = $savem;
+               if (!$rs) return false;
+               
+               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+               
+               $arr = &$rs->GetArray();
+               //print_pre($arr);
+               $arr2 = array();
+               for ($i=0; $i < sizeof($arr); $i++) {
+                       if ($arr[$i][2] && $arr[$i][3] != 'SYSTEM TABLE')
+                               $arr2[] = $arr[$i][2];
+               }
+               return $arr2;
+       }*/
+}
+
+class  ADORecordSet_access extends ADORecordSet_odbc { 
+       
+       var $databaseType = "access";           
+       
+       function ADORecordSet_access($id,$mode=false)
+       {
+               return $this->ADORecordSet_odbc($id,$mode);
+       }
+}// class
+} 
 ?>
\ No newline at end of file
index ad49f6406ec66c4af5ab05f62c999b3728c27872..68ea5056abd7e59b9afe4c1237b2e723da941adb 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-       Microsoft ADO data driver. Requires ADO. Works only on MS Windows.\r
-*/\r
-  define("_ADODB_ADO_LAYER", 1 );\r
-/*--------------------------------------------------------------------------------------\r
---------------------------------------------------------------------------------------*/\r
-  \r
-class ADODB_ado extends ADOConnection {\r
-       var $databaseType = "ado";      \r
-       var $_bindInputArray = false;\r
-       var $fmtDate = "'Y-m-d'";\r
-       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $dataProvider = "ado";      \r
-       var $hasAffectedRows = true;\r
-       var $adoParameterType = 201; // 201 = long varchar, 203=long wide varchar, 205 = long varbinary\r
-       var $_affectedRows = false;\r
-       var $_thisTransactions;\r
-       var $_cursor_type = 3; // 3=adOpenStatic,0=adOpenForwardOnly,1=adOpenKeyset,2=adOpenDynamic\r
-       var $_cursor_location = 3; // 2=adUseServer, 3 = adUseClient;\r
-       var $_lock_type = -1;\r
-       var $_execute_option = -1;\r
-       var $poorAffectedRows = true; \r
-       var $charPage;\r
-               \r
-       function ADODB_ado() \r
-       {       \r
-               $this->_affectedRows = new VARIANT;\r
-       }\r
-\r
-       function ServerInfo()\r
-       {\r
-               if (!empty($this->_connectionID)) $desc = $this->_connectionID->provider;\r
-               return array('description' => $desc, 'version' => '');\r
-       }\r
-       \r
-       function _affectedrows()\r
-       {\r
-                       return $this->_affectedRows->value;\r
-       }\r
-       \r
-       // you can also pass a connection string like this:\r
-       //\r
-       // $DB->Connect('USER ID=sa;PASSWORD=pwd;SERVER=mangrove;DATABASE=ai',false,false,'SQLOLEDB');\r
-       function _connect($argHostname, $argUsername, $argPassword, $argProvider= 'MSDASQL')\r
-       {\r
-               $u = 'UID';\r
-               $p = 'PWD';\r
-       \r
-               if (!empty($this->charPage))\r
-                       $dbc = new COM('ADODB.Connection',null,$this->charPage);\r
-               else\r
-                       $dbc = new COM('ADODB.Connection');\r
-                       \r
-               if (! $dbc) return false;\r
-\r
-               /* special support if provider is mssql or access */\r
-               if ($argProvider=='mssql') {\r
-                       $u = 'User Id';  //User parameter name for OLEDB\r
-                       $p = 'Password'; \r
-                       $argProvider = "SQLOLEDB"; // SQL Server Provider\r
-                       \r
-                       // not yet\r
-                       //if ($argDatabasename) $argHostname .= ";Initial Catalog=$argDatabasename";\r
-                       \r
-                       //use trusted conection for SQL if username not specified\r
-                       if (!$argUsername) $argHostname .= ";Trusted_Connection=Yes";\r
-               } else if ($argProvider=='access')\r
-                       $argProvider = "Microsoft.Jet.OLEDB.4.0"; // Microsoft Jet Provider\r
-               \r
-               if ($argProvider) $dbc->Provider = $argProvider;        \r
-               \r
-               if ($argUsername) $argHostname .= ";$u=$argUsername";\r
-               if ($argPassword)$argHostname .= ";$p=$argPassword";\r
-               \r
-               if ($this->debug) ADOConnection::outp( "Host=".$argHostname."<BR>\n version=$dbc->version");\r
-               // @ added below for php 4.0.1 and earlier\r
-               @$dbc->Open((string) $argHostname);\r
-               \r
-               $this->_connectionID = $dbc;\r
-               \r
-               $dbc->CursorLocation = $this->_cursor_location;\r
-               return  $dbc->State > 0;\r
-       }\r
-       \r
-       // returns true or false\r
-       function _pconnect($argHostname, $argUsername, $argPassword, $argProvider='MSDASQL')\r
-       {\r
-               return $this->_connect($argHostname,$argUsername,$argPassword,$argProvider);\r
-       }       \r
-       \r
-/*\r
-       adSchemaCatalogs        = 1,\r
-       adSchemaCharacterSets   = 2,\r
-       adSchemaCollations      = 3,\r
-       adSchemaColumns = 4,\r
-       adSchemaCheckConstraints        = 5,\r
-       adSchemaConstraintColumnUsage   = 6,\r
-       adSchemaConstraintTableUsage    = 7,\r
-       adSchemaKeyColumnUsage  = 8,\r
-       adSchemaReferentialContraints   = 9,\r
-       adSchemaTableConstraints        = 10,\r
-       adSchemaColumnsDomainUsage      = 11,\r
-       adSchemaIndexes = 12,\r
-       adSchemaColumnPrivileges        = 13,\r
-       adSchemaTablePrivileges = 14,\r
-       adSchemaUsagePrivileges = 15,\r
-       adSchemaProcedures      = 16,\r
-       adSchemaSchemata        = 17,\r
-       adSchemaSQLLanguages    = 18,\r
-       adSchemaStatistics      = 19,\r
-       adSchemaTables  = 20,\r
-       adSchemaTranslations    = 21,\r
-       adSchemaProviderTypes   = 22,\r
-       adSchemaViews   = 23,\r
-       adSchemaViewColumnUsage = 24,\r
-       adSchemaViewTableUsage  = 25,\r
-       adSchemaProcedureParameters     = 26,\r
-       adSchemaForeignKeys     = 27,\r
-       adSchemaPrimaryKeys     = 28,\r
-       adSchemaProcedureColumns        = 29,\r
-       adSchemaDBInfoKeywords  = 30,\r
-       adSchemaDBInfoLiterals  = 31,\r
-       adSchemaCubes   = 32,\r
-       adSchemaDimensions      = 33,\r
-       adSchemaHierarchies     = 34,\r
-       adSchemaLevels  = 35,\r
-       adSchemaMeasures        = 36,\r
-       adSchemaProperties      = 37,\r
-       adSchemaMembers = 38\r
-\r
-*/\r
-       \r
-       function &MetaTables()\r
-       {\r
-               $arr= array();\r
-               $dbc = $this->_connectionID;\r
-               \r
-               $adors=@$dbc->OpenSchema(20);//tables\r
-               if ($adors){\r
-                       $f = $adors->Fields(2);//table/view name\r
-                       $t = $adors->Fields(3);//table type\r
-                       while (!$adors->EOF){\r
-                               $tt=substr($t->value,0,6);\r
-                               if ($tt!='SYSTEM' && $tt !='ACCESS')\r
-                                       $arr[]=$f->value;\r
-                               //print $f->value . ' ' . $t->value.'<br>';\r
-                               $adors->MoveNext();\r
-                       }\r
-                       $adors->Close();\r
-               }\r
-               \r
-               return $arr;\r
-       }\r
-       \r
-       function &MetaColumns($table)\r
-       {\r
-               $table = strtoupper($table);\r
-               $arr= array();\r
-               $dbc = $this->_connectionID;\r
-               \r
-               $adors=@$dbc->OpenSchema(4);//tables\r
-       \r
-               if ($adors){\r
-                       $t = $adors->Fields(2);//table/view name\r
-                       while (!$adors->EOF){\r
-                               \r
-                               \r
-                               if (strtoupper($t->Value) == $table) {\r
-                               \r
-                                       $fld = new ADOFieldObject();\r
-                                       $c = $adors->Fields(3);\r
-                                       $fld->name = $c->Value;\r
-                                       $fld->type = 'CHAR'; // cannot discover type in ADO!\r
-                                       $fld->max_length = -1;\r
-                                       $arr[strtoupper($fld->name)]=$fld;\r
-                               }\r
-               \r
-                               $adors->MoveNext();\r
-                       }\r
-                       $adors->Close();\r
-               }\r
-               \r
-               return $arr;\r
-       }\r
-       \r
-\r
-\r
-       \r
-       /* returns queryID or false */\r
-       function &_query($sql,$inputarr=false) \r
-       {\r
-               \r
-               $dbc = $this->_connectionID;\r
-               \r
-       //      return rs       \r
-               if ($inputarr) {\r
-                       \r
-                       if (!empty($this->charPage))\r
-                               $oCmd = new COM('ADODB.Command',null,$this->charPage);\r
-                       else\r
-                               $oCmd = new COM('ADODB.Command');\r
-                       $oCmd->ActiveConnection = $dbc;\r
-                       $oCmd->CommandText = $sql;\r
-                       $oCmd->CommandType = 1;\r
-\r
-                       foreach($inputarr as $val) {\r
-                               // name, type, direction 1 = input, len,\r
-                               $this->adoParameterType = 130;\r
-                               $p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);\r
-                               //print $p->Type.' '.$p->value;\r
-                               $oCmd->Parameters->Append($p);\r
-                       }\r
-                       $p = false;\r
-                       $rs = $oCmd->Execute();\r
-                       $e = $dbc->Errors;\r
-                       if ($dbc->Errors->Count > 0) return false;\r
-                       return $rs;\r
-               }\r
-               \r
-               $rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option);\r
-               /*\r
-                       $rs =  new COM('ADODB.Recordset');\r
-                       if ($rs) {\r
-                               $rs->Open ($sql, $dbc, $this->_cursor_type,$this->_lock_type, $this->_execute_option);                                                  \r
-                       }\r
-               */\r
-               if ($dbc->Errors->Count > 0) return false;\r
-               if (! $rs) return false;\r
-               \r
-               if ($rs->State == 0) return true; // 0 = adStateClosed means no records returned\r
-               return $rs;\r
-       }\r
-\r
-       \r
-       function BeginTrans() \r
-       { \r
-               if ($this->transOff) return true;\r
-               \r
-               if (isset($this->_thisTransactions))\r
-                       if (!$this->_thisTransactions) return false;\r
-               else {\r
-                       $o = $this->_connectionID->Properties("Transaction DDL");\r
-                       $this->_thisTransactions = $o ? true : false;\r
-                       if (!$o) return false;\r
-               }\r
-               @$this->_connectionID->BeginTrans();\r
-               $this->transCnt += 1;\r
-               return true;\r
-       }\r
-       function CommitTrans($ok=true) \r
-       { \r
-               if (!$ok) return $this->RollbackTrans();\r
-               if ($this->transOff) return true;\r
-               \r
-               @$this->_connectionID->CommitTrans();\r
-               if ($this->transCnt) @$this->transCnt -= 1;\r
-               return true;\r
-       }\r
-       function RollbackTrans() {\r
-               if ($this->transOff) return true;\r
-               @$this->_connectionID->RollbackTrans();\r
-               if ($this->transCnt) @$this->transCnt -= 1;\r
-               return true;\r
-       }\r
-       \r
-       /*      Returns: the last error message from previous database operation        */      \r
-\r
-       function ErrorMsg() \r
-       {\r
-               $errc = $this->_connectionID->Errors;\r
-               if ($errc->Count == 0) return '';\r
-               $err = $errc->Item($errc->Count-1);\r
-               return $err->Description;\r
-       }\r
-       \r
-       function ErrorNo() \r
-       {\r
-               $errc = $this->_connectionID->Errors;\r
-               if ($errc->Count == 0) return 0;\r
-               $err = $errc->Item($errc->Count-1);\r
-               return $err->NativeError;\r
-       }\r
-\r
-       // returns true or false\r
-       function _close()\r
-       {\r
-               if ($this->_connectionID) $this->_connectionID->Close();\r
-               $this->_connectionID = false;\r
-               return true;\r
-       }\r
-       \r
-       \r
-}\r
-       \r
-/*--------------------------------------------------------------------------------------\r
-        Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordSet_ado extends ADORecordSet {  \r
-       \r
-       var $bind = false;\r
-       var $databaseType = "ado";      \r
-       var $dataProvider = "ado";      \r
-       var $_tarr = false; // caches the types\r
-       var $_flds; // and field objects\r
-       var $canSeek = true;\r
-       var $hideErrors = true;\r
-                 \r
-       function ADORecordSet_ado($id,$mode=false)\r
-       {\r
-               if ($mode === false) { \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               $this->fetchMode = $mode;\r
-               return $this->ADORecordSet($id,$mode);\r
-       }\r
-\r
-\r
-       // returns the field object\r
-       function FetchField($fieldOffset = -1) {\r
-               $off=$fieldOffset+1; // offsets begin at 1\r
-               \r
-               $o= new ADOFieldObject();\r
-               $rs = $this->_queryID;\r
-               $f = $rs->Fields($fieldOffset);\r
-               $o->name = $f->Name;\r
-               $t = $f->Type;\r
-               $o->type = $this->MetaType($t);\r
-               $o->max_length = $f->DefinedSize;\r
-               $o->ado_type = $t;\r
-               \r
-\r
-               //print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";\r
-               return $o;\r
-       }\r
-       \r
-       /* Use associative array to get fields array */\r
-       function Fields($colname)\r
-       {\r
-               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];\r
-               if (!$this->bind) {\r
-                       $this->bind = array();\r
-                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                               $o = $this->FetchField($i);\r
-                               $this->bind[strtoupper($o->name)] = $i;\r
-                       }\r
-               }\r
-               \r
-                return $this->fields[$this->bind[strtoupper($colname)]];\r
-       }\r
-\r
-               \r
-       function _initrs()\r
-       {\r
-               $rs = $this->_queryID;\r
-               $this->_numOfRows = $rs->RecordCount;\r
-               \r
-               $f = $rs->Fields;\r
-               $this->_numOfFields = $f->Count;\r
-       }\r
-       \r
-       \r
-        // should only be used to move forward as we normally use forward-only cursors\r
-       function _seek($row)\r
-       {\r
-          $rs = $this->_queryID; \r
-               // absoluteposition doesn't work -- my maths is wrong ?\r
-               //      $rs->AbsolutePosition->$row-2;\r
-               //      return true;\r
-               if ($this->_currentRow > $row) return false;\r
-               @$rs->Move((integer)$row - $this->_currentRow-1); //adBookmarkFirst\r
-               return true;\r
-       }\r
-       \r
-/*\r
-       OLEDB types\r
-       \r
-        enum DBTYPEENUM\r
-       {       DBTYPE_EMPTY    = 0,\r
-       DBTYPE_NULL     = 1,\r
-       DBTYPE_I2       = 2,\r
-       DBTYPE_I4       = 3,\r
-       DBTYPE_R4       = 4,\r
-       DBTYPE_R8       = 5,\r
-       DBTYPE_CY       = 6,\r
-       DBTYPE_DATE     = 7,\r
-       DBTYPE_BSTR     = 8,\r
-       DBTYPE_IDISPATCH        = 9,\r
-       DBTYPE_ERROR    = 10,\r
-       DBTYPE_BOOL     = 11,\r
-       DBTYPE_VARIANT  = 12,\r
-       DBTYPE_IUNKNOWN = 13,\r
-       DBTYPE_DECIMAL  = 14,\r
-       DBTYPE_UI1      = 17,\r
-       DBTYPE_ARRAY    = 0x2000,\r
-       DBTYPE_BYREF    = 0x4000,\r
-       DBTYPE_I1       = 16,\r
-       DBTYPE_UI2      = 18,\r
-       DBTYPE_UI4      = 19,\r
-       DBTYPE_I8       = 20,\r
-       DBTYPE_UI8      = 21,\r
-       DBTYPE_GUID     = 72,\r
-       DBTYPE_VECTOR   = 0x1000,\r
-       DBTYPE_RESERVED = 0x8000,\r
-       DBTYPE_BYTES    = 128,\r
-       DBTYPE_STR      = 129,\r
-       DBTYPE_WSTR     = 130,\r
-       DBTYPE_NUMERIC  = 131,\r
-       DBTYPE_UDT      = 132,\r
-       DBTYPE_DBDATE   = 133,\r
-       DBTYPE_DBTIME   = 134,\r
-       DBTYPE_DBTIMESTAMP      = 135\r
-       \r
-       ADO Types\r
-       \r
-       adEmpty = 0,\r
-       adTinyInt       = 16,\r
-       adSmallInt      = 2,\r
-       adInteger       = 3,\r
-       adBigInt        = 20,\r
-       adUnsignedTinyInt       = 17,\r
-       adUnsignedSmallInt      = 18,\r
-       adUnsignedInt   = 19,\r
-       adUnsignedBigInt        = 21,\r
-       adSingle        = 4,\r
-       adDouble        = 5,\r
-       adCurrency      = 6,\r
-       adDecimal       = 14,\r
-       adNumeric       = 131,\r
-       adBoolean       = 11,\r
-       adError = 10,\r
-       adUserDefined   = 132,\r
-       adVariant       = 12,\r
-       adIDispatch     = 9,\r
-       adIUnknown      = 13,   \r
-       adGUID  = 72,\r
-       adDate  = 7,\r
-       adDBDate        = 133,\r
-       adDBTime        = 134,\r
-       adDBTimeStamp   = 135,\r
-       adBSTR  = 8,\r
-       adChar  = 129,\r
-       adVarChar       = 200,\r
-       adLongVarChar   = 201,\r
-       adWChar = 130,\r
-       adVarWChar      = 202,\r
-       adLongVarWChar  = 203,\r
-       adBinary        = 128,\r
-       adVarBinary     = 204,\r
-       adLongVarBinary = 205,\r
-       adChapter       = 136,\r
-       adFileTime      = 64,\r
-       adDBFileTime    = 137,\r
-       adPropVariant   = 138,\r
-       adVarNumeric    = 139\r
-*/\r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               \r
-               if (!is_numeric($t)) return $t;\r
-               \r
-               switch ($t) {\r
-               case 0:\r
-               case 12: // variant\r
-               case 8: // bstr\r
-               case 129: //char\r
-               case 130: //wc\r
-               case 200: // varc\r
-               case 202:// varWC\r
-               case 128: // bin\r
-               case 204: // varBin\r
-               case 72: // guid\r
-                       if ($len <= $this->blobSize) return 'C';\r
-               \r
-               case 201:\r
-               case 203:\r
-                       return 'X';\r
-               case 128:\r
-               case 204:\r
-               case 205:\r
-                        return 'B';\r
-               case 7:\r
-               case 133: return 'D';\r
-               \r
-               case 134:\r
-               case 135: return 'T';\r
-               \r
-               case 11: return 'L';\r
-               \r
-               case 16://      adTinyInt       = 16,\r
-               case 2://adSmallInt     = 2,\r
-               case 3://adInteger      = 3,\r
-               case 4://adBigInt       = 20,\r
-               case 17://adUnsignedTinyInt     = 17,\r
-               case 18://adUnsignedSmallInt    = 18,\r
-               case 19://adUnsignedInt = 19,\r
-               case 20://adUnsignedBigInt      = 21,\r
-                       return 'I';\r
-               default: return 'N';\r
-               }\r
-       }\r
-       \r
-       // time stamp not supported yet\r
-       function _fetch()\r
-       {       \r
-               $rs = $this->_queryID;\r
-               if (!$rs or $rs->EOF) {\r
-                       $this->fields = false;\r
-                       return false;\r
-               }\r
-               $this->fields = array();\r
-       \r
-               if (!$this->_tarr) {\r
-                       $tarr = array();\r
-                       $flds = array();\r
-                       for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {\r
-                               $f = $rs->Fields($i);\r
-                               $flds[] = $f;\r
-                               $tarr[] = $f->Type;\r
-                       }\r
-                       // bind types and flds only once\r
-                       $this->_tarr = $tarr; \r
-                       $this->_flds = $flds;\r
-               }\r
-               $t = reset($this->_tarr);\r
-               $f = reset($this->_flds);\r
-               \r
-               if ($this->hideErrors)  $olde = error_reporting(E_ERROR|E_CORE_ERROR);// sometimes $f->value be null\r
-               for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {\r
-\r
-                       switch($t) {\r
-                       case 135: // timestamp\r
-                               if (!strlen((string)$f->value)) $this->fields[] = false;\r
-                               else $this->fields[] = adodb_date('Y-m-d H:i:s',(float)$f->value);\r
-                               break;                  \r
-                       case 133:// A date value (yyyymmdd) \r
-                               if ($val = $f->value) {\r
-                                       $this->fields[] = substr($val,0,4).'-'.substr($val,4,2).'-'.substr($val,6,2);\r
-                               } else\r
-                                       $this->fields[] = false;\r
-                               break;\r
-                       case 7: // adDate\r
-                               if (!strlen((string)$f->value)) $this->fields[] = false;\r
-                               else $this->fields[] = adodb_date('Y-m-d',(float)$f->value);\r
-                               break;\r
-                       case 1: // null\r
-                               $this->fields[] = false;\r
-                               break;\r
-                       case 6: // currency is not supported properly;\r
-                               ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>');\r
-                               $this->fields[] = (float) $f->value;\r
-                               break;\r
-                       default:\r
-                               $this->fields[] = $f->value; \r
-                               break;\r
-                       }\r
-                       //print " $f->value $t, ";\r
-                       $f = next($this->_flds);\r
-                       $t = next($this->_tarr);\r
-               } // for\r
-               if ($this->hideErrors) error_reporting($olde);\r
-               @$rs->MoveNext(); // @ needed for some versions of PHP!\r
-               \r
-               if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
-                       $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);\r
-               }\r
-               return true;\r
-       }\r
-       \r
-               function NextRecordSet()\r
-               {\r
-                       $rs = $this->_queryID;\r
-                       $this->_queryID = $rs->NextRecordSet();\r
-                       //$this->_queryID = $this->_QueryId->NextRecordSet();\r
-                       if ($this->_queryID == null) return false;\r
-                       \r
-                       $this->_currentRow = -1;\r
-                       $this->_currentPage = -1;\r
-                       $this->bind = false;\r
-                       $this->fields = false;\r
-                       $this->_flds = false;\r
-                       $this->_tarr = false;\r
-                       \r
-                       $this->_inited = false;\r
-                       $this->Init();\r
-                       return true;\r
-               }\r
-\r
-       function _close() {\r
-               $this->_flds = false;\r
-               @$this->_queryID->Close();// by Pete Dishman (peterd@telephonetics.co.uk)\r
-               $this->_queryID = false;        \r
-       }\r
-\r
-}\r
-\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+       Microsoft ADO data driver. Requires ADO. Works only on MS Windows.
+*/
+  define("_ADODB_ADO_LAYER", 1 );
+/*--------------------------------------------------------------------------------------
+--------------------------------------------------------------------------------------*/
+  
+class ADODB_ado extends ADOConnection {
+       var $databaseType = "ado";      
+       var $_bindInputArray = false;
+       var $fmtDate = "'Y-m-d'";
+       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $dataProvider = "ado";      
+       var $hasAffectedRows = true;
+       var $adoParameterType = 201; // 201 = long varchar, 203=long wide varchar, 205 = long varbinary
+       var $_affectedRows = false;
+       var $_thisTransactions;
+       var $_cursor_type = 3; // 3=adOpenStatic,0=adOpenForwardOnly,1=adOpenKeyset,2=adOpenDynamic
+       var $_cursor_location = 3; // 2=adUseServer, 3 = adUseClient;
+       var $_lock_type = -1;
+       var $_execute_option = -1;
+       var $poorAffectedRows = true; 
+       var $charPage;
+               
+       function ADODB_ado() 
+       {       
+               $this->_affectedRows = new VARIANT;
+       }
+
+       function ServerInfo()
+       {
+               if (!empty($this->_connectionID)) $desc = $this->_connectionID->provider;
+               return array('description' => $desc, 'version' => '');
+       }
+       
+       function _affectedrows()
+       {
+                       return $this->_affectedRows->value;
+       }
+       
+       // you can also pass a connection string like this:
+       //
+       // $DB->Connect('USER ID=sa;PASSWORD=pwd;SERVER=mangrove;DATABASE=ai',false,false,'SQLOLEDB');
+       function _connect($argHostname, $argUsername, $argPassword, $argProvider= 'MSDASQL')
+       {
+               $u = 'UID';
+               $p = 'PWD';
+       
+               if (!empty($this->charPage))
+                       $dbc = new COM('ADODB.Connection',null,$this->charPage);
+               else
+                       $dbc = new COM('ADODB.Connection');
+                       
+               if (! $dbc) return false;
+
+               /* special support if provider is mssql or access */
+               if ($argProvider=='mssql') {
+                       $u = 'User Id';  //User parameter name for OLEDB
+                       $p = 'Password'; 
+                       $argProvider = "SQLOLEDB"; // SQL Server Provider
+                       
+                       // not yet
+                       //if ($argDatabasename) $argHostname .= ";Initial Catalog=$argDatabasename";
+                       
+                       //use trusted conection for SQL if username not specified
+                       if (!$argUsername) $argHostname .= ";Trusted_Connection=Yes";
+               } else if ($argProvider=='access')
+                       $argProvider = "Microsoft.Jet.OLEDB.4.0"; // Microsoft Jet Provider
+               
+               if ($argProvider) $dbc->Provider = $argProvider;        
+               
+               if ($argUsername) $argHostname .= ";$u=$argUsername";
+               if ($argPassword)$argHostname .= ";$p=$argPassword";
+               
+               if ($this->debug) ADOConnection::outp( "Host=".$argHostname."<BR>\n version=$dbc->version");
+               // @ added below for php 4.0.1 and earlier
+               @$dbc->Open((string) $argHostname);
+               
+               $this->_connectionID = $dbc;
+               
+               $dbc->CursorLocation = $this->_cursor_location;
+               return  $dbc->State > 0;
+       }
+       
+       // returns true or false
+       function _pconnect($argHostname, $argUsername, $argPassword, $argProvider='MSDASQL')
+       {
+               return $this->_connect($argHostname,$argUsername,$argPassword,$argProvider);
+       }       
+       
+/*
+       adSchemaCatalogs        = 1,
+       adSchemaCharacterSets   = 2,
+       adSchemaCollations      = 3,
+       adSchemaColumns = 4,
+       adSchemaCheckConstraints        = 5,
+       adSchemaConstraintColumnUsage   = 6,
+       adSchemaConstraintTableUsage    = 7,
+       adSchemaKeyColumnUsage  = 8,
+       adSchemaReferentialContraints   = 9,
+       adSchemaTableConstraints        = 10,
+       adSchemaColumnsDomainUsage      = 11,
+       adSchemaIndexes = 12,
+       adSchemaColumnPrivileges        = 13,
+       adSchemaTablePrivileges = 14,
+       adSchemaUsagePrivileges = 15,
+       adSchemaProcedures      = 16,
+       adSchemaSchemata        = 17,
+       adSchemaSQLLanguages    = 18,
+       adSchemaStatistics      = 19,
+       adSchemaTables  = 20,
+       adSchemaTranslations    = 21,
+       adSchemaProviderTypes   = 22,
+       adSchemaViews   = 23,
+       adSchemaViewColumnUsage = 24,
+       adSchemaViewTableUsage  = 25,
+       adSchemaProcedureParameters     = 26,
+       adSchemaForeignKeys     = 27,
+       adSchemaPrimaryKeys     = 28,
+       adSchemaProcedureColumns        = 29,
+       adSchemaDBInfoKeywords  = 30,
+       adSchemaDBInfoLiterals  = 31,
+       adSchemaCubes   = 32,
+       adSchemaDimensions      = 33,
+       adSchemaHierarchies     = 34,
+       adSchemaLevels  = 35,
+       adSchemaMeasures        = 36,
+       adSchemaProperties      = 37,
+       adSchemaMembers = 38
+
+*/
+       
+       function &MetaTables()
+       {
+               $arr= array();
+               $dbc = $this->_connectionID;
+               
+               $adors=@$dbc->OpenSchema(20);//tables
+               if ($adors){
+                       $f = $adors->Fields(2);//table/view name
+                       $t = $adors->Fields(3);//table type
+                       while (!$adors->EOF){
+                               $tt=substr($t->value,0,6);
+                               if ($tt!='SYSTEM' && $tt !='ACCESS')
+                                       $arr[]=$f->value;
+                               //print $f->value . ' ' . $t->value.'<br>';
+                               $adors->MoveNext();
+                       }
+                       $adors->Close();
+               }
+               
+               return $arr;
+       }
+       
+       function &MetaColumns($table)
+       {
+               $table = strtoupper($table);
+               $arr= array();
+               $dbc = $this->_connectionID;
+               
+               $adors=@$dbc->OpenSchema(4);//tables
+       
+               if ($adors){
+                       $t = $adors->Fields(2);//table/view name
+                       while (!$adors->EOF){
+                               
+                               
+                               if (strtoupper($t->Value) == $table) {
+                               
+                                       $fld = new ADOFieldObject();
+                                       $c = $adors->Fields(3);
+                                       $fld->name = $c->Value;
+                                       $fld->type = 'CHAR'; // cannot discover type in ADO!
+                                       $fld->max_length = -1;
+                                       $arr[strtoupper($fld->name)]=$fld;
+                               }
+               
+                               $adors->MoveNext();
+                       }
+                       $adors->Close();
+               }
+               
+               return $arr;
+       }
+       
+
+
+       
+       /* returns queryID or false */
+       function &_query($sql,$inputarr=false) 
+       {
+               
+               $dbc = $this->_connectionID;
+               
+       //      return rs       
+               if ($inputarr) {
+                       
+                       if (!empty($this->charPage))
+                               $oCmd = new COM('ADODB.Command',null,$this->charPage);
+                       else
+                               $oCmd = new COM('ADODB.Command');
+                       $oCmd->ActiveConnection = $dbc;
+                       $oCmd->CommandText = $sql;
+                       $oCmd->CommandType = 1;
+
+                       foreach($inputarr as $val) {
+                               // name, type, direction 1 = input, len,
+                               $this->adoParameterType = 130;
+                               $p = $oCmd->CreateParameter('name',$this->adoParameterType,1,strlen($val),$val);
+                               //print $p->Type.' '.$p->value;
+                               $oCmd->Parameters->Append($p);
+                       }
+                       $p = false;
+                       $rs = $oCmd->Execute();
+                       $e = $dbc->Errors;
+                       if ($dbc->Errors->Count > 0) return false;
+                       return $rs;
+               }
+               
+               $rs = @$dbc->Execute($sql,$this->_affectedRows, $this->_execute_option);
+               /*
+                       $rs =  new COM('ADODB.Recordset');
+                       if ($rs) {
+                               $rs->Open ($sql, $dbc, $this->_cursor_type,$this->_lock_type, $this->_execute_option);                                                  
+                       }
+               */
+               if ($dbc->Errors->Count > 0) return false;
+               if (! $rs) return false;
+               
+               if ($rs->State == 0) return true; // 0 = adStateClosed means no records returned
+               return $rs;
+       }
+
+       
+       function BeginTrans() 
+       { 
+               if ($this->transOff) return true;
+               
+               if (isset($this->_thisTransactions))
+                       if (!$this->_thisTransactions) return false;
+               else {
+                       $o = $this->_connectionID->Properties("Transaction DDL");
+                       $this->_thisTransactions = $o ? true : false;
+                       if (!$o) return false;
+               }
+               @$this->_connectionID->BeginTrans();
+               $this->transCnt += 1;
+               return true;
+       }
+       function CommitTrans($ok=true) 
+       { 
+               if (!$ok) return $this->RollbackTrans();
+               if ($this->transOff) return true;
+               
+               @$this->_connectionID->CommitTrans();
+               if ($this->transCnt) @$this->transCnt -= 1;
+               return true;
+       }
+       function RollbackTrans() {
+               if ($this->transOff) return true;
+               @$this->_connectionID->RollbackTrans();
+               if ($this->transCnt) @$this->transCnt -= 1;
+               return true;
+       }
+       
+       /*      Returns: the last error message from previous database operation        */      
+
+       function ErrorMsg() 
+       {
+               $errc = $this->_connectionID->Errors;
+               if ($errc->Count == 0) return '';
+               $err = $errc->Item($errc->Count-1);
+               return $err->Description;
+       }
+       
+       function ErrorNo() 
+       {
+               $errc = $this->_connectionID->Errors;
+               if ($errc->Count == 0) return 0;
+               $err = $errc->Item($errc->Count-1);
+               return $err->NativeError;
+       }
+
+       // returns true or false
+       function _close()
+       {
+               if ($this->_connectionID) $this->_connectionID->Close();
+               $this->_connectionID = false;
+               return true;
+       }
+       
+       
+}
+       
+/*--------------------------------------------------------------------------------------
+        Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_ado extends ADORecordSet {  
+       
+       var $bind = false;
+       var $databaseType = "ado";      
+       var $dataProvider = "ado";      
+       var $_tarr = false; // caches the types
+       var $_flds; // and field objects
+       var $canSeek = true;
+       var $hideErrors = true;
+                 
+       function ADORecordSet_ado($id,$mode=false)
+       {
+               if ($mode === false) { 
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               $this->fetchMode = $mode;
+               return $this->ADORecordSet($id,$mode);
+       }
+
+
+       // returns the field object
+       function FetchField($fieldOffset = -1) {
+               $off=$fieldOffset+1; // offsets begin at 1
+               
+               $o= new ADOFieldObject();
+               $rs = $this->_queryID;
+               $f = $rs->Fields($fieldOffset);
+               $o->name = $f->Name;
+               $t = $f->Type;
+               $o->type = $this->MetaType($t);
+               $o->max_length = $f->DefinedSize;
+               $o->ado_type = $t;
+               
+
+               //print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";
+               return $o;
+       }
+       
+       /* Use associative array to get fields array */
+       function Fields($colname)
+       {
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+               if (!$this->bind) {
+                       $this->bind = array();
+                       for ($i=0; $i < $this->_numOfFields; $i++) {
+                               $o = $this->FetchField($i);
+                               $this->bind[strtoupper($o->name)] = $i;
+                       }
+               }
+               
+                return $this->fields[$this->bind[strtoupper($colname)]];
+       }
+
+               
+       function _initrs()
+       {
+               $rs = $this->_queryID;
+               $this->_numOfRows = $rs->RecordCount;
+               
+               $f = $rs->Fields;
+               $this->_numOfFields = $f->Count;
+       }
+       
+       
+        // should only be used to move forward as we normally use forward-only cursors
+       function _seek($row)
+       {
+          $rs = $this->_queryID; 
+               // absoluteposition doesn't work -- my maths is wrong ?
+               //      $rs->AbsolutePosition->$row-2;
+               //      return true;
+               if ($this->_currentRow > $row) return false;
+               @$rs->Move((integer)$row - $this->_currentRow-1); //adBookmarkFirst
+               return true;
+       }
+       
+/*
+       OLEDB types
+       
+        enum DBTYPEENUM
+       {       DBTYPE_EMPTY    = 0,
+       DBTYPE_NULL     = 1,
+       DBTYPE_I2       = 2,
+       DBTYPE_I4       = 3,
+       DBTYPE_R4       = 4,
+       DBTYPE_R8       = 5,
+       DBTYPE_CY       = 6,
+       DBTYPE_DATE     = 7,
+       DBTYPE_BSTR     = 8,
+       DBTYPE_IDISPATCH        = 9,
+       DBTYPE_ERROR    = 10,
+       DBTYPE_BOOL     = 11,
+       DBTYPE_VARIANT  = 12,
+       DBTYPE_IUNKNOWN = 13,
+       DBTYPE_DECIMAL  = 14,
+       DBTYPE_UI1      = 17,
+       DBTYPE_ARRAY    = 0x2000,
+       DBTYPE_BYREF    = 0x4000,
+       DBTYPE_I1       = 16,
+       DBTYPE_UI2      = 18,
+       DBTYPE_UI4      = 19,
+       DBTYPE_I8       = 20,
+       DBTYPE_UI8      = 21,
+       DBTYPE_GUID     = 72,
+       DBTYPE_VECTOR   = 0x1000,
+       DBTYPE_RESERVED = 0x8000,
+       DBTYPE_BYTES    = 128,
+       DBTYPE_STR      = 129,
+       DBTYPE_WSTR     = 130,
+       DBTYPE_NUMERIC  = 131,
+       DBTYPE_UDT      = 132,
+       DBTYPE_DBDATE   = 133,
+       DBTYPE_DBTIME   = 134,
+       DBTYPE_DBTIMESTAMP      = 135
+       
+       ADO Types
+       
+       adEmpty = 0,
+       adTinyInt       = 16,
+       adSmallInt      = 2,
+       adInteger       = 3,
+       adBigInt        = 20,
+       adUnsignedTinyInt       = 17,
+       adUnsignedSmallInt      = 18,
+       adUnsignedInt   = 19,
+       adUnsignedBigInt        = 21,
+       adSingle        = 4,
+       adDouble        = 5,
+       adCurrency      = 6,
+       adDecimal       = 14,
+       adNumeric       = 131,
+       adBoolean       = 11,
+       adError = 10,
+       adUserDefined   = 132,
+       adVariant       = 12,
+       adIDispatch     = 9,
+       adIUnknown      = 13,   
+       adGUID  = 72,
+       adDate  = 7,
+       adDBDate        = 133,
+       adDBTime        = 134,
+       adDBTimeStamp   = 135,
+       adBSTR  = 8,
+       adChar  = 129,
+       adVarChar       = 200,
+       adLongVarChar   = 201,
+       adWChar = 130,
+       adVarWChar      = 202,
+       adLongVarWChar  = 203,
+       adBinary        = 128,
+       adVarBinary     = 204,
+       adLongVarBinary = 205,
+       adChapter       = 136,
+       adFileTime      = 64,
+       adDBFileTime    = 137,
+       adPropVariant   = 138,
+       adVarNumeric    = 139
+*/
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               
+               if (!is_numeric($t)) return $t;
+               
+               switch ($t) {
+               case 0:
+               case 12: // variant
+               case 8: // bstr
+               case 129: //char
+               case 130: //wc
+               case 200: // varc
+               case 202:// varWC
+               case 128: // bin
+               case 204: // varBin
+               case 72: // guid
+                       if ($len <= $this->blobSize) return 'C';
+               
+               case 201:
+               case 203:
+                       return 'X';
+               case 128:
+               case 204:
+               case 205:
+                        return 'B';
+               case 7:
+               case 133: return 'D';
+               
+               case 134:
+               case 135: return 'T';
+               
+               case 11: return 'L';
+               
+               case 16://      adTinyInt       = 16,
+               case 2://adSmallInt     = 2,
+               case 3://adInteger      = 3,
+               case 4://adBigInt       = 20,
+               case 17://adUnsignedTinyInt     = 17,
+               case 18://adUnsignedSmallInt    = 18,
+               case 19://adUnsignedInt = 19,
+               case 20://adUnsignedBigInt      = 21,
+                       return 'I';
+               default: return 'N';
+               }
+       }
+       
+       // time stamp not supported yet
+       function _fetch()
+       {       
+               $rs = $this->_queryID;
+               if (!$rs or $rs->EOF) {
+                       $this->fields = false;
+                       return false;
+               }
+               $this->fields = array();
+       
+               if (!$this->_tarr) {
+                       $tarr = array();
+                       $flds = array();
+                       for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {
+                               $f = $rs->Fields($i);
+                               $flds[] = $f;
+                               $tarr[] = $f->Type;
+                       }
+                       // bind types and flds only once
+                       $this->_tarr = $tarr; 
+                       $this->_flds = $flds;
+               }
+               $t = reset($this->_tarr);
+               $f = reset($this->_flds);
+               
+               if ($this->hideErrors)  $olde = error_reporting(E_ERROR|E_CORE_ERROR);// sometimes $f->value be null
+               for ($i=0,$max = $this->_numOfFields; $i < $max; $i++) {
+
+                       switch($t) {
+                       case 135: // timestamp
+                               if (!strlen((string)$f->value)) $this->fields[] = false;
+                               else $this->fields[] = adodb_date('Y-m-d H:i:s',(float)$f->value);
+                               break;                  
+                       case 133:// A date value (yyyymmdd) 
+                               if ($val = $f->value) {
+                                       $this->fields[] = substr($val,0,4).'-'.substr($val,4,2).'-'.substr($val,6,2);
+                               } else
+                                       $this->fields[] = false;
+                               break;
+                       case 7: // adDate
+                               if (!strlen((string)$f->value)) $this->fields[] = false;
+                               else $this->fields[] = adodb_date('Y-m-d',(float)$f->value);
+                               break;
+                       case 1: // null
+                               $this->fields[] = false;
+                               break;
+                       case 6: // currency is not supported properly;
+                               ADOConnection::outp( '<b>'.$f->Name.': currency type not supported by PHP</b>');
+                               $this->fields[] = (float) $f->value;
+                               break;
+                       default:
+                               $this->fields[] = $f->value; 
+                               break;
+                       }
+                       //print " $f->value $t, ";
+                       $f = next($this->_flds);
+                       $t = next($this->_tarr);
+               } // for
+               if ($this->hideErrors) error_reporting($olde);
+               @$rs->MoveNext(); // @ needed for some versions of PHP!
+               
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+                       $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
+               }
+               return true;
+       }
+       
+               function NextRecordSet()
+               {
+                       $rs = $this->_queryID;
+                       $this->_queryID = $rs->NextRecordSet();
+                       //$this->_queryID = $this->_QueryId->NextRecordSet();
+                       if ($this->_queryID == null) return false;
+                       
+                       $this->_currentRow = -1;
+                       $this->_currentPage = -1;
+                       $this->bind = false;
+                       $this->fields = false;
+                       $this->_flds = false;
+                       $this->_tarr = false;
+                       
+                       $this->_inited = false;
+                       $this->Init();
+                       return true;
+               }
+
+       function _close() {
+               $this->_flds = false;
+               @$this->_queryID->Close();// by Pete Dishman (peterd@telephonetics.co.uk)
+               $this->_queryID = false;        
+       }
+
+}
+
 ?>
\ No newline at end of file
index 946714defab5c7da5d3c9c4c149ae49e875729d4..74b37a5776054c6ef1847c8b69ca1edab58cc3cb 100644 (file)
@@ -1,46 +1,46 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-Released under both BSD license and Lesser GPL library license. \r
-Whenever there is any discrepancy between the two licenses, \r
-the BSD license will take precedence. See License.txt. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-       Microsoft Access ADO data driver. Requires ADO and ODBC. Works only on MS Windows.\r
-*/\r
-\r
-if (!defined('_ADODB_ADO_LAYER')) {\r
-       include(ADODB_DIR."/drivers/adodb-ado.inc.php");\r
-}\r
-\r
-class  ADODB_ado_access extends ADODB_ado {    \r
-       var $databaseType = 'ado_access';\r
-       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE\r
-       var $fmtDate = "#Y-m-d#";\r
-       var $fmtTimeStamp = "#Y-m-d h:i:sA#";// note no comma\r
-       var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";\r
-       var $sysTimeStamp = 'NOW';\r
-       var $hasTransactions = false;\r
-       \r
-       function ADODB_ado_access()\r
-       {\r
-               $this->ADODB_ado();\r
-       }\r
-       \r
-       function BeginTrans() { return false;}\r
-\r
-}\r
-\r
\r
-class  ADORecordSet_ado_access extends ADORecordSet_ado {      \r
-       \r
-       var $databaseType = "ado_access";               \r
-       \r
-       function ADORecordSet_ado_access($id,$mode=false)\r
-       {\r
-               return $this->ADORecordSet_ado($id,$mode);\r
-       }\r
-}\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+Released under both BSD license and Lesser GPL library license. 
+Whenever there is any discrepancy between the two licenses, 
+the BSD license will take precedence. See License.txt. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+       Microsoft Access ADO data driver. Requires ADO and ODBC. Works only on MS Windows.
+*/
+
+if (!defined('_ADODB_ADO_LAYER')) {
+       include(ADODB_DIR."/drivers/adodb-ado.inc.php");
+}
+
+class  ADODB_ado_access extends ADODB_ado {    
+       var $databaseType = 'ado_access';
+       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE
+       var $fmtDate = "#Y-m-d#";
+       var $fmtTimeStamp = "#Y-m-d h:i:sA#";// note no comma
+       var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
+       var $sysTimeStamp = 'NOW';
+       var $hasTransactions = false;
+       
+       function ADODB_ado_access()
+       {
+               $this->ADODB_ado();
+       }
+       
+       function BeginTrans() { return false;}
+
+}
+
+class  ADORecordSet_ado_access extends ADORecordSet_ado {      
+       
+       var $databaseType = "ado_access";               
+       
+       function ADORecordSet_ado_access($id,$mode=false)
+       {
+               return $this->ADORecordSet_ado($id,$mode);
+       }
+}
 ?>
\ No newline at end of file
index e09bca54d1aba8cc2321b7a5d2190ec58c914564..fec181abc88e3d4a49bed14556a9cb832d8475c4 100644 (file)
@@ -1,62 +1,62 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Microsoft SQL Server ADO data driver. Requires ADO and MSSQL client. \r
-  Works only on MS Windows.\r
-  \r
-  It is normally better to use the mssql driver directly because it is much faster. \r
-  This file is only a technology demonstration and for test purposes.\r
-*/\r
-\r
-if (!defined('_ADODB_ADO_LAYER')) {\r
-       include(ADODB_DIR."/drivers/adodb-ado.inc.php");\r
-}\r
-\r
-class  ADODB_ado_mssql extends ADODB_ado {     \r
-       var $databaseType = 'ado_mssql';\r
-       var $hasTop = 'top';\r
-       var $sysDate = 'GetDate()';\r
-       var $sysTimeStamp = 'GetDate()';\r
-       var $leftOuter = '*=';\r
-       var $rightOuter = '=*';\r
-       var $ansiOuter = true; // for mssql7 or later\r
-       var $substr = "substring";\r
-       var $length = 'len';\r
-       var $upperCase = 'upper';\r
-       \r
-       //var $_inTransaction = 1; // always open recordsets, so no transaction problems.\r
-       \r
-       function ADODB_ado_mssql()\r
-       {\r
-               $this->ADODB_ado();\r
-       }\r
-       \r
-       function _insertid()\r
-       {\r
-               return $this->GetOne('select @@identity');\r
-       }\r
-       \r
-       function _affectedrows()\r
-       {\r
-               return $this->GetOne('select @@rowcount');\r
-       }\r
-       \r
-}\r
\r
-class  ADORecordSet_ado_mssql extends ADORecordSet_ado {       \r
-       \r
-       var $databaseType = 'ado_mssql';\r
-       \r
-       function ADORecordSet_ado_mssql($id,$mode=false)\r
-       {\r
-               return $this->ADORecordSet_ado($id,$mode);\r
-       }\r
-}\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Microsoft SQL Server ADO data driver. Requires ADO and MSSQL client. 
+  Works only on MS Windows.
+  
+  It is normally better to use the mssql driver directly because it is much faster. 
+  This file is only a technology demonstration and for test purposes.
+*/
+
+if (!defined('_ADODB_ADO_LAYER')) {
+       include(ADODB_DIR."/drivers/adodb-ado.inc.php");
+}
+
+class  ADODB_ado_mssql extends ADODB_ado {     
+       var $databaseType = 'ado_mssql';
+       var $hasTop = 'top';
+       var $sysDate = 'GetDate()';
+       var $sysTimeStamp = 'GetDate()';
+       var $leftOuter = '*=';
+       var $rightOuter = '=*';
+       var $ansiOuter = true; // for mssql7 or later
+       var $substr = "substring";
+       var $length = 'len';
+       var $upperCase = 'upper';
+       
+       //var $_inTransaction = 1; // always open recordsets, so no transaction problems.
+       
+       function ADODB_ado_mssql()
+       {
+               $this->ADODB_ado();
+       }
+       
+       function _insertid()
+       {
+               return $this->GetOne('select @@identity');
+       }
+       
+       function _affectedrows()
+       {
+               return $this->GetOne('select @@rowcount');
+       }
+       
+}
+class  ADORecordSet_ado_mssql extends ADORecordSet_ado {       
+       
+       var $databaseType = 'ado_mssql';
+       
+       function ADORecordSet_ado_mssql($id,$mode=false)
+       {
+               return $this->ADORecordSet_ado($id,$mode);
+       }
+}
 ?>
\ No newline at end of file
index 8598e16e7e70c985205ffd6ff4a7846dc5637062..4030c7189beacb5d526e2c04768ef0f21cb06764 100644 (file)
@@ -1,79 +1,79 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Support Borland Interbase 6.5 and later\r
-\r
-*/\r
-\r
-include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");\r
-\r
-class ADODB_borland_ibase extends ADODB_ibase {\r
-       var $databaseType = "borland_ibase";    \r
-       \r
-       function ADODB_borland_ibase()\r
-       {\r
-               $this->ADODB_ibase();\r
-       }\r
-       \r
-       function ServerInfo()\r
-       {\r
-               $arr['dialect'] = $this->dialect;\r
-               switch($arr['dialect']) {\r
-               case '': \r
-               case '1': $s = 'Interbase 6.5, Dialect 1'; break;\r
-               case '2': $s = 'Interbase 6.5, Dialect 2'; break;\r
-               default:\r
-               case '3': $s = 'Interbase 6.5, Dialect 3'; break;\r
-               }\r
-               $arr['version'] = '6.5';\r
-               $arr['description'] = $s;\r
-               return $arr;\r
-       }\r
-       \r
-       // Note that Interbase 6.5 uses ROWS instead - don't you love forking wars!\r
-       //              SELECT col1, col2 FROM table ROWS 5 -- get 5 rows \r
-       //              SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2\r
-       // Firebird uses\r
-       //              SELECT FIRST 5 SKIP 2 col1, col2 FROM TABLE\r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)\r
-       {\r
-               if ($nrows > 0) {\r
-                       if ($offset <= 0) $str = " ROWS $nrows "; \r
-                       else {\r
-                               $a = $offset+1;\r
-                               $b = $offset+$nrows;\r
-                               $str = " ROWS $a TO $b";\r
-                       }\r
-               } else {\r
-                       // ok, skip \r
-                       $a = $offset + 1;\r
-                       $str = " ROWS $a TO 999999999"; // 999 million\r
-               }\r
-               $sql .= $str;\r
-               \r
-               return ($secs2cache) ? \r
-                               $this->CacheExecute($secs2cache,$sql,$inputarr)\r
-                       :\r
-                               $this->Execute($sql,$inputarr);\r
-       }\r
-       \r
-};\r
\r
-\r
-class  ADORecordSet_borland_ibase extends ADORecordSet_ibase { \r
-       \r
-       var $databaseType = "borland_ibase";            \r
-       \r
-       function ADORecordSet_borland_ibase($id,$mode=false)\r
-       {\r
-               $this->ADORecordSet_ibase($id,$mode);\r
-       }\r
-}\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Support Borland Interbase 6.5 and later
+
+*/
+
+include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");
+
+class ADODB_borland_ibase extends ADODB_ibase {
+       var $databaseType = "borland_ibase";    
+       
+       function ADODB_borland_ibase()
+       {
+               $this->ADODB_ibase();
+       }
+       
+       function ServerInfo()
+       {
+               $arr['dialect'] = $this->dialect;
+               switch($arr['dialect']) {
+               case '': 
+               case '1': $s = 'Interbase 6.5, Dialect 1'; break;
+               case '2': $s = 'Interbase 6.5, Dialect 2'; break;
+               default:
+               case '3': $s = 'Interbase 6.5, Dialect 3'; break;
+               }
+               $arr['version'] = '6.5';
+               $arr['description'] = $s;
+               return $arr;
+       }
+       
+       // Note that Interbase 6.5 uses ROWS instead - don't you love forking wars!
+       //              SELECT col1, col2 FROM table ROWS 5 -- get 5 rows 
+       //              SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2
+       // Firebird uses
+       //              SELECT FIRST 5 SKIP 2 col1, col2 FROM TABLE
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
+       {
+               if ($nrows > 0) {
+                       if ($offset <= 0) $str = " ROWS $nrows "; 
+                       else {
+                               $a = $offset+1;
+                               $b = $offset+$nrows;
+                               $str = " ROWS $a TO $b";
+                       }
+               } else {
+                       // ok, skip 
+                       $a = $offset + 1;
+                       $str = " ROWS $a TO 999999999"; // 999 million
+               }
+               $sql .= $str;
+               
+               return ($secs2cache) ? 
+                               $this->CacheExecute($secs2cache,$sql,$inputarr)
+                       :
+                               $this->Execute($sql,$inputarr);
+       }
+       
+};
+
+class  ADORecordSet_borland_ibase extends ADORecordSet_ibase { 
+       
+       var $databaseType = "borland_ibase";            
+       
+       function ADORecordSet_borland_ibase($id,$mode=false)
+       {
+               $this->ADORecordSet_ibase($id,$mode);
+       }
+}
 ?>
\ No newline at end of file
index d0b61014c1f6931156c74f1eb6911a8d95e8113d..a444d9e0f93b26eeea153b87db9dd1e1e2e475a0 100644 (file)
-<?php\r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 4.\r
-  \r
-  Currently unsupported: MetaDatabases, MetaTables and MetaColumns, and also inputarr in Execute.\r
-  Native types have been converted to MetaTypes.\r
-  Transactions not supported yet.\r
-*/ \r
-\r
-if (! defined("_ADODB_CSV_LAYER")) {\r
- define("_ADODB_CSV_LAYER", 1 );\r
-\r
-include_once(ADODB_DIR.'/adodb-csvlib.inc.php');\r
\r
-class ADODB_csv extends ADOConnection {\r
-       var $databaseType = 'csv';\r
-       var $databaseProvider = 'csv';\r
-       var $hasInsertID = true;\r
-       var $hasAffectedRows = true;    \r
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
-       var $_affectedrows=0;\r
-       var $_insertid=0;\r
-       var $_url;\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $hasTransactions = false;\r
-       var $_errorNo = false;\r
-       \r
-       function ADODB_csv() \r
-       {               \r
-       }\r
-       \r
-       function _insertid()\r
-       {\r
-                       return $this->_insertid;\r
-       }\r
-       \r
-       function _affectedrows()\r
-       {\r
-                       return $this->_affectedrows;\r
-       }\r
-  \r
-       function &MetaDatabases()\r
-       {\r
-               return false;\r
-       }\r
-\r
-       \r
-       // returns true or false\r
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;\r
-               $this->_url = $argHostname;\r
-               return true;    \r
-       }\r
-       \r
-       // returns true or false\r
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;\r
-               $this->_url = $argHostname;\r
-               return true;\r
-       }\r
-       \r
-       function &MetaColumns($table) \r
-       {\r
-               return false;\r
-       }\r
-               \r
-               \r
-       // parameters use PostgreSQL convention, not MySQL\r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $url = $this->_url.'?sql='.urlencode($sql)."&nrows=$nrows&fetch=".\r
-                       (($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE).\r
-                       "&offset=$offset";\r
-               $err = false;\r
-               $rs = csv2rs($url,$err,false);\r
-               \r
-               if ($this->debug) print "$url<br><i>$err</i><br>";\r
-\r
-               $at = strpos($err,'::::');\r
-               if ($at === false) {\r
-                       $this->_errorMsg = $err;\r
-                       $this->_errorNo = (integer)$err;\r
-               } else {\r
-                       $this->_errorMsg = substr($err,$at+4,1024);\r
-                       $this->_errorNo = -9999;\r
-               }\r
-               if ($this->_errorNo) \r
-                       if ($fn = $this->raiseErrorFn) {\r
-                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,'');\r
-                       }\r
-                       \r
-               if (is_object($rs)) {   \r
-               \r
-                       $rs->databaseType='csv';                \r
-                       $rs->fetchMode = ($this->fetchMode !== false) ?  $this->fetchMode : $ADODB_FETCH_MODE;\r
-                       $rs->connection = &$this;\r
-               }\r
-               return $rs;\r
-       }\r
-       \r
-       // returns queryID or false\r
-       function &_Execute($sql,$inputarr=false)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               if (!$this->_bindInputArray && $inputarr) {\r
-                       $sqlarr = explode('?',$sql);\r
-                       $sql = '';\r
-                       $i = 0;\r
-                       foreach($inputarr as $v) {\r
-\r
-                               $sql .= $sqlarr[$i];\r
-                               if (gettype($v) == 'string')\r
-                                       $sql .= $this->qstr($v);\r
-                               else if ($v === null)\r
-                                       $sql .= 'NULL';\r
-                               else\r
-                                       $sql .= $v;\r
-                               $i += 1;\r
-       \r
-                       }\r
-                       $sql .= $sqlarr[$i];\r
-                       if ($i+1 != sizeof($sqlarr))    \r
-                               print "Input Array does not match ?: ".htmlspecialchars($sql);\r
-                       $inputarr = false;\r
-               }\r
-               \r
-               $url =  $this->_url.'?sql='.urlencode($sql)."&fetch=".\r
-                       (($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE);\r
-               $err = false;\r
-               \r
-               \r
-               $rs = csv2rs($url,$err,false);\r
-               if ($this->debug) print urldecode($url)."<br><i>$err</i><br>";\r
-               $at = strpos($err,'::::');\r
-               if ($at === false) {            \r
-                       $this->_errorMsg = $err;\r
-                       $this->_errorNo = (integer)$err;\r
-               } else {\r
-                       $this->_errorMsg = substr($err,$at+4,1024);\r
-                       $this->_errorNo = -9999;\r
-               }\r
-               \r
-               if ($this->_errorNo) \r
-                       if ($fn = $this->raiseErrorFn) {\r
-                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr);\r
-                       }\r
-               if (is_object($rs)) {\r
-                       $rs->fetchMode = ($this->fetchMode !== false) ?  $this->fetchMode : $ADODB_FETCH_MODE;\r
-                       \r
-                       $this->_affectedrows = $rs->affectedrows;\r
-                       $this->_insertid = $rs->insertid;\r
-                       $rs->databaseType='csv';\r
-                       $rs->connection = &$this;\r
-               }\r
-               return $rs;\r
-       }\r
-\r
-       /*      Returns: the last error message from previous database operation        */      \r
-       function ErrorMsg() \r
-       {\r
-                       return $this->_errorMsg;\r
-       }\r
-       \r
-       /*      Returns: the last error number from previous database operation */      \r
-       function ErrorNo() \r
-       {\r
-               return $this->_errorNo;\r
-       }\r
-       \r
-       // returns true or false\r
-       function _close()\r
-       {\r
-               return true;\r
-       }\r
-} // class\r
-\r
-class ADORecordset_csv extends ADORecordset {\r
-       function ADORecordset_csv($id,$mode=false)\r
-       {\r
-               $this->ADORecordset($id,$mode);\r
-       }\r
-       \r
-       function _close()\r
-       {\r
-               return true;\r
-       }\r
-}\r
-\r
-} // define\r
-       \r
+<?php
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 4.
+  
+  Currently unsupported: MetaDatabases, MetaTables and MetaColumns, and also inputarr in Execute.
+  Native types have been converted to MetaTypes.
+  Transactions not supported yet.
+*/ 
+
+if (! defined("_ADODB_CSV_LAYER")) {
+ define("_ADODB_CSV_LAYER", 1 );
+
+include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
+class ADODB_csv extends ADOConnection {
+       var $databaseType = 'csv';
+       var $databaseProvider = 'csv';
+       var $hasInsertID = true;
+       var $hasAffectedRows = true;    
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";
+       var $_affectedrows=0;
+       var $_insertid=0;
+       var $_url;
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $hasTransactions = false;
+       var $_errorNo = false;
+       
+       function ADODB_csv() 
+       {               
+       }
+       
+       function _insertid()
+       {
+                       return $this->_insertid;
+       }
+       
+       function _affectedrows()
+       {
+                       return $this->_affectedrows;
+       }
+  
+       function &MetaDatabases()
+       {
+               return false;
+       }
+
+       
+       // returns true or false
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;
+               $this->_url = $argHostname;
+               return true;    
+       }
+       
+       // returns true or false
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;
+               $this->_url = $argHostname;
+               return true;
+       }
+       
+       function &MetaColumns($table) 
+       {
+               return false;
+       }
+               
+               
+       // parameters use PostgreSQL convention, not MySQL
+       function &SelectLimit($sql,$nrows=-1,$offset=-1)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $url = $this->_url.'?sql='.urlencode($sql)."&nrows=$nrows&fetch=".
+                       (($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE).
+                       "&offset=$offset";
+               $err = false;
+               $rs = csv2rs($url,$err,false);
+               
+               if ($this->debug) print "$url<br><i>$err</i><br>";
+
+               $at = strpos($err,'::::');
+               if ($at === false) {
+                       $this->_errorMsg = $err;
+                       $this->_errorNo = (integer)$err;
+               } else {
+                       $this->_errorMsg = substr($err,$at+4,1024);
+                       $this->_errorNo = -9999;
+               }
+               if ($this->_errorNo) 
+                       if ($fn = $this->raiseErrorFn) {
+                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,'');
+                       }
+                       
+               if (is_object($rs)) {   
+               
+                       $rs->databaseType='csv';                
+                       $rs->fetchMode = ($this->fetchMode !== false) ?  $this->fetchMode : $ADODB_FETCH_MODE;
+                       $rs->connection = &$this;
+               }
+               return $rs;
+       }
+       
+       // returns queryID or false
+       function &_Execute($sql,$inputarr=false)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               if (!$this->_bindInputArray && $inputarr) {
+                       $sqlarr = explode('?',$sql);
+                       $sql = '';
+                       $i = 0;
+                       foreach($inputarr as $v) {
+
+                               $sql .= $sqlarr[$i];
+                               if (gettype($v) == 'string')
+                                       $sql .= $this->qstr($v);
+                               else if ($v === null)
+                                       $sql .= 'NULL';
+                               else
+                                       $sql .= $v;
+                               $i += 1;
+       
+                       }
+                       $sql .= $sqlarr[$i];
+                       if ($i+1 != sizeof($sqlarr))    
+                               print "Input Array does not match ?: ".htmlspecialchars($sql);
+                       $inputarr = false;
+               }
+               
+               $url =  $this->_url.'?sql='.urlencode($sql)."&fetch=".
+                       (($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE);
+               $err = false;
+               
+               
+               $rs = csv2rs($url,$err,false);
+               if ($this->debug) print urldecode($url)."<br><i>$err</i><br>";
+               $at = strpos($err,'::::');
+               if ($at === false) {            
+                       $this->_errorMsg = $err;
+                       $this->_errorNo = (integer)$err;
+               } else {
+                       $this->_errorMsg = substr($err,$at+4,1024);
+                       $this->_errorNo = -9999;
+               }
+               
+               if ($this->_errorNo) 
+                       if ($fn = $this->raiseErrorFn) {
+                               $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr);
+                       }
+               if (is_object($rs)) {
+                       $rs->fetchMode = ($this->fetchMode !== false) ?  $this->fetchMode : $ADODB_FETCH_MODE;
+                       
+                       $this->_affectedrows = $rs->affectedrows;
+                       $this->_insertid = $rs->insertid;
+                       $rs->databaseType='csv';
+                       $rs->connection = &$this;
+               }
+               return $rs;
+       }
+
+       /*      Returns: the last error message from previous database operation        */      
+       function ErrorMsg() 
+       {
+                       return $this->_errorMsg;
+       }
+       
+       /*      Returns: the last error number from previous database operation */      
+       function ErrorNo() 
+       {
+               return $this->_errorNo;
+       }
+       
+       // returns true or false
+       function _close()
+       {
+               return true;
+       }
+} // class
+
+class ADORecordset_csv extends ADORecordset {
+       function ADORecordset_csv($id,$mode=false)
+       {
+               $this->ADORecordset($id,$mode);
+       }
+       
+       function _close()
+       {
+               return true;
+       }
+}
+
+} // define
+       
 ?>
\ No newline at end of file
index 24f67020339a4f40b6ce12c046766fc04dc63054..d901abf8aaa43ca3e78a767295173f3565de1b07 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  DB2 data driver. Requires ODBC.\r
\r
-From phpdb list:\r
-\r
-Hi Andrew,\r
-\r
-thanks a lot for your help. Today we discovered what\r
-our real problem was:\r
-\r
-After "playing" a little bit with the php-scripts that try\r
-to connect to the IBM DB2, we set the optional parameter\r
-Cursortype when calling odbc_pconnect(....).\r
-\r
-And the exciting thing: When we set the cursor type\r
-to SQL_CUR_USE_ODBC Cursor Type, then\r
-the whole query speed up from 1 till 10 seconds\r
-to 0.2 till 0.3 seconds for 100 records. Amazing!!!\r
-\r
-Therfore, PHP is just almost fast as calling the DB2\r
-from Servlets using JDBC (don't take too much care\r
-about the speed at whole: the database was on a\r
-completely other location, so the whole connection\r
-was made over a slow network connection).\r
-\r
-I hope this helps when other encounter the same\r
-problem when trying to connect to DB2 from\r
-PHP.\r
-\r
-Kind regards,\r
-Christian Szardenings\r
-\r
-2 Oct 2001\r
-Mark Newnham has discovered that the SQL_CUR_USE_ODBC is not supported by \r
-IBM's DB2 ODBC driver, so this must be a 3rd party ODBC driver.\r
-\r
-From the IBM CLI Reference:\r
-\r
-SQL_ATTR_ODBC_CURSORS (DB2 CLI v5) \r
-This connection attribute is defined by ODBC, but is not supported by DB2\r
-CLI. Any attempt to set or get this attribute will result in an SQLSTATE of\r
-HYC00 (Driver not capable). \r
-\r
-A 32-bit option specifying how the Driver Manager uses the ODBC cursor\r
-library. \r
-\r
-So I guess this means the message [above] was related to using a 3rd party\r
-odbc driver.\r
-\r
-Setting SQL_CUR_USE_ODBC\r
-========================\r
-To set SQL_CUR_USE_ODBC for drivers that require it, do this:\r
-\r
-$db = NewADOConnection('db2');\r
-$db->curMode = SQL_CUR_USE_ODBC;\r
-$db->Connect($dsn, $userid, $pwd);\r
-\r
-*/\r
-\r
-if (!defined('_ADODB_ODBC_LAYER')) {\r
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
-}\r
-if (!defined('ADODB_DB2')){\r
-define('ADODB_DB2',1);\r
-\r
-class ADODB_DB2 extends ADODB_odbc {\r
-       var $databaseType = "db2";      \r
-       var $concat_operator = '||';\r
-       var $sysDate = 'CURRENT_DATE';\r
-       var $sysTimeStamp = 'CURRENT TIMESTAMP';\r
-       // The complete string representation of a timestamp has the form \r
-       // yyyy-mm-dd-hh.mm.ss.nnnnnn.\r
-       var $fmtTimeStamp = "'Y-m-d-H.i.s'";\r
-       var $ansiOuter = true;\r
-       var $identitySQL = 'values IDENTITY_VAL_LOCAL()';\r
-       var $_bindInputArray = true;\r
-       var $upperCase = 'upper';\r
-       \r
-       \r
-       function ADODB_DB2()\r
-       {\r
-               if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;\r
-               $this->ADODB_odbc();\r
-       }\r
-       \r
-       function IfNull( $field, $ifNull ) \r
-       {\r
-               return " COALESCE($field, $ifNull) "; // if DB2 UDB\r
-       }\r
-       \r
-       function ServerInfo()\r
-       {\r
-               //odbc_setoption($this->_connectionID,1,101 /*SQL_ATTR_ACCESS_MODE*/, 1 /*SQL_MODE_READ_ONLY*/);\r
-               $vers = $this->GetOne('select versionnumber from sysibm.sysversions');\r
-               //odbc_setoption($this->_connectionID,1,101, 0 /*SQL_MODE_READ_WRITE*/);\r
-               return array('description'=>'DB2 ODBC driver', 'version'=>$vers);\r
-       }\r
-       \r
-       function _insertid()\r
-       {\r
-               return $this->GetOne($this->identitySQL);\r
-       }\r
-       \r
-       function RowLock($tables,$where)\r
-       {\r
-               if ($this->_autocommit) $this->BeginTrans();\r
-               return $this->GetOne("select 1 as ignore from $tables where $where for update");\r
-       }\r
-       /*\r
-       function &MetaTables($showSchema=false)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $savem = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $qid = odbc_tables($this->_connectionID);\r
-               \r
-               $rs = new ADORecordSet_odbc($qid);\r
-               \r
-               $ADODB_FETCH_MODE = $savem;\r
-               if (!$rs) return false;\r
-               \r
-               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
-               \r
-               //print_r($rs);\r
-               $arr =& $rs->GetArray();\r
-               $rs->Close();\r
-               $arr2 = array();\r
-               //print_r($arr);\r
-               for ($i=0; $i < sizeof($arr); $i++) {\r
-                       $row = $arr[$i];\r
-                       if ($row[2] && strncmp($row[1],'SYS',3) != 0)\r
-                                if ($showSchema) $arr2[] = $row[1].'.'.$row[2];\r
-                                else $arr2[] = $row[2];\r
-               }\r
-               return $arr2;\r
-       }*/\r
-       \r
-       function &MetaTables($ttype=false,$showSchema=false)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $savem = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $qid = odbc_tables($this->_connectionID);\r
-               \r
-               $rs = new ADORecordSet_odbc($qid);\r
-               \r
-               $ADODB_FETCH_MODE = $savem;\r
-               if (!$rs) return false;\r
-               \r
-               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
-               \r
-               $arr =& $rs->GetArray();\r
-               //print_r($arr);\r
-               \r
-               $rs->Close();\r
-               $arr2 = array();\r
-               \r
-               if ($ttype) {\r
-                       $isview = strncmp($ttype,'V',1) === 0;\r
-               }\r
-               for ($i=0; $i < sizeof($arr); $i++) {\r
-               \r
-                       if (!$arr[$i][2]) continue;\r
-                       if (strncmp($arr[$i][1],'SYS',3) === 0) continue;\r
-                       \r
-                       $type = $arr[$i][3];\r
-                       \r
-                       if ($showSchema) $arr[$i][2] = $arr[$i][1].'.'.$arr[$i][2];\r
-                       \r
-                       if ($ttype) { \r
-                               if ($isview) {\r
-                                       if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];\r
-                               } else if (strncmp($type,'T',1) === 0) $arr2[] = $arr[$i][2];\r
-                       } else if (strncmp($type,'S',1) !== 0) $arr2[] = $arr[$i][2];\r
-               }\r
-               return $arr2;\r
-       }\r
-       \r
-       // Format date column in sql string given an input format that understands Y M D\r
-       function SQLDate($fmt, $col=false)\r
-       {       \r
-       // use right() and replace() ?\r
-               if (!$col) $col = $this->sysDate;\r
-               $s = '';\r
-               \r
-               $len = strlen($fmt);\r
-               for ($i=0; $i < $len; $i++) {\r
-                       if ($s) $s .= '||';\r
-                       $ch = $fmt[$i];\r
-                       switch($ch) {\r
-                       case 'Y':\r
-                       case 'y':\r
-                               $s .= "char(year($col))";\r
-                               break;\r
-                       case 'M':\r
-                               $s .= "substr(monthname($col),1,3)";\r
-                               break;\r
-                       case 'm':\r
-                               $s .= "right(digits(month($col)),2)";\r
-                               break;\r
-                       case 'D':\r
-                       case 'd':\r
-                               $s .= "right(digits(day($col)),2)";\r
-                               break;\r
-                       case 'H':\r
-                       case 'h':\r
-                               if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)";        \r
-                               else $s .= "''";\r
-                               break;\r
-                       case 'i':\r
-                       case 'I':\r
-                               if ($col != $this->sysDate)\r
-                                       $s .= "right(digits(minute($col)),2)";\r
-                                       else $s .= "''";\r
-                               break;\r
-                       case 'S':\r
-                       case 's':\r
-                               if ($col != $this->sysDate)\r
-                                       $s .= "right(digits(second($col)),2)";\r
-                               else $s .= "''";\r
-                               break;\r
-                       default:\r
-                               if ($ch == '\\') {\r
-                                       $i++;\r
-                                       $ch = substr($fmt,$i,1);\r
-                               }\r
-                               $s .= $this->qstr($ch);\r
-                       }\r
-               }\r
-               return $s;\r
-       } \r
\r
-       \r
-               function &SelectLimit($sql,$nrows=-1,$offset=-1)\r
-               {\r
-                       if ($offset <= 0) {\r
-                       // could also use " OPTIMIZE FOR $nrows ROWS "\r
-                               if ($nrows >= 0) $sql .=  " FETCH FIRST $nrows ROWS ONLY ";\r
-                               $rs =& $this->Execute($sql,false);\r
-                       } else {\r
-                               if ($offset > 0 && $nrows < 0);\r
-                               else {\r
-                                       $nrows += $offset;\r
-                                       $sql .=  " FETCH FIRST $nrows ROWS ONLY ";\r
-                               }\r
-                               $rs =& ADOConnection::SelectLimit($sql,-1,$offset);\r
-                       }\r
-                       \r
-                       return $rs;\r
-               }\r
-       \r
-};\r
\r
-\r
-class  ADORecordSet_db2 extends ADORecordSet_odbc {    \r
-       \r
-       var $databaseType = "db2";              \r
-       \r
-       function ADORecordSet_db2($id,$mode=false)\r
-       {\r
-               $this->ADORecordSet_odbc($id,$mode);\r
-       }\r
-\r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               \r
-               switch (strtoupper($t)) {\r
-               case 'VARCHAR':\r
-               case 'CHAR':\r
-               case 'CHARACTER':\r
-                       if ($len <= $this->blobSize) return 'C';\r
-               \r
-               case 'LONGCHAR':\r
-               case 'TEXT':\r
-               case 'CLOB':\r
-               case 'DBCLOB': // double-byte\r
-                       return 'X';\r
-               \r
-               case 'BLOB':\r
-               case 'GRAPHIC':\r
-               case 'VARGRAPHIC':\r
-                       return 'B';\r
-                       \r
-               case 'DATE':\r
-                       return 'D';\r
-               \r
-               case 'TIME':\r
-               case 'TIMESTAMP':\r
-                       return 'T';\r
-               \r
-               //case 'BOOLEAN': \r
-               //case 'BIT':\r
-               //      return 'L';\r
-                       \r
-               //case 'COUNTER':\r
-               //      return 'R';\r
-                       \r
-               case 'INT':\r
-               case 'INTEGER':\r
-               case 'BIGINT':\r
-               case 'SMALLINT':\r
-                       return 'I';\r
-                       \r
-               default: return 'N';\r
-               }\r
-       }\r
-}\r
-\r
-} //define\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  DB2 data driver. Requires ODBC.
+From phpdb list:
+
+Hi Andrew,
+
+thanks a lot for your help. Today we discovered what
+our real problem was:
+
+After "playing" a little bit with the php-scripts that try
+to connect to the IBM DB2, we set the optional parameter
+Cursortype when calling odbc_pconnect(....).
+
+And the exciting thing: When we set the cursor type
+to SQL_CUR_USE_ODBC Cursor Type, then
+the whole query speed up from 1 till 10 seconds
+to 0.2 till 0.3 seconds for 100 records. Amazing!!!
+
+Therfore, PHP is just almost fast as calling the DB2
+from Servlets using JDBC (don't take too much care
+about the speed at whole: the database was on a
+completely other location, so the whole connection
+was made over a slow network connection).
+
+I hope this helps when other encounter the same
+problem when trying to connect to DB2 from
+PHP.
+
+Kind regards,
+Christian Szardenings
+
+2 Oct 2001
+Mark Newnham has discovered that the SQL_CUR_USE_ODBC is not supported by 
+IBM's DB2 ODBC driver, so this must be a 3rd party ODBC driver.
+
+From the IBM CLI Reference:
+
+SQL_ATTR_ODBC_CURSORS (DB2 CLI v5) 
+This connection attribute is defined by ODBC, but is not supported by DB2
+CLI. Any attempt to set or get this attribute will result in an SQLSTATE of
+HYC00 (Driver not capable). 
+
+A 32-bit option specifying how the Driver Manager uses the ODBC cursor
+library. 
+
+So I guess this means the message [above] was related to using a 3rd party
+odbc driver.
+
+Setting SQL_CUR_USE_ODBC
+========================
+To set SQL_CUR_USE_ODBC for drivers that require it, do this:
+
+$db = NewADOConnection('db2');
+$db->curMode = SQL_CUR_USE_ODBC;
+$db->Connect($dsn, $userid, $pwd);
+
+
+
+USING CLI INTERFACE
+===================
+
+I have had reports that the $host and $database params have to be reversed in 
+Connect() when using the CLI interface. From Halmai Csongor csongor.halmai#nexum.hu:
+
+> The symptom is that if I change the database engine from postgres or any other to DB2 then the following
+> connection command becomes wrong despite being described this version to be correct in the docs. 
+>
+> $connection_object->Connect( $DATABASE_HOST, $DATABASE_AUTH_USER_NAME, $DATABASE_AUTH_PASSWORD, $DATABASE_NAME )
+>
+> In case of DB2 I had to swap the first and last arguments in order to connect properly. 
+
+
+*/
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+if (!defined('ADODB_DB2')){
+define('ADODB_DB2',1);
+
+class ADODB_DB2 extends ADODB_odbc {
+       var $databaseType = "db2";      
+       var $concat_operator = '||';
+       var $sysDate = 'CURRENT_DATE';
+       var $sysTimeStamp = 'CURRENT TIMESTAMP';
+       // The complete string representation of a timestamp has the form 
+       // yyyy-mm-dd-hh.mm.ss.nnnnnn.
+       var $fmtTimeStamp = "'Y-m-d-H.i.s'";
+       var $ansiOuter = true;
+       var $identitySQL = 'values IDENTITY_VAL_LOCAL()';
+       var $_bindInputArray = false;
+       var $upperCase = 'upper';
+       
+       
+       function ADODB_DB2()
+       {
+               if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;
+               $this->ADODB_odbc();
+       }
+       
+       function IfNull( $field, $ifNull ) 
+       {
+               return " COALESCE($field, $ifNull) "; // if DB2 UDB
+       }
+       
+       function ServerInfo()
+       {
+               //odbc_setoption($this->_connectionID,1,101 /*SQL_ATTR_ACCESS_MODE*/, 1 /*SQL_MODE_READ_ONLY*/);
+               $vers = $this->GetOne('select versionnumber from sysibm.sysversions');
+               //odbc_setoption($this->_connectionID,1,101, 0 /*SQL_MODE_READ_WRITE*/);
+               return array('description'=>'DB2 ODBC driver', 'version'=>$vers);
+       }
+       
+       function _insertid()
+       {
+               return $this->GetOne($this->identitySQL);
+       }
+       
+       function RowLock($tables,$where)
+       {
+               if ($this->_autocommit) $this->BeginTrans();
+               return $this->GetOne("select 1 as ignore from $tables where $where for update");
+       }
+       
+       function &MetaTables($ttype=false,$showSchema=false)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $savem = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $qid = odbc_tables($this->_connectionID);
+               
+               $rs = new ADORecordSet_odbc($qid);
+               
+               $ADODB_FETCH_MODE = $savem;
+               if (!$rs) return false;
+               
+               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+               
+               $arr =& $rs->GetArray();
+               //print_r($arr);
+               
+               $rs->Close();
+               $arr2 = array();
+               
+               if ($ttype) {
+                       $isview = strncmp($ttype,'V',1) === 0;
+               }
+               for ($i=0; $i < sizeof($arr); $i++) {
+               
+                       if (!$arr[$i][2]) continue;
+                       if (strncmp($arr[$i][1],'SYS',3) === 0) continue;
+                       
+                       $type = $arr[$i][3];
+                       
+                       if ($showSchema) $arr[$i][2] = $arr[$i][1].'.'.$arr[$i][2];
+                       
+                       if ($ttype) { 
+                               if ($isview) {
+                                       if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];
+                               } else if (strncmp($type,'T',1) === 0) $arr2[] = $arr[$i][2];
+                       } else if (strncmp($type,'S',1) !== 0) $arr2[] = $arr[$i][2];
+               }
+               return $arr2;
+       }
+       
+       // Format date column in sql string given an input format that understands Y M D
+       function SQLDate($fmt, $col=false)
+       {       
+       // use right() and replace() ?
+               if (!$col) $col = $this->sysDate;
+               $s = '';
+               
+               $len = strlen($fmt);
+               for ($i=0; $i < $len; $i++) {
+                       if ($s) $s .= '||';
+                       $ch = $fmt[$i];
+                       switch($ch) {
+                       case 'Y':
+                       case 'y':
+                               $s .= "char(year($col))";
+                               break;
+                       case 'M':
+                               $s .= "substr(monthname($col),1,3)";
+                               break;
+                       case 'm':
+                               $s .= "right(digits(month($col)),2)";
+                               break;
+                       case 'D':
+                       case 'd':
+                               $s .= "right(digits(day($col)),2)";
+                               break;
+                       case 'H':
+                       case 'h':
+                               if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)";        
+                               else $s .= "''";
+                               break;
+                       case 'i':
+                       case 'I':
+                               if ($col != $this->sysDate)
+                                       $s .= "right(digits(minute($col)),2)";
+                                       else $s .= "''";
+                               break;
+                       case 'S':
+                       case 's':
+                               if ($col != $this->sysDate)
+                                       $s .= "right(digits(second($col)),2)";
+                               else $s .= "''";
+                               break;
+                       default:
+                               if ($ch == '\\') {
+                                       $i++;
+                                       $ch = substr($fmt,$i,1);
+                               }
+                               $s .= $this->qstr($ch);
+                       }
+               }
+               return $s;
+       } 
+       
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputArr=false)
+       {
+               if ($offset <= 0) {
+               // could also use " OPTIMIZE FOR $nrows ROWS "
+                       if ($nrows >= 0) $sql .=  " FETCH FIRST $nrows ROWS ONLY ";
+                       $rs =& $this->Execute($sql,$inputArr);
+               } else {
+                       if ($offset > 0 && $nrows < 0);
+                       else {
+                               $nrows += $offset;
+                               $sql .=  " FETCH FIRST $nrows ROWS ONLY ";
+                       }
+                       $rs =& ADOConnection::SelectLimit($sql,-1,$offset,$inputArr);
+               }
+               
+               return $rs;
+       }
+       
+};
+
+class  ADORecordSet_db2 extends ADORecordSet_odbc {    
+       
+       var $databaseType = "db2";              
+       
+       function ADORecordSet_db2($id,$mode=false)
+       {
+               $this->ADORecordSet_odbc($id,$mode);
+       }
+
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               
+               switch (strtoupper($t)) {
+               case 'VARCHAR':
+               case 'CHAR':
+               case 'CHARACTER':
+                       if ($len <= $this->blobSize) return 'C';
+               
+               case 'LONGCHAR':
+               case 'TEXT':
+               case 'CLOB':
+               case 'DBCLOB': // double-byte
+                       return 'X';
+               
+               case 'BLOB':
+               case 'GRAPHIC':
+               case 'VARGRAPHIC':
+                       return 'B';
+                       
+               case 'DATE':
+                       return 'D';
+               
+               case 'TIME':
+               case 'TIMESTAMP':
+                       return 'T';
+               
+               //case 'BOOLEAN': 
+               //case 'BIT':
+               //      return 'L';
+                       
+               //case 'COUNTER':
+               //      return 'R';
+                       
+               case 'INT':
+               case 'INTEGER':
+               case 'BIGINT':
+               case 'SMALLINT':
+                       return 'I';
+                       
+               default: return 'N';
+               }
+       }
+}
+
+} //define
 ?>
\ No newline at end of file
index 46a4460db875a29810a778c67740b1d2ecf22333..4221070cd2e046e2601cad977c1e961557967ec4 100644 (file)
-<?php\r
-/*\r
- @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
- Contribution by Frank M. Kromann <frank@frontbase.com>. \r
-  Set tabs to 8.\r
-*/ \r
-\r
-if (! defined("_ADODB_FBSQL_LAYER")) {\r
- define("_ADODB_FBSQL_LAYER", 1 );\r
-\r
-class ADODB_fbsql extends ADOConnection {\r
-       var $databaseType = 'fbsql';\r
-       var $hasInsertID = true;\r
-       var $hasAffectedRows = true;    \r
-       var $metaTablesSQL = "SHOW TABLES";     \r
-       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";\r
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
-       var $hasLimit = false;\r
-       \r
-       function ADODB_fbsql() \r
-       {                       \r
-       }\r
-       \r
-       function _insertid()\r
-       {\r
-                       return fbsql_insert_id($this->_connectionID);\r
-       }\r
-       \r
-       function _affectedrows()\r
-       {\r
-                       return fbsql_affected_rows($this->_connectionID);\r
-       }\r
-  \r
-       function &MetaDatabases()\r
-       {\r
-               $qid = fbsql_list_dbs($this->_connectionID);\r
-               $arr = array();\r
-               $i = 0;\r
-               $max = fbsql_num_rows($qid);\r
-               while ($i < $max) {\r
-                       $arr[] = fbsql_tablename($qid,$i);\r
-                       $i += 1;\r
-               }\r
-               return $arr;\r
-       }\r
-\r
-       // returns concatenated string\r
-       function Concat()\r
-       {\r
-               $s = "";\r
-               $arr = func_get_args();\r
-               $first = true;\r
-\r
-               $s = implode(',',$arr);\r
-               if (sizeof($arr) > 0) return "CONCAT($s)";\r
-               else return '';\r
-       }\r
-       \r
-       // returns true or false\r
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               $this->_connectionID = fbsql_connect($argHostname,$argUsername,$argPassword);\r
-               if ($this->_connectionID === false) return false;\r
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-               return true;    \r
-       }\r
-       \r
-       // returns true or false\r
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               $this->_connectionID = fbsql_pconnect($argHostname,$argUsername,$argPassword);\r
-               if ($this->_connectionID === false) return false;\r
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-               return true;    \r
-       }\r
-       \r
-       function &MetaColumns($table) \r
-       {\r
-               if ($this->metaColumnsSQL) {\r
-                       \r
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));\r
-                       \r
-                       if ($rs === false) return false;\r
-                       \r
-                       $retarr = array();\r
-                       while (!$rs->EOF){\r
-                               $fld = new ADOFieldObject();\r
-                               $fld->name = $rs->fields[0];\r
-                               $fld->type = $rs->fields[1];\r
-                                       \r
-                               // split type into type(length):\r
-                               if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) {\r
-                                       $fld->type = $query_array[1];\r
-                                       $fld->max_length = $query_array[2];\r
-                               } else {\r
-                                       $fld->max_length = -1;\r
-                               }\r
-                               $fld->not_null = ($rs->fields[2] != 'YES');\r
-                               $fld->primary_key = ($rs->fields[3] == 'PRI');\r
-                               $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);\r
-                               $fld->binary = (strpos($fld->type,'blob') !== false);\r
-                               \r
-                               $retarr[strtoupper($fld->name)] = $fld; \r
-                               $rs->MoveNext();\r
-                       }\r
-                       $rs->Close();\r
-                       return $retarr; \r
-               }\r
-               return false;\r
-       }\r
-               \r
-       // returns true or false\r
-       function SelectDB($dbName) \r
-       {\r
-               $this->databaseName = $dbName;\r
-               if ($this->_connectionID) {\r
-                       return @fbsql_select_db($dbName,$this->_connectionID);          \r
-               }\r
-               else return false;      \r
-       }\r
-       \r
-       \r
-       // returns queryID or false\r
-       function _query($sql,$inputarr)\r
-       {\r
-               return fbsql_query("$sql;",$this->_connectionID);\r
-       }\r
-\r
-       /*      Returns: the last error message from previous database operation        */      \r
-       function ErrorMsg() \r
-       {\r
-               $this->_errorMsg = @fbsql_error($this->_connectionID);\r
-                       return $this->_errorMsg;\r
-       }\r
-       \r
-       /*      Returns: the last error number from previous database operation */      \r
-       function ErrorNo() \r
-       {\r
-               return @fbsql_errno($this->_connectionID);\r
-       }\r
-       \r
-       // returns true or false\r
-       function _close()\r
-       {\r
-               return @fbsql_close($this->_connectionID);\r
-       }\r
-               \r
-}\r
-       \r
-/*--------------------------------------------------------------------------------------\r
-        Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordSet_fbsql extends ADORecordSet{ \r
-       \r
-       var $databaseType = "fbsql";\r
-       var $canSeek = true;\r
-       \r
-       function ADORecordSet_fbsql($queryID,$mode=false) \r
-       {\r
-               if (!$mode) { \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               switch ($mode) {\r
-               case ADODB_FETCH_NUM: $this->fetchMode = FBSQL_NUM; break;\r
-               default:\r
-               case ADODB_FETCH_BOTH: $this->fetchMode = FBSQL_BOTH; break;\r
-               case ADODB_FETCH_ASSOC: $this->fetchMode = FBSQL_ASSOC; break;\r
-               }\r
-               return $this->ADORecordSet($queryID);\r
-       }\r
-       \r
-       function _initrs()\r
-       {\r
-       GLOBAL $ADODB_COUNTRECS;\r
-               $this->_numOfRows = ($ADODB_COUNTRECS) ? @fbsql_num_rows($this->_queryID):-1;\r
-               $this->_numOfFields = @fbsql_num_fields($this->_queryID);\r
-       }\r
-       \r
-\r
-\r
-       function &FetchField($fieldOffset = -1) {\r
-               if ($fieldOffset != -1) {\r
-                       $o =  @fbsql_fetch_field($this->_queryID, $fieldOffset);\r
-                       //$o->max_length = -1; // fbsql returns the max length less spaces -- so it is unrealiable\r
-                       $f = @fbsql_field_flags($this->_queryID,$fieldOffset);\r
-                       $o->binary = (strpos($f,'binary')!== false);\r
-               }\r
-               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
-                       $o = @fbsql_fetch_field($this->_queryID);// fbsql returns the max length less spaces -- so it is unrealiable\r
-                       //$o->max_length = -1;\r
-               }\r
-               \r
-               return $o;\r
-       }\r
-               \r
-       function _seek($row)\r
-       {\r
-               return @fbsql_data_seek($this->_queryID,$row);\r
-       }\r
-       \r
-       function _fetch($ignore_fields=false)\r
-       {\r
-               $this->fields = @fbsql_fetch_array($this->_queryID,$this->fetchMode);\r
-               return ($this->fields == true);\r
-       }\r
-       \r
-       function _close() {\r
-               return @fbsql_free_result($this->_queryID);             \r
-       }\r
-       \r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               $len = -1; // fbsql max_length is not accurate\r
-               switch (strtoupper($t)) {\r
-               case 'CHARACTER':\r
-               case 'CHARACTER VARYING': \r
-               case 'BLOB': \r
-               case 'CLOB': \r
-               case 'BIT': \r
-               case 'BIT VARYING': \r
-                       if ($len <= $this->blobSize) return 'C';\r
-                       \r
-               // so we have to check whether binary...\r
-               case 'IMAGE':\r
-               case 'LONGBLOB': \r
-               case 'BLOB':\r
-               case 'MEDIUMBLOB':\r
-                       return !empty($fieldobj->binary) ? 'B' : 'X';\r
-                       \r
-               case 'DATE': return 'D';\r
-               \r
-               case 'TIME':\r
-               case 'TIME WITH TIME ZONE':\r
-               case 'TIMESTAMP': \r
-               case 'TIMESTAMP WITH TIME ZONE': return 'T';\r
-               \r
-               case 'PRIMARY_KEY':\r
-                       return 'R';\r
-               case 'INTEGER':\r
-               case 'SMALLINT': \r
-               case 'BOOLEAN':\r
-                       \r
-                       if (!empty($fieldobj->primary_key)) return 'R';\r
-                       else return 'I';\r
-               \r
-               default: return 'N';\r
-               }\r
-       }\r
-\r
-} //class\r
-} // defined\r
+<?php
+/*
+ @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+ Contribution by Frank M. Kromann <frank@frontbase.com>. 
+  Set tabs to 8.
+*/ 
+
+if (! defined("_ADODB_FBSQL_LAYER")) {
+ define("_ADODB_FBSQL_LAYER", 1 );
+
+class ADODB_fbsql extends ADOConnection {
+       var $databaseType = 'fbsql';
+       var $hasInsertID = true;
+       var $hasAffectedRows = true;    
+       var $metaTablesSQL = "SHOW TABLES";     
+       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";
+       var $hasLimit = false;
+       
+       function ADODB_fbsql() 
+       {                       
+       }
+       
+       function _insertid()
+       {
+                       return fbsql_insert_id($this->_connectionID);
+       }
+       
+       function _affectedrows()
+       {
+                       return fbsql_affected_rows($this->_connectionID);
+       }
+  
+       function &MetaDatabases()
+       {
+               $qid = fbsql_list_dbs($this->_connectionID);
+               $arr = array();
+               $i = 0;
+               $max = fbsql_num_rows($qid);
+               while ($i < $max) {
+                       $arr[] = fbsql_tablename($qid,$i);
+                       $i += 1;
+               }
+               return $arr;
+       }
+
+       // returns concatenated string
+       function Concat()
+       {
+               $s = "";
+               $arr = func_get_args();
+               $first = true;
+
+               $s = implode(',',$arr);
+               if (sizeof($arr) > 0) return "CONCAT($s)";
+               else return '';
+       }
+       
+       // returns true or false
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               $this->_connectionID = fbsql_connect($argHostname,$argUsername,$argPassword);
+               if ($this->_connectionID === false) return false;
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);
+               return true;    
+       }
+       
+       // returns true or false
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               $this->_connectionID = fbsql_pconnect($argHostname,$argUsername,$argPassword);
+               if ($this->_connectionID === false) return false;
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);
+               return true;    
+       }
+       
+       function &MetaColumns($table) 
+       {
+               if ($this->metaColumnsSQL) {
+                       
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
+                       
+                       if ($rs === false) return false;
+                       
+                       $retarr = array();
+                       while (!$rs->EOF){
+                               $fld = new ADOFieldObject();
+                               $fld->name = $rs->fields[0];
+                               $fld->type = $rs->fields[1];
+                                       
+                               // split type into type(length):
+                               if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) {
+                                       $fld->type = $query_array[1];
+                                       $fld->max_length = $query_array[2];
+                               } else {
+                                       $fld->max_length = -1;
+                               }
+                               $fld->not_null = ($rs->fields[2] != 'YES');
+                               $fld->primary_key = ($rs->fields[3] == 'PRI');
+                               $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
+                               $fld->binary = (strpos($fld->type,'blob') !== false);
+                               
+                               $retarr[strtoupper($fld->name)] = $fld; 
+                               $rs->MoveNext();
+                       }
+                       $rs->Close();
+                       return $retarr; 
+               }
+               return false;
+       }
+               
+       // returns true or false
+       function SelectDB($dbName) 
+       {
+               $this->databaseName = $dbName;
+               if ($this->_connectionID) {
+                       return @fbsql_select_db($dbName,$this->_connectionID);          
+               }
+               else return false;      
+       }
+       
+       
+       // returns queryID or false
+       function _query($sql,$inputarr)
+       {
+               return fbsql_query("$sql;",$this->_connectionID);
+       }
+
+       /*      Returns: the last error message from previous database operation        */      
+       function ErrorMsg() 
+       {
+               $this->_errorMsg = @fbsql_error($this->_connectionID);
+                       return $this->_errorMsg;
+       }
+       
+       /*      Returns: the last error number from previous database operation */      
+       function ErrorNo() 
+       {
+               return @fbsql_errno($this->_connectionID);
+       }
+       
+       // returns true or false
+       function _close()
+       {
+               return @fbsql_close($this->_connectionID);
+       }
+               
+}
+       
+/*--------------------------------------------------------------------------------------
+        Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_fbsql extends ADORecordSet{ 
+       
+       var $databaseType = "fbsql";
+       var $canSeek = true;
+       
+       function ADORecordSet_fbsql($queryID,$mode=false) 
+       {
+               if (!$mode) { 
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               switch ($mode) {
+               case ADODB_FETCH_NUM: $this->fetchMode = FBSQL_NUM; break;
+               default:
+               case ADODB_FETCH_BOTH: $this->fetchMode = FBSQL_BOTH; break;
+               case ADODB_FETCH_ASSOC: $this->fetchMode = FBSQL_ASSOC; break;
+               }
+               return $this->ADORecordSet($queryID);
+       }
+       
+       function _initrs()
+       {
+       GLOBAL $ADODB_COUNTRECS;
+               $this->_numOfRows = ($ADODB_COUNTRECS) ? @fbsql_num_rows($this->_queryID):-1;
+               $this->_numOfFields = @fbsql_num_fields($this->_queryID);
+       }
+       
+
+
+       function &FetchField($fieldOffset = -1) {
+               if ($fieldOffset != -1) {
+                       $o =  @fbsql_fetch_field($this->_queryID, $fieldOffset);
+                       //$o->max_length = -1; // fbsql returns the max length less spaces -- so it is unrealiable
+                       $f = @fbsql_field_flags($this->_queryID,$fieldOffset);
+                       $o->binary = (strpos($f,'binary')!== false);
+               }
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */
+                       $o = @fbsql_fetch_field($this->_queryID);// fbsql returns the max length less spaces -- so it is unrealiable
+                       //$o->max_length = -1;
+               }
+               
+               return $o;
+       }
+               
+       function _seek($row)
+       {
+               return @fbsql_data_seek($this->_queryID,$row);
+       }
+       
+       function _fetch($ignore_fields=false)
+       {
+               $this->fields = @fbsql_fetch_array($this->_queryID,$this->fetchMode);
+               return ($this->fields == true);
+       }
+       
+       function _close() {
+               return @fbsql_free_result($this->_queryID);             
+       }
+       
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               $len = -1; // fbsql max_length is not accurate
+               switch (strtoupper($t)) {
+               case 'CHARACTER':
+               case 'CHARACTER VARYING': 
+               case 'BLOB': 
+               case 'CLOB': 
+               case 'BIT': 
+               case 'BIT VARYING': 
+                       if ($len <= $this->blobSize) return 'C';
+                       
+               // so we have to check whether binary...
+               case 'IMAGE':
+               case 'LONGBLOB': 
+               case 'BLOB':
+               case 'MEDIUMBLOB':
+                       return !empty($fieldobj->binary) ? 'B' : 'X';
+                       
+               case 'DATE': return 'D';
+               
+               case 'TIME':
+               case 'TIME WITH TIME ZONE':
+               case 'TIMESTAMP': 
+               case 'TIMESTAMP WITH TIME ZONE': return 'T';
+               
+               case 'PRIMARY_KEY':
+                       return 'R';
+               case 'INTEGER':
+               case 'SMALLINT': 
+               case 'BOOLEAN':
+                       
+                       if (!empty($fieldobj->primary_key)) return 'R';
+                       else return 'I';
+               
+               default: return 'N';
+               }
+       }
+
+} //class
+} // defined
 ?>
\ No newline at end of file
index 58ea10f9e1f6fb69955d5960e891b28b843d3ea8..b5f10be2d68ae0b933fa4210e720fa5a2b796e23 100644 (file)
@@ -1,69 +1,69 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-\r
-*/\r
-\r
-\r
-include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");\r
-\r
-class ADODB_firebird extends ADODB_ibase {\r
-       var $databaseType = "firebird"; \r
-       function ADODB_firebird()\r
-       {       \r
-               $this->ADODB_ibase();\r
-       }\r
-       \r
-       function ServerInfo()\r
-       {\r
-               $arr['dialect'] = $this->dialect;\r
-               switch($arr['dialect']) {\r
-               case '': \r
-               case '1': $s = 'Firebird Dialect 1'; break;\r
-               case '2': $s = 'Firebird Dialect 2'; break;\r
-               default:\r
-               case '3': $s = 'Firebird Dialect 3'; break;\r
-               }\r
-               $arr['version'] = ADOConnection::_findvers($s);\r
-               $arr['description'] = $s;\r
-               return $arr;\r
-       }\r
-       \r
-       // Note that Interbase 6.5 uses this ROWS instead - don't you love forking wars!\r
-       //              SELECT col1, col2 FROM table ROWS 5 -- get 5 rows \r
-       //              SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2\r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $secs=0)\r
-       {\r
-               $str = 'SELECT ';\r
-               if ($nrows >= 0) $str .= "FIRST $nrows "; \r
-               $str .=($offset>=0) ? "SKIP $offset " : '';\r
-               \r
-               $sql = preg_replace('/^[ \t]*select/i',$str,$sql); \r
-               if ($secs)\r
-                       $rs =& $this->CacheExecute($secs,$sql,$inputarr);\r
-               else\r
-                       $rs =& $this->Execute($sql,$inputarr);\r
-                       \r
-               return $rs;\r
-       }\r
-       \r
-       \r
-};\r
\r
-\r
-class  ADORecordSet_firebird extends ADORecordSet_ibase {      \r
-       \r
-       var $databaseType = "firebird";         \r
-       \r
-       function ADORecordSet_firebird($id,$mode=false)\r
-       {\r
-               $this->ADORecordSet_ibase($id,$mode);\r
-       }\r
-}\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+
+*/
+
+
+include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");
+
+class ADODB_firebird extends ADODB_ibase {
+       var $databaseType = "firebird"; 
+       function ADODB_firebird()
+       {       
+               $this->ADODB_ibase();
+       }
+       
+       function ServerInfo()
+       {
+               $arr['dialect'] = $this->dialect;
+               switch($arr['dialect']) {
+               case '': 
+               case '1': $s = 'Firebird Dialect 1'; break;
+               case '2': $s = 'Firebird Dialect 2'; break;
+               default:
+               case '3': $s = 'Firebird Dialect 3'; break;
+               }
+               $arr['version'] = ADOConnection::_findvers($s);
+               $arr['description'] = $s;
+               return $arr;
+       }
+       
+       // Note that Interbase 6.5 uses this ROWS instead - don't you love forking wars!
+       //              SELECT col1, col2 FROM table ROWS 5 -- get 5 rows 
+       //              SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $secs=0)
+       {
+               $str = 'SELECT ';
+               if ($nrows >= 0) $str .= "FIRST $nrows "; 
+               $str .=($offset>=0) ? "SKIP $offset " : '';
+               
+               $sql = preg_replace('/^[ \t]*select/i',$str,$sql); 
+               if ($secs)
+                       $rs =& $this->CacheExecute($secs,$sql,$inputarr);
+               else
+                       $rs =& $this->Execute($sql,$inputarr);
+                       
+               return $rs;
+       }
+       
+       
+};
+
+class  ADORecordSet_firebird extends ADORecordSet_ibase {      
+       
+       var $databaseType = "firebird";         
+       
+       function ADORecordSet_firebird($id,$mode=false)
+       {
+               $this->ADORecordSet_ibase($id,$mode);
+       }
+}
 ?>
\ No newline at end of file
index d42b1d70892675e74388623ad0bbe33077204d8c..e9e7c94eea73caae2efc080e58a93ddcdb0a36b3 100644 (file)
-<?php\r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.  \r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-\r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Interbase data driver. Requires interbase client. Works on Windows and Unix.\r
-\r
-  3 Jan 2002 -- suggestions by Hans-Peter Oeri <kampfcaspar75@oeri.ch>\r
-       changed transaction handling and added experimental blob stuff\r
-  \r
-  Docs to interbase at the website\r
-   http://www.synectics.co.za/php3/tutorial/IB_PHP3_API.html\r
-   \r
-  To use gen_id(), see\r
-   http://www.volny.cz/iprenosil/interbase/ip_ib_code.htm#_code_creategen\r
-   \r
-   $rs = $conn->Execute('select gen_id(adodb,1) from rdb$database');\r
-   $id = $rs->fields[0];\r
-   $conn->Execute("insert into table (id, col1,...) values ($id, $val1,...)");\r
-*/\r
-\r
-\r
-class ADODB_ibase extends ADOConnection {\r
-       var $databaseType = "ibase";\r
-       var $dataProvider = "ibase";\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $ibase_timefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S';\r
-       var $fmtDate = "'Y-m-d'";\r
-       var $fmtTimeStamp = "'Y-m-d, H:i:s'";\r
-       var $concat_operator='||';\r
-       var $_transactionID;\r
-       var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'";\r
-       //OPN STUFF start\r
-       var $metaColumnsSQL = "select a.rdb\$field_name, a.rdb\$null_flag, a.rdb\$default_source, b.rdb\$field_length, b.rdb\$field_scale, b.rdb\$field_sub_type, b.rdb\$field_precision, b.rdb\$field_type from rdb\$relation_fields a, rdb\$fields b where a.rdb\$field_source = b.rdb\$field_name and a.rdb\$relation_name = '%s' order by a.rdb\$field_position asc";\r
-       //OPN STUFF end\r
-       var $ibasetrans;\r
-       var $hasGenID = true;\r
-       var $_bindInputArray = true;\r
-       var $buffers = 0;\r
-       var $dialect = 1;\r
-       var $sysDate = "cast('TODAY' as date)";\r
-       var $sysTimeStamp = "cast('NOW' as timestamp)";\r
-       var $ansiOuter = true;\r
-       var $hasAffectedRows = false;\r
-       var $poorAffectedRows = true;\r
-       var $blobEncodeType = 'C';\r
-       \r
-       function ADODB_ibase() \r
-       {\r
-                if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT;\r
-       }\r
-       \r
-       function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false)\r
-       {       \r
-               if ($internalKey) return array('RDB$DB_KEY');\r
-               \r
-               $table = strtoupper($table);\r
-               \r
-               $sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME\r
-       FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME  \r
-       WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\'\r
-       ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION';\r
-\r
-               $a = $this->GetCol($sql,false,true);\r
-               if ($a && sizeof($a)>0) return $a;\r
-               return false;     \r
-       }\r
-       \r
-       function ServerInfo()\r
-       {\r
-               $arr['dialect'] = $this->dialect;\r
-               switch($arr['dialect']) {\r
-               case '': \r
-               case '1': $s = 'Interbase 5.5 or earlier'; break;\r
-               case '2': $s = 'Interbase 5.6'; break;\r
-               default:\r
-               case '3': $s = 'Interbase 6.0'; break;\r
-               }\r
-               $arr['version'] = ADOConnection::_findvers($s);\r
-               $arr['description'] = $s;\r
-               return $arr;\r
-       }\r
-\r
-       function BeginTrans()\r
-       {        \r
-               if ($this->transOff) return true;\r
-               $this->transCnt += 1;\r
-               $this->autoCommit = false;\r
-               $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID);\r
-               return $this->_transactionID;\r
-       }\r
-       \r
-       function CommitTrans($ok=true) \r
-       { \r
-               if (!$ok) return $this->RollbackTrans();\r
-               if ($this->transOff) return true;\r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $ret = false;\r
-               $this->autoCommit = true;\r
-               if ($this->_transactionID) {\r
-                                       //print ' commit ';\r
-                       $ret = ibase_commit($this->_transactionID);\r
-               }\r
-               $this->_transactionID = false;\r
-               return $ret;\r
-       }\r
-       \r
-       function RollbackTrans()\r
-       {\r
-               if ($this->transOff) return true;\r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $ret = false;\r
-               $this->autoCommit = true;\r
-               if ($this->_transactionID) \r
-                                 $ret = ibase_rollback($this->_transactionID);\r
-               $this->_transactionID = false;   \r
-               \r
-               return $ret;\r
-       }\r
-       \r
-       function &MetaIndexes ($table, $primary = FALSE, $owner=false)\r
-       {\r
-        // save old fetch mode\r
-        global $ADODB_FETCH_MODE;\r
-        \r
-        $save = $ADODB_FETCH_MODE;\r
-        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-        if ($this->fetchMode !== FALSE) {\r
-               $savem = $this->SetFetchMode(FALSE);\r
-        }\r
-        $table = strtoupper($table);\r
-        $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'";\r
-        if (!$primary) {\r
-               $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'";\r
-        } else {\r
-               $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'";\r
-        }\r
-        // get index details\r
-        $rs = $this->Execute($sql);\r
-        if (!is_object($rs)) {\r
-               // restore fetchmode\r
-               if (isset($savem)) {\r
-                   $this->SetFetchMode($savem);\r
-               }\r
-               $ADODB_FETCH_MODE = $save;\r
-            return FALSE;\r
-        }\r
-        \r
-        $indexes = array ();\r
-               while ($row = $rs->FetchRow()) {\r
-                       $index = $row[0];\r
-             if (!isset($indexes[$index])) {\r
-                       if (is_null($row[3])) {$row[3] = 0;}\r
-                     $indexes[$index] = array(\r
-                             'unique' => ($row[3] == 1),\r
-                             'columns' => array()\r
-                     );\r
-             }\r
-                       $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$name."' ORDER BY RDB\$FIELD_POSITION ASC";\r
-                       $rs1 = $this->Execute($sql);\r
-            while ($row1 = $rs1->FetchRow()) {\r
-               $indexes[$index]['columns'][$row1[2]] = $row1[1];\r
-               }\r
-               }\r
-        // restore fetchmode\r
-        if (isset($savem)) {\r
-            $this->SetFetchMode($savem);\r
-        }\r
-        $ADODB_FETCH_MODE = $save;\r
-        \r
-        return $indexes;\r
-       }\r
-\r
-       \r
-       // See http://community.borland.com/article/0,1410,25844,00.html\r
-       function RowLock($tables,$where,$col)\r
-       {\r
-               if ($this->autoCommit) $this->BeginTrans();\r
-               $this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim?\r
-               return 1;\r
-       }\r
-       \r
-       \r
-       function CreateSequence($seqname,$startID=1)\r
-       {\r
-               $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));\r
-               if (!$ok) return false;\r
-               return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');\r
-       }\r
-       \r
-       function DropSequence($seqname)\r
-       {\r
-               $seqname = strtoupper($seqname);\r
-               $this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'");\r
-       }\r
-       \r
-       function GenID($seqname='adodbseq',$startID=1)\r
-       {\r
-               $getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE");\r
-               $rs = @$this->Execute($getnext);\r
-               if (!$rs) {\r
-                       $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));\r
-                       $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');\r
-                       $rs = $this->Execute($getnext);\r
-               }\r
-               if ($rs && !$rs->EOF) $this->genID = (integer) reset($rs->fields);\r
-               else $this->genID = 0; // false\r
-               \r
-               if ($rs) $rs->Close();\r
-               \r
-               return $this->genID;\r
-       }\r
-\r
-       function SelectDB($dbName) \r
-       {\r
-                  return false;\r
-       }\r
-\r
-       function _handleerror()\r
-       {\r
-               $this->_errorMsg = ibase_errmsg();\r
-       }\r
-\r
-       function ErrorNo() \r
-       {\r
-               if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg,$arr)) return (integer) $arr[1];\r
-               else return 0;\r
-       }\r
-\r
-       function ErrorMsg() \r
-       {\r
-                       return $this->_errorMsg;\r
-       }\r
-\r
-          // returns true or false\r
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {  \r
-               if (!function_exists('ibase_pconnect')) return false;\r
-               if ($argDatabasename) $argHostname .= ':'.$argDatabasename;\r
-               $this->_connectionID = ibase_connect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);\r
-               if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html\r
-                       $this->replaceQuote = "''";\r
-               }\r
-               if ($this->_connectionID === false) {\r
-                       $this->_handleerror();\r
-                       return false;\r
-               }\r
-               \r
-               ibase_timefmt($this->ibase_timefmt);    \r
-               return true;\r
-       }\r
-          // returns true or false\r
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (!function_exists('ibase_pconnect')) return false;\r
-               if ($argDatabasename) $argHostname .= ':'.$argDatabasename;\r
-               $this->_connectionID = ibase_pconnect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);\r
-               if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html\r
-                       $this->replaceQuote = "''";\r
-               }\r
-               if ($this->_connectionID === false) {\r
-                       $this->_handleerror();\r
-                       return false;\r
-               }\r
-               \r
-               ibase_timefmt($this->ibase_timefmt);\r
-               return true;\r
-       }       \r
-       \r
-       function Prepare($sql)\r
-       {\r
-       //      return $sql;\r
-               $stmt = ibase_prepare($this->_connectionID,$sql);\r
-               if (!$stmt) return false;\r
-               return array($sql,$stmt);\r
-       }\r
-\r
-          // returns query ID if successful, otherwise false\r
-          // there have been reports of problems with nested queries - the code is probably not re-entrant?\r
-       function _query($sql,$iarr=false)\r
-       { \r
-\r
-               if (!$this->autoCommit && $this->_transactionID) {\r
-                       $conn = $this->_transactionID;\r
-                       $docommit = false;\r
-               } else {\r
-                       $conn = $this->_connectionID;\r
-                       $docommit = true;\r
-               }\r
-               if (is_array($sql)) {\r
-                       $fn = 'ibase_execute';\r
-                       $sql = $sql[1];\r
-                       \r
-                       if (is_array($iarr)) {  \r
-                               if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4\r
-                                       $fnarr =& array_merge( array($sql) , $iarr);\r
-                                       $ret = call_user_func_array($fn,$fnarr);\r
-                               } else {\r
-                                       switch(sizeof($iarr)) {\r
-                                       case 1: $ret = $fn($sql,$iarr[0]); break;\r
-                                       case 2: $ret = $fn($sql,$iarr[0],$iarr[1]); break;\r
-                                       case 3: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2]); break;\r
-                                       case 4: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;\r
-                                       case 5: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;\r
-                                       case 6: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;\r
-                                       case 7: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;\r
-                                       default: ADOConnection::outp( "Too many parameters to ibase query $sql");\r
-                                       case 8: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;\r
-                                       }\r
-                               }\r
-                       } else $ret = $fn($sql); \r
-               } else {\r
-                       $fn = 'ibase_query';\r
-               \r
-                       if (is_array($iarr)) {  \r
-                               if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4\r
-                                       $fnarr =& array_merge( array($conn,$sql) , $iarr);\r
-                                       $ret = call_user_func_array($fn,$fnarr);\r
-                               } else {\r
-                                       switch(sizeof($iarr)) {\r
-                                       case 1: $ret = $fn($conn,$sql,$iarr[0]); break;\r
-                                       case 2: $ret = $fn($conn,$sql,$iarr[0],$iarr[1]); break;\r
-                                       case 3: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2]); break;\r
-                                       case 4: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;\r
-                                       case 5: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;\r
-                                       case 6: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;\r
-                                       case 7: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;\r
-                                       default: ADOConnection::outp( "Too many parameters to ibase query $sql");\r
-                                       case 8: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;\r
-                                       }\r
-                               }\r
-                       } else $ret = $fn($conn,$sql); \r
-               }\r
-               if ($docommit && $ret === true) ibase_commit($this->_connectionID);\r
-\r
-               $this->_handleerror();\r
-               return $ret;\r
-       }\r
-\r
-        // returns true or false\r
-        function _close()\r
-        {         \r
-               if (!$this->autoCommit) @ibase_rollback($this->_connectionID);\r
-               return @ibase_close($this->_connectionID);\r
-        }\r
-       \r
-       //OPN STUFF start\r
-       function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $isInterbase6)\r
-       {\r
-               $fscale = abs($fscale);\r
-               $fld->max_length = $flen;\r
-               $fld->scale = null;\r
-               switch($ftype){\r
-                       case 7: \r
-                       case 8:\r
-                               if ($isInterbase6) {\r
-                                   switch($fsubtype){\r
-                                       case 0: \r
-                                               $fld->type = ($ftype == 7 ? 'smallint' : 'integer');\r
-                                               break;\r
-                                       case 1: \r
-                                               $fld->type = 'numeric';\r
-                                                       $fld->max_length = $fprecision;\r
-                                                       $fld->scale = $fscale;\r
-                                               break;\r
-                                       case 2:\r
-                                               $fld->type = 'decimal';\r
-                                                       $fld->max_length = $fprecision;\r
-                                                       $fld->scale = $fscale;\r
-                                               break;\r
-                                   } // switch\r
-                               } else {\r
-                                       if ($fscale !=0) {\r
-                                           $fld->type = 'decimal';\r
-                                               $fld->scale = $fscale;\r
-                                               $fld->max_length = ($ftype == 7 ? 4 : 9);\r
-                                       } else {\r
-                                               $fld->type = ($ftype == 7 ? 'smallint' : 'integer');\r
-                                       }\r
-                               }\r
-                               break;\r
-                       case 16: \r
-                               if ($isInterbase6) {\r
-                                   switch($fsubtype){\r
-                                       case 0: \r
-                                               $fld->type = 'decimal';\r
-                                                       $fld->max_length = 18;\r
-                                                       $fld->scale = 0;\r
-                                               break;\r
-                                       case 1: \r
-                                               $fld->type = 'numeric';\r
-                                                       $fld->max_length = $fprecision;\r
-                                                       $fld->scale = $fscale;\r
-                                               break;\r
-                                       case 2:\r
-                                               $fld->type = 'decimal';\r
-                                                       $fld->max_length = $fprecision;\r
-                                                       $fld->scale = $fscale;\r
-                                               break;\r
-                                   } // switch\r
-                               }\r
-                               break;\r
-                       case 10:\r
-                               $fld->type = 'float';\r
-                               break;\r
-                       case 14:\r
-                               $fld->type = 'char';\r
-                               break;\r
-                       case 27:\r
-                               if ($fscale !=0) {\r
-                                   $fld->type = 'decimal';\r
-                                       $fld->max_length = 15;\r
-                                       $fld->scale = 5;\r
-                               } else {\r
-                                       $fld->type = 'double';\r
-                               }\r
-                               break;\r
-                       case 35:\r
-                               if ($isInterbase6) {\r
-                                   $fld->type = 'timestamp';\r
-                               } else {\r
-                                       $fld->type = 'date';\r
-                               }\r
-                               break;\r
-                       case 12:\r
-                       case 13:\r
-                               $fld->type = 'date';\r
-                               break;\r
-                       case 37:\r
-                               $fld->type = 'varchar';\r
-                               break;\r
-                       case 40:\r
-                               $fld->type = 'cstring';\r
-                               break;\r
-                       case 261:\r
-                               $fld->type = 'blob';\r
-                               $fld->max_length = -1;\r
-                               break;\r
-               } // switch\r
-       }\r
-       //OPN STUFF end\r
-               // returns array of ADOFieldObjects for current table\r
-       function &MetaColumns($table) \r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-               \r
-               if ($this->metaColumnsSQL) {\r
-               \r
-                       $save = $ADODB_FETCH_MODE;\r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               \r
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));\r
-               \r
-                       $ADODB_FETCH_MODE = $save;\r
-                       if ($rs === false) return false;\r
-\r
-                       $retarr = array();\r
-                       //OPN STUFF start\r
-                       $isInterbase6 = ($this->dialect==3 ? true : false);\r
-                       //OPN STUFF end\r
-                       while (!$rs->EOF) { //print_r($rs->fields);\r
-                               $fld = new ADOFieldObject();\r
-                               $fld->name = trim($rs->fields[0]);\r
-                               //OPN STUFF start\r
-                               $this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $isInterbase6);\r
-                               if (isset($rs->fields[1]) && $rs->fields[1]) {\r
-                                       $fld->not_null = true;\r
-                               }                               \r
-                               if (isset($rs->fields[2])) {\r
-                                       \r
-                                       $fld->has_default = true;\r
-                                       $d = substr($rs->fields[2],strlen('default '));\r
-                                       switch ($fld->type)\r
-                                       {\r
-                                       case 'smallint':\r
-                                       case 'integer': $fld->default_value = (int) $d; break;\r
-                                       case 'char': \r
-                                       case 'blob':\r
-                                       case 'text':\r
-                                       case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break;\r
-                                       case 'double':\r
-                                       case 'float': $fld->default_value = (float) $d; break;\r
-                                       default: $fld->default_value = $d; break;\r
-                                       }\r
-                       //      case 35:$tt = 'TIMESTAMP'; break;\r
-                               }\r
-                               if ((isset($rs->fields[5])) && ($fld->type == 'blob')) {\r
-                                       $fld->sub_type = $rs->fields[5];\r
-                               } else {\r
-                                       $fld->sub_type = null;\r
-                               }\r
-                               //OPN STUFF end\r
-                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
-                               else $retarr[strtoupper($fld->name)] = $fld;\r
-                               \r
-                               $rs->MoveNext();\r
-                       }\r
-                       $rs->Close();\r
-                       return $retarr; \r
-               }\r
-               return false;\r
-       }\r
-       \r
-       function BlobEncode( $blob ) \r
-       {\r
-               $blobid = ibase_blob_create( $this->_connectionID);\r
-               ibase_blob_add( $blobid, $blob );\r
-               return ibase_blob_close( $blobid );\r
-       }\r
-       \r
-       // since we auto-decode all blob's since 2.42, \r
-       // BlobDecode should not do any transforms\r
-       function BlobDecode($blob)\r
-       {\r
-               return $blob; \r
-       }\r
-       \r
-       \r
-       \r
-       \r
-       // old blobdecode function\r
-       // still used to auto-decode all blob's\r
-       function _BlobDecode( $blob ) \r
-       {\r
-               $blobid = ibase_blob_open( $blob );\r
-               $realblob = ibase_blob_get( $blobid,$this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>\r
-               while($string = ibase_blob_get($blobid, 8192)){ \r
-                       $realblob .= $string; \r
-               }\r
-               ibase_blob_close( $blobid );\r
-\r
-               return( $realblob );\r
-       } \r
-       \r
-       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') \r
-       { \r
-               $fd = fopen($path,'rb'); \r
-               if ($fd === false) return false; \r
-               $blob_id = ibase_blob_create($this->_connectionID); \r
-               \r
-               /* fill with data */ \r
-               \r
-               while ($val = fread($fd,32768)){ \r
-                       ibase_blob_add($blob_id, $val); \r
-               } \r
-               \r
-               /* close and get $blob_id_str for inserting into table */ \r
-               $blob_id_str = ibase_blob_close($blob_id); \r
-               \r
-               fclose($fd); \r
-               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; \r
-       } \r
-       \r
-       /*\r
-               Insert a null into the blob field of the table first.\r
-               Then use UpdateBlob to store the blob.\r
-               \r
-               Usage:\r
-                \r
-               $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
-               $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
-       */\r
-       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') \r
-       { \r
-       $blob_id = ibase_blob_create($this->_connectionID); \r
-       \r
-       // ibase_blob_add($blob_id, $val); \r
-       \r
-       // replacement that solves the problem by which only the first modulus 64K / \r
-       // of $val are stored at the blob field //////////////////////////////////// \r
-       // Thx Abel Berenstein  aberenstein#afip.gov.ar\r
-       $len = strlen($val); \r
-       $chunk_size = 32768; \r
-       $tail_size = $len % $chunk_size; \r
-       $n_chunks = ($len - $tail_size) / $chunk_size; \r
-       \r
-       for ($n = 0; $n < $n_chunks; $n++) { \r
-               $start = $n * $chunk_size; \r
-               $data = substr($val, $start, $chunk_size); \r
-               ibase_blob_add($blob_id, $data); \r
-       } \r
-       \r
-       if ($tail_size) {\r
-               $start = $n_chunks * $chunk_size; \r
-               $data = substr($val, $start, $tail_size); \r
-               ibase_blob_add($blob_id, $data); \r
-       }\r
-       // end replacement ///////////////////////////////////////////////////////// \r
-       \r
-       $blob_id_str = ibase_blob_close($blob_id); \r
-       \r
-       return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; \r
-       \r
-       } \r
-       \r
-       \r
-       function OldUpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
-       {\r
-               $blob_id = ibase_blob_create($this->_connectionID);\r
-               ibase_blob_add($blob_id, $val);\r
-               $blob_id_str = ibase_blob_close($blob_id);\r
-               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;\r
-       }\r
-       \r
-       // Format date column in sql string given an input format that understands Y M D\r
-       // Only since Interbase 6.0 - uses EXTRACT\r
-       // problem - does not zero-fill the day and month yet\r
-       function SQLDate($fmt, $col=false)\r
-       {       \r
-               if (!$col) $col = $this->sysDate;\r
-               $s = '';\r
-               \r
-               $len = strlen($fmt);\r
-               for ($i=0; $i < $len; $i++) {\r
-                       if ($s) $s .= '||';\r
-                       $ch = $fmt[$i];\r
-                       switch($ch) {\r
-                       case 'Y':\r
-                       case 'y':\r
-                               $s .= "extract(year from $col)";\r
-                               break;\r
-                       case 'M':\r
-                       case 'm':\r
-                               $s .= "extract(month from $col)";\r
-                               break;\r
-                       case 'Q':\r
-                       case 'q':\r
-                               $s .= "cast(((extract(month from $col)+2) / 3) as integer)";\r
-                               break;\r
-                       case 'D':\r
-                       case 'd':\r
-                               $s .= "(extract(day from $col))";\r
-                               break;\r
-                       case 'H':\r
-                       case 'h':\r
-                         $s .= "(extract(hour from $col))";\r
-                         break;                        \r
-                       case 'I':\r
-                       case 'i':\r
-                         $s .= "(extract(minute from $col))";\r
-                         break;                \r
-                       case 'S':\r
-                       case 's':\r
-                         $s .= "CAST((extract(second from $col)) AS INTEGER)";\r
-                         break;        \r
-\r
-                       default:\r
-                               if ($ch == '\\') {\r
-                                       $i++;\r
-                                       $ch = substr($fmt,$i,1);\r
-                               }\r
-                               $s .= $this->qstr($ch);\r
-                               break;\r
-                       }\r
-               }\r
-               return $s;\r
-       }\r
-}\r
-\r
-/*--------------------------------------------------------------------------------------\r
-                Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordset_ibase extends ADORecordSet \r
-{\r
-\r
-       var $databaseType = "ibase";\r
-       var $bind=false;\r
-       var $_cacheType;\r
-       \r
-       function ADORecordset_ibase($id,$mode=false)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-                       $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode;\r
-                       return $this->ADORecordSet($id);\r
-       }\r
-\r
-       /*              Returns: an object containing field information.\r
-                       Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
-                       fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
-                       fetchField() is retrieved.              */\r
-\r
-       function &FetchField($fieldOffset = -1)\r
-       {\r
-                        $fld = new ADOFieldObject;\r
-                        $ibf = ibase_field_info($this->_queryID,$fieldOffset);\r
-                        $fld->name = strtolower($ibf['alias']);\r
-                        if (empty($fld->name)) $fld->name = strtolower($ibf['name']);\r
-                        $fld->type = $ibf['type'];\r
-                        $fld->max_length = $ibf['length'];\r
-                        return $fld;\r
-       }\r
-\r
-       function _initrs()\r
-       {\r
-                       $this->_numOfRows = -1;\r
-                       $this->_numOfFields = @ibase_num_fields($this->_queryID);\r
-                       \r
-                       // cache types for blob decode check\r
-                       for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { \r
-                               $f1 = $this->FetchField($i); \r
-                               $this->_cacheType[] = $f1->type;\r
-                       }                               \r
-       }\r
-\r
-       function _seek($row)\r
-       {\r
-               return false;\r
-       }\r
-\r
-       \r
-       \r
-       function _fetch() \r
-       {\r
-               $f = @ibase_fetch_row($this->_queryID); \r
-               if ($f === false) {\r
-                       $this->fields = false;\r
-                       return false;\r
-               }\r
-               // OPN stuff start - optimized\r
-               // fix missing nulls and decode blobs automatically\r
-       \r
-               global $ADODB_ANSI_PADDING_OFF;\r
-               //$ADODB_ANSI_PADDING_OFF=1;\r
-               $rtrim = !empty($ADODB_ANSI_PADDING_OFF);\r
-               \r
-               for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { \r
-                       if ($this->_cacheType[$i]=="BLOB") {\r
-                               if (isset($f[$i])) { \r
-                                       $f[$i] = $this->connection->_BlobDecode($f[$i]); \r
-                               } else { \r
-                                       $f[$i] = null; \r
-                               } \r
-                       } else { \r
-                               if (!isset($f[$i])) { \r
-                                       $f[$i] = null; \r
-                               } else if ($rtrim && is_string($f[$i])) {\r
-                                       $f[$i] = rtrim($f[$i]);\r
-                               }\r
-                       } \r
-               } \r
-               // OPN stuff end \r
-               \r
-               $this->fields = $f;\r
-               if ($this->fetchMode == ADODB_FETCH_ASSOC) {\r
-                       $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);\r
-               } else if ($this->fetchMode == ADODB_FETCH_BOTH) {\r
-                       $this->fields =& array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE));\r
-               }\r
-               return true;\r
-       }\r
-\r
-       /* Use associative array to get fields array */\r
-       function Fields($colname)\r
-       {\r
-               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];\r
-               if (!$this->bind) {\r
-                       $this->bind = array();\r
-                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                               $o = $this->FetchField($i);\r
-                               $this->bind[strtoupper($o->name)] = $i;\r
-                       }\r
-               }\r
-               \r
-                return $this->fields[$this->bind[strtoupper($colname)]];\r
-               \r
-       }\r
-       \r
-\r
-       function _close() \r
-       {\r
-                       return @ibase_free_result($this->_queryID);\r
-       }\r
-\r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               switch (strtoupper($t)) {\r
-               case 'CHAR':\r
-                       return 'C';\r
-                       \r
-               case 'TEXT':\r
-               case 'VARCHAR':\r
-               case 'VARYING':\r
-               if ($len <= $this->blobSize) return 'C';\r
-                       return 'X';\r
-               case 'BLOB':\r
-                       return 'B';\r
-                          \r
-               case 'TIMESTAMP':\r
-               case 'DATE': return 'D';\r
-                               \r
-                               //case 'T': return 'T';\r
-\r
-                               //case 'L': return 'L';\r
-               case 'INT': \r
-               case 'SHORT':\r
-               case 'INTEGER': return 'I';\r
-               default: return 'N';\r
-               }\r
-       }\r
-\r
-}\r
+<?php
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.  
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+
+  Latest version is available at http://php.weblogs.com/
+  
+  Interbase data driver. Requires interbase client. Works on Windows and Unix.
+
+  3 Jan 2002 -- suggestions by Hans-Peter Oeri <kampfcaspar75@oeri.ch>
+       changed transaction handling and added experimental blob stuff
+  
+  Docs to interbase at the website
+   http://www.synectics.co.za/php3/tutorial/IB_PHP3_API.html
+   
+  To use gen_id(), see
+   http://www.volny.cz/iprenosil/interbase/ip_ib_code.htm#_code_creategen
+   
+   $rs = $conn->Execute('select gen_id(adodb,1) from rdb$database');
+   $id = $rs->fields[0];
+   $conn->Execute("insert into table (id, col1,...) values ($id, $val1,...)");
+*/
+
+
+class ADODB_ibase extends ADOConnection {
+       var $databaseType = "ibase";
+       var $dataProvider = "ibase";
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $ibase_timefmt = '%Y-%m-%d'; // For hours,mins,secs change to '%Y-%m-%d %H:%M:%S';
+       var $fmtDate = "'Y-m-d'";
+       var $fmtTimeStamp = "'Y-m-d, H:i:s'";
+       var $concat_operator='||';
+       var $_transactionID;
+       var $metaTablesSQL = "select rdb\$relation_name from rdb\$relations where rdb\$relation_name not like 'RDB\$%'";
+       //OPN STUFF start
+       var $metaColumnsSQL = "select a.rdb\$field_name, a.rdb\$null_flag, a.rdb\$default_source, b.rdb\$field_length, b.rdb\$field_scale, b.rdb\$field_sub_type, b.rdb\$field_precision, b.rdb\$field_type from rdb\$relation_fields a, rdb\$fields b where a.rdb\$field_source = b.rdb\$field_name and a.rdb\$relation_name = '%s' order by a.rdb\$field_position asc";
+       //OPN STUFF end
+       var $ibasetrans;
+       var $hasGenID = true;
+       var $_bindInputArray = true;
+       var $buffers = 0;
+       var $dialect = 1;
+       var $sysDate = "cast('TODAY' as date)";
+       var $sysTimeStamp = "cast('NOW' as timestamp)";
+       var $ansiOuter = true;
+       var $hasAffectedRows = false;
+       var $poorAffectedRows = true;
+       var $blobEncodeType = 'C';
+       
+       function ADODB_ibase() 
+       {
+                if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT;
+       }
+       
+       function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false)
+       {       
+               if ($internalKey) return array('RDB$DB_KEY');
+               
+               $table = strtoupper($table);
+               
+               $sql = 'SELECT S.RDB$FIELD_NAME AFIELDNAME
+       FROM RDB$INDICES I JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME=S.RDB$INDEX_NAME  
+       WHERE I.RDB$RELATION_NAME=\''.$table.'\' and I.RDB$INDEX_NAME like \'RDB$PRIMARY%\'
+       ORDER BY I.RDB$INDEX_NAME,S.RDB$FIELD_POSITION';
+
+               $a = $this->GetCol($sql,false,true);
+               if ($a && sizeof($a)>0) return $a;
+               return false;     
+       }
+       
+       function ServerInfo()
+       {
+               $arr['dialect'] = $this->dialect;
+               switch($arr['dialect']) {
+               case '': 
+               case '1': $s = 'Interbase 5.5 or earlier'; break;
+               case '2': $s = 'Interbase 5.6'; break;
+               default:
+               case '3': $s = 'Interbase 6.0'; break;
+               }
+               $arr['version'] = ADOConnection::_findvers($s);
+               $arr['description'] = $s;
+               return $arr;
+       }
+
+       function BeginTrans()
+       {        
+               if ($this->transOff) return true;
+               $this->transCnt += 1;
+               $this->autoCommit = false;
+               $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID);
+               return $this->_transactionID;
+       }
+       
+       function CommitTrans($ok=true) 
+       { 
+               if (!$ok) return $this->RollbackTrans();
+               if ($this->transOff) return true;
+               if ($this->transCnt) $this->transCnt -= 1;
+               $ret = false;
+               $this->autoCommit = true;
+               if ($this->_transactionID) {
+                                       //print ' commit ';
+                       $ret = ibase_commit($this->_transactionID);
+               }
+               $this->_transactionID = false;
+               return $ret;
+       }
+       
+       function RollbackTrans()
+       {
+               if ($this->transOff) return true;
+               if ($this->transCnt) $this->transCnt -= 1;
+               $ret = false;
+               $this->autoCommit = true;
+               if ($this->_transactionID) 
+                                 $ret = ibase_rollback($this->_transactionID);
+               $this->_transactionID = false;   
+               
+               return $ret;
+       }
+       
+       function &MetaIndexes ($table, $primary = FALSE, $owner=false)
+       {
+        // save old fetch mode
+        global $ADODB_FETCH_MODE;
+        
+        $save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+        if ($this->fetchMode !== FALSE) {
+               $savem = $this->SetFetchMode(FALSE);
+        }
+        $table = strtoupper($table);
+        $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'";
+        if (!$primary) {
+               $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'";
+        } else {
+               $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'";
+        }
+        // get index details
+        $rs = $this->Execute($sql);
+        if (!is_object($rs)) {
+               // restore fetchmode
+               if (isset($savem)) {
+                   $this->SetFetchMode($savem);
+               }
+               $ADODB_FETCH_MODE = $save;
+            return FALSE;
+        }
+        
+        $indexes = array ();
+               while ($row = $rs->FetchRow()) {
+                       $index = $row[0];
+             if (!isset($indexes[$index])) {
+                       if (is_null($row[3])) {$row[3] = 0;}
+                     $indexes[$index] = array(
+                             'unique' => ($row[3] == 1),
+                             'columns' => array()
+                     );
+             }
+                       $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$name."' ORDER BY RDB\$FIELD_POSITION ASC";
+                       $rs1 = $this->Execute($sql);
+            while ($row1 = $rs1->FetchRow()) {
+               $indexes[$index]['columns'][$row1[2]] = $row1[1];
+               }
+               }
+        // restore fetchmode
+        if (isset($savem)) {
+            $this->SetFetchMode($savem);
+        }
+        $ADODB_FETCH_MODE = $save;
+        
+        return $indexes;
+       }
+
+       
+       // See http://community.borland.com/article/0,1410,25844,00.html
+       function RowLock($tables,$where,$col)
+       {
+               if ($this->autoCommit) $this->BeginTrans();
+               $this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim?
+               return 1;
+       }
+       
+       
+       function CreateSequence($seqname,$startID=1)
+       {
+               $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
+               if (!$ok) return false;
+               return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
+       }
+       
+       function DropSequence($seqname)
+       {
+               $seqname = strtoupper($seqname);
+               $this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'");
+       }
+       
+       function GenID($seqname='adodbseq',$startID=1)
+       {
+               $getnext = ("SELECT Gen_ID($seqname,1) FROM RDB\$DATABASE");
+               $rs = @$this->Execute($getnext);
+               if (!$rs) {
+                       $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" ));
+                       $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';');
+                       $rs = $this->Execute($getnext);
+               }
+               if ($rs && !$rs->EOF) $this->genID = (integer) reset($rs->fields);
+               else $this->genID = 0; // false
+               
+               if ($rs) $rs->Close();
+               
+               return $this->genID;
+       }
+
+       function SelectDB($dbName) 
+       {
+                  return false;
+       }
+
+       function _handleerror()
+       {
+               $this->_errorMsg = ibase_errmsg();
+       }
+
+       function ErrorNo() 
+       {
+               if (preg_match('/error code = ([\-0-9]*)/i', $this->_errorMsg,$arr)) return (integer) $arr[1];
+               else return 0;
+       }
+
+       function ErrorMsg() 
+       {
+                       return $this->_errorMsg;
+       }
+
+          // returns true or false
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {  
+               if (!function_exists('ibase_pconnect')) return false;
+               if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
+               $this->_connectionID = ibase_connect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);
+               if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
+                       $this->replaceQuote = "''";
+               }
+               if ($this->_connectionID === false) {
+                       $this->_handleerror();
+                       return false;
+               }
+               
+               ibase_timefmt($this->ibase_timefmt);    
+               return true;
+       }
+          // returns true or false
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (!function_exists('ibase_pconnect')) return false;
+               if ($argDatabasename) $argHostname .= ':'.$argDatabasename;
+               $this->_connectionID = ibase_pconnect($argHostname,$argUsername,$argPassword,$this->charSet,$this->buffers,$this->dialect);
+               if ($this->dialect != 1) { // http://www.ibphoenix.com/ibp_60_del_id_ds.html
+                       $this->replaceQuote = "''";
+               }
+               if ($this->_connectionID === false) {
+                       $this->_handleerror();
+                       return false;
+               }
+               
+               ibase_timefmt($this->ibase_timefmt);
+               return true;
+       }       
+       
+       function Prepare($sql)
+       {
+               $stmt = ibase_prepare($this->_connectionID,$sql);
+               if (!$stmt) return false;
+               return array($sql,$stmt);
+       }
+
+          // returns query ID if successful, otherwise false
+          // there have been reports of problems with nested queries - the code is probably not re-entrant?
+       function _query($sql,$iarr=false)
+       { 
+
+               if (!$this->autoCommit && $this->_transactionID) {
+                       $conn = $this->_transactionID;
+                       $docommit = false;
+               } else {
+                       $conn = $this->_connectionID;
+                       $docommit = true;
+               }
+               if (is_array($sql)) {
+                       $fn = 'ibase_execute';
+                       $sql = $sql[1];
+                       
+                       if (is_array($iarr)) {  
+                               if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
+                                       $fnarr =& array_merge( array($sql) , $iarr);
+                                       $ret = call_user_func_array($fn,$fnarr);
+                               } else {
+                                       switch(sizeof($iarr)) {
+                                       case 1: $ret = $fn($sql,$iarr[0]); break;
+                                       case 2: $ret = $fn($sql,$iarr[0],$iarr[1]); break;
+                                       case 3: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2]); break;
+                                       case 4: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
+                                       case 5: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
+                                       case 6: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
+                                       case 7: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
+                                       default: ADOConnection::outp( "Too many parameters to ibase query $sql");
+                                       case 8: $ret = $fn($sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
+                                       }
+                               }
+                       } else $ret = $fn($sql); 
+               } else {
+                       $fn = 'ibase_query';
+               
+                       if (is_array($iarr)) {  
+                               if (ADODB_PHPVER >= 0x4050) { // actually 4.0.4
+                                       $fnarr =& array_merge( array($conn,$sql) , $iarr);
+                                       $ret = call_user_func_array($fn,$fnarr);
+                               } else {
+                                       switch(sizeof($iarr)) {
+                                       case 1: $ret = $fn($conn,$sql,$iarr[0]); break;
+                                       case 2: $ret = $fn($conn,$sql,$iarr[0],$iarr[1]); break;
+                                       case 3: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2]); break;
+                                       case 4: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3]); break;
+                                       case 5: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4]); break;
+                                       case 6: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5]); break;
+                                       case 7: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6]); break;
+                                       default: ADOConnection::outp( "Too many parameters to ibase query $sql");
+                                       case 8: $ret = $fn($conn,$sql,$iarr[0],$iarr[1],$iarr[2],$iarr[3],$iarr[4],$iarr[5],$iarr[6],$iarr[7]); break;
+                                       }
+                               }
+                       } else $ret = $fn($conn,$sql); 
+               }
+               if ($docommit && $ret === true) ibase_commit($this->_connectionID);
+
+               $this->_handleerror();
+               return $ret;
+       }
+
+        // returns true or false
+        function _close()
+        {         
+               if (!$this->autoCommit) @ibase_rollback($this->_connectionID);
+               return @ibase_close($this->_connectionID);
+        }
+       
+       //OPN STUFF start
+       function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $isInterbase6)
+       {
+               $fscale = abs($fscale);
+               $fld->max_length = $flen;
+               $fld->scale = null;
+               switch($ftype){
+                       case 7: 
+                       case 8:
+                               if ($isInterbase6) {
+                                   switch($fsubtype){
+                                       case 0: 
+                                               $fld->type = ($ftype == 7 ? 'smallint' : 'integer');
+                                               break;
+                                       case 1: 
+                                               $fld->type = 'numeric';
+                                                       $fld->max_length = $fprecision;
+                                                       $fld->scale = $fscale;
+                                               break;
+                                       case 2:
+                                               $fld->type = 'decimal';
+                                                       $fld->max_length = $fprecision;
+                                                       $fld->scale = $fscale;
+                                               break;
+                                   } // switch
+                               } else {
+                                       if ($fscale !=0) {
+                                           $fld->type = 'decimal';
+                                               $fld->scale = $fscale;
+                                               $fld->max_length = ($ftype == 7 ? 4 : 9);
+                                       } else {
+                                               $fld->type = ($ftype == 7 ? 'smallint' : 'integer');
+                                       }
+                               }
+                               break;
+                       case 16: 
+                               if ($isInterbase6) {
+                                   switch($fsubtype){
+                                       case 0: 
+                                               $fld->type = 'decimal';
+                                                       $fld->max_length = 18;
+                                                       $fld->scale = 0;
+                                               break;
+                                       case 1: 
+                                               $fld->type = 'numeric';
+                                                       $fld->max_length = $fprecision;
+                                                       $fld->scale = $fscale;
+                                               break;
+                                       case 2:
+                                               $fld->type = 'decimal';
+                                                       $fld->max_length = $fprecision;
+                                                       $fld->scale = $fscale;
+                                               break;
+                                   } // switch
+                               }
+                               break;
+                       case 10:
+                               $fld->type = 'float';
+                               break;
+                       case 14:
+                               $fld->type = 'char';
+                               break;
+                       case 27:
+                               if ($fscale !=0) {
+                                   $fld->type = 'decimal';
+                                       $fld->max_length = 15;
+                                       $fld->scale = 5;
+                               } else {
+                                       $fld->type = 'double';
+                               }
+                               break;
+                       case 35:
+                               if ($isInterbase6) {
+                                   $fld->type = 'timestamp';
+                               } else {
+                                       $fld->type = 'date';
+                               }
+                               break;
+                       case 12:
+                       case 13:
+                               $fld->type = 'date';
+                               break;
+                       case 37:
+                               $fld->type = 'varchar';
+                               break;
+                       case 40:
+                               $fld->type = 'cstring';
+                               break;
+                       case 261:
+                               $fld->type = 'blob';
+                               $fld->max_length = -1;
+                               break;
+               } // switch
+       }
+       //OPN STUFF end
+               // returns array of ADOFieldObjects for current table
+       function &MetaColumns($table) 
+       {
+       global $ADODB_FETCH_MODE;
+               
+               if ($this->metaColumnsSQL) {
+               
+                       $save = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
+               
+                       $ADODB_FETCH_MODE = $save;
+                       if ($rs === false) return false;
+
+                       $retarr = array();
+                       //OPN STUFF start
+                       $isInterbase6 = ($this->dialect==3 ? true : false);
+                       //OPN STUFF end
+                       while (!$rs->EOF) { //print_r($rs->fields);
+                               $fld = new ADOFieldObject();
+                               $fld->name = trim($rs->fields[0]);
+                               //OPN STUFF start
+                               $this->_ConvertFieldType($fld, $rs->fields[7], $rs->fields[3], $rs->fields[4], $rs->fields[5], $rs->fields[6], $isInterbase6);
+                               if (isset($rs->fields[1]) && $rs->fields[1]) {
+                                       $fld->not_null = true;
+                               }                               
+                               if (isset($rs->fields[2])) {
+                                       
+                                       $fld->has_default = true;
+                                       $d = substr($rs->fields[2],strlen('default '));
+                                       switch ($fld->type)
+                                       {
+                                       case 'smallint':
+                                       case 'integer': $fld->default_value = (int) $d; break;
+                                       case 'char': 
+                                       case 'blob':
+                                       case 'text':
+                                       case 'varchar': $fld->default_value = (string) substr($d,1,strlen($d)-2); break;
+                                       case 'double':
+                                       case 'float': $fld->default_value = (float) $d; break;
+                                       default: $fld->default_value = $d; break;
+                                       }
+                       //      case 35:$tt = 'TIMESTAMP'; break;
+                               }
+                               if ((isset($rs->fields[5])) && ($fld->type == 'blob')) {
+                                       $fld->sub_type = $rs->fields[5];
+                               } else {
+                                       $fld->sub_type = null;
+                               }
+                               //OPN STUFF end
+                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     
+                               else $retarr[strtoupper($fld->name)] = $fld;
+                               
+                               $rs->MoveNext();
+                       }
+                       $rs->Close();
+                       return $retarr; 
+               }
+               return false;
+       }
+       
+       function BlobEncode( $blob ) 
+       {
+               $blobid = ibase_blob_create( $this->_connectionID);
+               ibase_blob_add( $blobid, $blob );
+               return ibase_blob_close( $blobid );
+       }
+       
+       // since we auto-decode all blob's since 2.42, 
+       // BlobDecode should not do any transforms
+       function BlobDecode($blob)
+       {
+               return $blob; 
+       }
+       
+       
+       
+       
+       // old blobdecode function
+       // still used to auto-decode all blob's
+       function _BlobDecode( $blob ) 
+       {
+               $blobid = ibase_blob_open( $blob );
+               $realblob = ibase_blob_get( $blobid,$this->maxblobsize); // 2nd param is max size of blob -- Kevin Boillet <kevinboillet@yahoo.fr>
+               while($string = ibase_blob_get($blobid, 8192)){ 
+                       $realblob .= $string; 
+               }
+               ibase_blob_close( $blobid );
+
+               return( $realblob );
+       } 
+       
+       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') 
+       { 
+               $fd = fopen($path,'rb'); 
+               if ($fd === false) return false; 
+               $blob_id = ibase_blob_create($this->_connectionID); 
+               
+               /* fill with data */ 
+               
+               while ($val = fread($fd,32768)){ 
+                       ibase_blob_add($blob_id, $val); 
+               } 
+               
+               /* close and get $blob_id_str for inserting into table */ 
+               $blob_id_str = ibase_blob_close($blob_id); 
+               
+               fclose($fd); 
+               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; 
+       } 
+       
+       /*
+               Insert a null into the blob field of the table first.
+               Then use UpdateBlob to store the blob.
+               
+               Usage:
+                
+               $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+               $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+       */
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') 
+       { 
+       $blob_id = ibase_blob_create($this->_connectionID); 
+       
+       // ibase_blob_add($blob_id, $val); 
+       
+       // replacement that solves the problem by which only the first modulus 64K / 
+       // of $val are stored at the blob field //////////////////////////////////// 
+       // Thx Abel Berenstein  aberenstein#afip.gov.ar
+       $len = strlen($val); 
+       $chunk_size = 32768; 
+       $tail_size = $len % $chunk_size; 
+       $n_chunks = ($len - $tail_size) / $chunk_size; 
+       
+       for ($n = 0; $n < $n_chunks; $n++) { 
+               $start = $n * $chunk_size; 
+               $data = substr($val, $start, $chunk_size); 
+               ibase_blob_add($blob_id, $data); 
+       } 
+       
+       if ($tail_size) {
+               $start = $n_chunks * $chunk_size; 
+               $data = substr($val, $start, $tail_size); 
+               ibase_blob_add($blob_id, $data); 
+       }
+       // end replacement ///////////////////////////////////////////////////////// 
+       
+       $blob_id_str = ibase_blob_close($blob_id); 
+       
+       return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false; 
+       
+       } 
+       
+       
+       function OldUpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+       {
+               $blob_id = ibase_blob_create($this->_connectionID);
+               ibase_blob_add($blob_id, $val);
+               $blob_id_str = ibase_blob_close($blob_id);
+               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;
+       }
+       
+       // Format date column in sql string given an input format that understands Y M D
+       // Only since Interbase 6.0 - uses EXTRACT
+       // problem - does not zero-fill the day and month yet
+       function SQLDate($fmt, $col=false)
+       {       
+               if (!$col) $col = $this->sysDate;
+               $s = '';
+               
+               $len = strlen($fmt);
+               for ($i=0; $i < $len; $i++) {
+                       if ($s) $s .= '||';
+                       $ch = $fmt[$i];
+                       switch($ch) {
+                       case 'Y':
+                       case 'y':
+                               $s .= "extract(year from $col)";
+                               break;
+                       case 'M':
+                       case 'm':
+                               $s .= "extract(month from $col)";
+                               break;
+                       case 'Q':
+                       case 'q':
+                               $s .= "cast(((extract(month from $col)+2) / 3) as integer)";
+                               break;
+                       case 'D':
+                       case 'd':
+                               $s .= "(extract(day from $col))";
+                               break;
+                       case 'H':
+                       case 'h':
+                         $s .= "(extract(hour from $col))";
+                         break;                        
+                       case 'I':
+                       case 'i':
+                         $s .= "(extract(minute from $col))";
+                         break;                
+                       case 'S':
+                       case 's':
+                         $s .= "CAST((extract(second from $col)) AS INTEGER)";
+                         break;        
+
+                       default:
+                               if ($ch == '\\') {
+                                       $i++;
+                                       $ch = substr($fmt,$i,1);
+                               }
+                               $s .= $this->qstr($ch);
+                               break;
+                       }
+               }
+               return $s;
+       }
+}
+
+/*--------------------------------------------------------------------------------------
+                Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_ibase extends ADORecordSet 
+{
+
+       var $databaseType = "ibase";
+       var $bind=false;
+       var $_cacheType;
+       
+       function ADORecordset_ibase($id,$mode=false)
+       {
+       global $ADODB_FETCH_MODE;
+       
+                       $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode;
+                       return $this->ADORecordSet($id);
+       }
+
+       /*              Returns: an object containing field information.
+                       Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+                       fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+                       fetchField() is retrieved.              */
+
+       function &FetchField($fieldOffset = -1)
+       {
+                        $fld = new ADOFieldObject;
+                        $ibf = ibase_field_info($this->_queryID,$fieldOffset);
+                        $fld->name = strtolower($ibf['alias']);
+                        if (empty($fld->name)) $fld->name = strtolower($ibf['name']);
+                        $fld->type = $ibf['type'];
+                        $fld->max_length = $ibf['length'];
+                        return $fld;
+       }
+
+       function _initrs()
+       {
+                       $this->_numOfRows = -1;
+                       $this->_numOfFields = @ibase_num_fields($this->_queryID);
+                       
+                       // cache types for blob decode check
+                       for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { 
+                               $f1 = $this->FetchField($i); 
+                               $this->_cacheType[] = $f1->type;
+                       }                               
+       }
+
+       function _seek($row)
+       {
+               return false;
+       }
+
+       
+       
+       function _fetch() 
+       {
+               $f = @ibase_fetch_row($this->_queryID); 
+               if ($f === false) {
+                       $this->fields = false;
+                       return false;
+               }
+               // OPN stuff start - optimized
+               // fix missing nulls and decode blobs automatically
+       
+               global $ADODB_ANSI_PADDING_OFF;
+               //$ADODB_ANSI_PADDING_OFF=1;
+               $rtrim = !empty($ADODB_ANSI_PADDING_OFF);
+               
+               for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { 
+                       if ($this->_cacheType[$i]=="BLOB") {
+                               if (isset($f[$i])) { 
+                                       $f[$i] = $this->connection->_BlobDecode($f[$i]); 
+                               } else { 
+                                       $f[$i] = null; 
+                               } 
+                       } else { 
+                               if (!isset($f[$i])) { 
+                                       $f[$i] = null; 
+                               } else if ($rtrim && is_string($f[$i])) {
+                                       $f[$i] = rtrim($f[$i]);
+                               }
+                       } 
+               } 
+               // OPN stuff end 
+               
+               $this->fields = $f;
+               if ($this->fetchMode == ADODB_FETCH_ASSOC) {
+                       $this->fields = &$this->GetRowAssoc(ADODB_ASSOC_CASE);
+               } else if ($this->fetchMode == ADODB_FETCH_BOTH) {
+                       $this->fields =& array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE));
+               }
+               return true;
+       }
+
+       /* Use associative array to get fields array */
+       function Fields($colname)
+       {
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+               if (!$this->bind) {
+                       $this->bind = array();
+                       for ($i=0; $i < $this->_numOfFields; $i++) {
+                               $o = $this->FetchField($i);
+                               $this->bind[strtoupper($o->name)] = $i;
+                       }
+               }
+               
+                return $this->fields[$this->bind[strtoupper($colname)]];
+               
+       }
+       
+
+       function _close() 
+       {
+                       return @ibase_free_result($this->_queryID);
+       }
+
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               switch (strtoupper($t)) {
+               case 'CHAR':
+                       return 'C';
+                       
+               case 'TEXT':
+               case 'VARCHAR':
+               case 'VARYING':
+               if ($len <= $this->blobSize) return 'C';
+                       return 'X';
+               case 'BLOB':
+                       return 'B';
+                          
+               case 'TIMESTAMP':
+               case 'DATE': return 'D';
+                               
+                               //case 'T': return 'T';
+
+                               //case 'L': return 'L';
+               case 'INT': 
+               case 'SHORT':
+               case 'INTEGER': return 'I';
+               default: return 'N';
+               }
+       }
+
+}
 ?>
\ No newline at end of file
index 0473f950028ea61c5fb812a0ae50046e05edf162..2f1bd3256df1aadb562fc25934049f9dd688fe2f 100644 (file)
@@ -1,30 +1,30 @@
-<?php\r
-/**\r
-* @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-* Released under both BSD license and Lesser GPL library license.\r
-* Whenever there is any discrepancy between the two licenses,\r
-* the BSD license will take precedence.\r
-*\r
-* Set tabs to 4 for best viewing.\r
-*\r
-* Latest version is available at http://php.weblogs.com\r
-*\r
-* Informix 9 driver that supports SELECT FIRST\r
-*\r
-*/\r
-include_once(ADODB_DIR.'/drivers/adodb-informix72.inc.php');\r
-\r
-class ADODB_informix extends ADODB_informix72 {\r
-       var $databaseType = "informix";\r
-       var $hasTop = 'FIRST';\r
-       var $ansiOuter = true;\r
-}\r
-\r
-class ADORecordset_informix extends ADORecordset_informix72 {\r
-       var $databaseType = "informix";\r
-       function ADORecordset_informix($id,$mode=false)\r
-       {\r
-               $this->ADORecordset_informix72($id,$mode);\r
-       }\r
-}\r
+<?php
+/**
+* @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+* Released under both BSD license and Lesser GPL library license.
+* Whenever there is any discrepancy between the two licenses,
+* the BSD license will take precedence.
+*
+* Set tabs to 4 for best viewing.
+*
+* Latest version is available at http://php.weblogs.com
+*
+* Informix 9 driver that supports SELECT FIRST
+*
+*/
+include_once(ADODB_DIR.'/drivers/adodb-informix72.inc.php');
+
+class ADODB_informix extends ADODB_informix72 {
+       var $databaseType = "informix";
+       var $hasTop = 'FIRST';
+       var $ansiOuter = true;
+}
+
+class ADORecordset_informix extends ADORecordset_informix72 {
+       var $databaseType = "informix";
+       function ADORecordset_informix($id,$mode=false)
+       {
+               $this->ADORecordset_informix72($id,$mode);
+       }
+}
 ?>
\ No newline at end of file
index f9110793544ba4ae1c3231e13c92433ce975ec5b..78228168149df0e291f5d477021affef4ee96d3f 100644 (file)
-<?php\r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim. All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license.\r
-  Whenever there is any discrepancy between the two licenses,\r
-  the BSD license will take precedence.\r
-  Set tabs to 4 for best viewing.\r
-\r
-  Latest version is available at http://php.weblogs.com/\r
-\r
-  Informix port by Mitchell T. Young (mitch@youngfamily.org)\r
-\r
-  Further mods by "Samuel CARRIERE" <samuel_carriere@hotmail.com>\r
-\r
-*/\r
-\r
-if (!defined('IFX_SCROLL')) define('IFX_SCROLL',1);\r
-\r
-class ADODB_informix72 extends ADOConnection {\r
-       var $databaseType = "informix72";\r
-       var $dataProvider = "informix";\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $fmtDate = "'Y-m-d'";\r
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
-       var $hasInsertID = true;\r
-       var $hasAffectedRows = true;\r
-       var $upperCase = 'upper';\r
-    var $substr = 'substr';\r
-       var $metaTablesSQL="select tabname from systables";\r
-       var $metaColumnsSQL = \r
-"select c.colname, c.coltype, c.collength, d.default \r
-       from syscolumns c, systables t,sysdefaults d \r
-       where c.tabid=t.tabid and d.tabid=t.tabid and d.colno=c.colno and tabname='%s'";\r
-\r
-//     var $metaColumnsSQL = "select colname, coltype, collength from syscolumns c, systables t where c.tabid=t.tabid and tabname='%s'";\r
-       var $concat_operator = '||';\r
-\r
-       var $lastQuery = false;\r
-       var $has_insertid = true;\r
-\r
-       var $_autocommit = true;\r
-       var $_bindInputArray = true;  // set to true if ADOConnection.Execute() permits binding of array parameters.\r
-       var $sysDate = 'TODAY';\r
-       var $sysTimeStamp = 'CURRENT';\r
-       var $cursorType = IFX_SCROLL; // IFX_SCROLL or IFX_HOLD or 0\r
-   \r
-       function ADODB_informix72()\r
-       {\r
-               // alternatively, use older method:\r
-               //putenv("DBDATE=Y4MD-");\r
-\r
-               // force ISO date format\r
-               putenv('GL_DATE=%Y-%m-%d');\r
-               \r
-               if (function_exists('ifx_byteasvarchar')) {\r
-                       ifx_byteasvarchar(1); // Mode "0" will return a blob id, and mode "1" will return a varchar with text content. \r
-               ifx_textasvarchar(1); // Mode "0" will return a blob id, and mode "1" will return a varchar with text content. \r
-               ifx_blobinfile_mode(0); // Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.\r
-               }\r
-       }\r
-\r
-       function _insertid()\r
-       {\r
-               $sqlca =ifx_getsqlca($this->lastQuery);\r
-               return @$sqlca["sqlerrd1"];\r
-       }\r
-\r
-       function _affectedrows()\r
-       {\r
-               if ($this->lastQuery) {\r
-                  return @ifx_affected_rows ($this->lastQuery);\r
-               }\r
-               return 0;\r
-       }\r
-\r
-       function BeginTrans()\r
-       {\r
-               if ($this->transOff) return true;\r
-               $this->transCnt += 1;\r
-               $this->Execute('BEGIN');\r
-               $this->_autocommit = false;\r
-               return true;\r
-       }\r
-\r
-       function CommitTrans($ok=true) \r
-       { \r
-               if (!$ok) return $this->RollbackTrans();\r
-               if ($this->transOff) return true;\r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $this->Execute('COMMIT');\r
-               $this->_autocommit = true;\r
-               return true;\r
-       }\r
-\r
-       function RollbackTrans()\r
-       {\r
-               if ($this->transOff) return true;\r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $this->Execute('ROLLBACK');\r
-               $this->_autocommit = true;\r
-               return true;\r
-       }\r
-\r
-       function RowLock($tables,$where)\r
-       {\r
-               if ($this->_autocommit) $this->BeginTrans();\r
-               return $this->GetOne("select 1 as ignore from $tables where $where for update");\r
-       }\r
-\r
-       /*      Returns: the last error message from previous database operation\r
-               Note: This function is NOT available for Microsoft SQL Server.  */\r
-\r
-       function ErrorMsg() \r
-       {\r
-               if (!empty($this->_logsql)) return $this->_errorMsg;\r
-               $this->_errorMsg = ifx_errormsg();\r
-               return $this->_errorMsg;\r
-       }\r
-\r
-       function ErrorNo()\r
-       {\r
-               preg_match("/.*SQLCODE=([^\]]*)/",ifx_error(),$parse); //!EOS\r
-               if (is_array($parse) && isset($parse[1])) return (int)$parse[1]; \r
-               return 0;\r
-       }\r
-\r
-   \r
-    function &MetaColumns($table)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               if (!empty($this->metaColumnsSQL)) {\r
-                       $save = $ADODB_FETCH_MODE;\r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));\r
-                       if (isset($savem)) $this->SetFetchMode($savem);\r
-                       $ADODB_FETCH_MODE = $save;\r
-                       if ($rs === false) return false;\r
-\r
-                       $retarr = array();\r
-                       while (!$rs->EOF) { //print_r($rs->fields);\r
-                               $fld = new ADOFieldObject();\r
-                               $fld->name = $rs->fields[0];\r
-                               $fld->type = $rs->fields[1];\r
-                               $fld->max_length = $rs->fields[2];\r
-                               if (trim($rs->fields[3]) != "AAAAAA 0") {\r
-                                       $fld->has_default = 1;\r
-                                       $fld->default_value = $rs->fields[3];\r
-                               } else {\r
-                                       $fld->has_default = 0;\r
-                               }\r
-\r
-                $retarr[strtolower($fld->name)] = $fld;        \r
-                               $rs->MoveNext();\r
-                       }\r
-\r
-                       $rs->Close();\r
-                       return $retarr; \r
-               }\r
-\r
-               return false;\r
-       }\r
-       \r
-   function &xMetaColumns($table)\r
-   {\r
-               return ADOConnection::MetaColumns($table,false);\r
-   }\r
-\r
-   function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB')\r
-   {\r
-               $type = ($blobtype == 'TEXT') ? 1 : 0;\r
-               $blobid = ifx_create_blob($type,0,$val);\r
-               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blobid));\r
-   }\r
-\r
-   function BlobDecode($blobid)\r
-   {\r
-               return function_exists('ifx_byteasvarchar') ? $blobid : @ifx_get_blob($blobid);\r
-   }\r
-   \r
-       // returns true or false\r
-   function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (!function_exists('ifx_connect')) return false;\r
-               \r
-               $dbs = $argDatabasename . "@" . $argHostname;\r
-               if ($argHostname) putenv("INFORMIXSERVER=$argHostname"); \r
-               putenv("INFORMIXSERVER=$argHostname"); \r
-               $this->_connectionID = ifx_connect($dbs,$argUsername,$argPassword);\r
-               if ($this->_connectionID === false) return false;\r
-               #if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-               return true;\r
-       }\r
-\r
-       // returns true or false\r
-   function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (!function_exists('ifx_connect')) return false;\r
-               \r
-               $dbs = $argDatabasename . "@" . $argHostname;\r
-               if ($argHostname) putenv("INFORMIXSERVER=$argHostname"); \r
-               $this->_connectionID = ifx_pconnect($dbs,$argUsername,$argPassword);\r
-               if ($this->_connectionID === false) return false;\r
-               #if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-               return true;\r
-       }\r
-/*\r
-       // ifx_do does not accept bind parameters - wierd ???\r
-       function Prepare($sql)\r
-       {\r
-               $stmt = ifx_prepare($sql);\r
-               if (!$stmt) return $sql;\r
-               else return array($sql,$stmt);\r
-       }\r
-*/\r
-       // returns query ID if successful, otherwise false\r
-       function _query($sql,$inputarr)\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-       \r
-         // String parameters have to be converted using ifx_create_char\r
-         if ($inputarr) {\r
-                foreach($inputarr as $v) {\r
-                       if (gettype($v) == 'string') {\r
-                          $tab[] = ifx_create_char($v);\r
-                       }\r
-                       else {\r
-                          $tab[] = $v;\r
-                       }\r
-                }\r
-         }\r
-\r
-         // In case of select statement, we use a scroll cursor in order\r
-         // to be able to call "move", or "movefirst" statements\r
-         if (!$ADODB_COUNTRECS && preg_match("/^\s*select/is", $sql)) {\r
-                if ($inputarr) {\r
-                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType, $tab);\r
-                }\r
-                else {\r
-                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType);\r
-                }\r
-         }\r
-         else {\r
-                if ($inputarr) {\r
-                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $tab);\r
-                }\r
-                else {\r
-                       $this->lastQuery = ifx_query($sql,$this->_connectionID);\r
-                }\r
-         }\r
-\r
-         // Following line have been commented because autocommit mode is\r
-         // not supported by informix SE 7.2\r
-\r
-         //if ($this->_autocommit) ifx_query('COMMIT',$this->_connectionID);\r
-\r
-               return $this->lastQuery;\r
-       }\r
-\r
-       // returns true or false\r
-       function _close()\r
-       {\r
-               $this->lastQuery = false;\r
-               return ifx_close($this->_connectionID);\r
-       }\r
-}\r
-\r
-\r
-/*--------------------------------------------------------------------------------------\r
-        Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordset_informix72 extends ADORecordSet {\r
-\r
-       var $databaseType = "informix72";\r
-       var $canSeek = true;\r
-       var $_fieldprops = false;\r
-\r
-       function ADORecordset_informix72($id,$mode=false)\r
-       {\r
-               if ($mode === false) { \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               $this->fetchMode = $mode;\r
-               return $this->ADORecordSet($id);\r
-       }\r
-\r
-\r
-\r
-       /*      Returns: an object containing field information.\r
-               Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
-               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
-               fetchField() is retrieved.      */\r
-       function &FetchField($fieldOffset = -1)\r
-       {\r
-               if (empty($this->_fieldprops)) {\r
-                       $fp = ifx_fieldproperties($this->_queryID);\r
-                       foreach($fp as $k => $v) {\r
-                               $o = new ADOFieldObject;\r
-                               $o->name = $k;\r
-                               $arr = split(';',$v); //"SQLTYPE;length;precision;scale;ISNULLABLE"\r
-                               $o->type = $arr[0];\r
-                               $o->max_length = $arr[1];\r
-                               $this->_fieldprops[] = $o;\r
-                               $o->not_null = $arr[4]=="N";\r
-                       }\r
-               }\r
-               return $this->_fieldprops[$fieldOffset];\r
-       }\r
-\r
-       function _initrs()\r
-       {\r
-               $this->_numOfRows = -1; // ifx_affected_rows not reliable, only returns estimate -- ($ADODB_COUNTRECS)? ifx_affected_rows($this->_queryID):-1;\r
-               $this->_numOfFields = ifx_num_fields($this->_queryID);\r
-       }\r
-\r
-       function _seek($row)\r
-       {\r
-               return @ifx_fetch_row($this->_queryID, $row);\r
-       }\r
-\r
-   function MoveLast()\r
-   {\r
-         $this->fields = @ifx_fetch_row($this->_queryID, "LAST");\r
-         if ($this->fields) $this->EOF = false;\r
-         $this->_currentRow = -1;\r
-\r
-         if ($this->fetchMode == ADODB_FETCH_NUM) {\r
-                foreach($this->fields as $v) {\r
-                       $arr[] = $v;\r
-                }\r
-                $this->fields = $arr;\r
-         }\r
-\r
-         return true;\r
-   }\r
-\r
-   function MoveFirst()\r
-       {\r
-         $this->fields = @ifx_fetch_row($this->_queryID, "FIRST");\r
-         if ($this->fields) $this->EOF = false;\r
-         $this->_currentRow = 0;\r
-\r
-         if ($this->fetchMode == ADODB_FETCH_NUM) {\r
-                foreach($this->fields as $v) {\r
-                       $arr[] = $v;\r
-                }\r
-                $this->fields = $arr;\r
-         }\r
-\r
-         return true;\r
-   }\r
-\r
-   function _fetch($ignore_fields=false)\r
-   {\r
-\r
-               $this->fields = @ifx_fetch_row($this->_queryID);\r
-\r
-               if (!is_array($this->fields)) return false;\r
-\r
-               if ($this->fetchMode == ADODB_FETCH_NUM) {\r
-                       foreach($this->fields as $v) {\r
-                               $arr[] = $v;\r
-                       }\r
-                       $this->fields = $arr;\r
-               }\r
-               return true;\r
-       }\r
-\r
-       /*      close() only needs to be called if you are worried about using too much memory while your script\r
-               is running. All associated result memory for the specified result identifier will automatically be freed.       */\r
-       function _close()\r
-       {\r
-               return ifx_free_result($this->_queryID);\r
-       }\r
-\r
-}\r
+<?php
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim. All rights reserved.
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence.
+  Set tabs to 4 for best viewing.
+
+  Latest version is available at http://php.weblogs.com/
+
+  Informix port by Mitchell T. Young (mitch@youngfamily.org)
+
+  Further mods by "Samuel CARRIERE" <samuel_carriere@hotmail.com>
+
+*/
+
+if (!defined('IFX_SCROLL')) define('IFX_SCROLL',1);
+
+class ADODB_informix72 extends ADOConnection {
+       var $databaseType = "informix72";
+       var $dataProvider = "informix";
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $fmtDate = "'Y-m-d'";
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";
+       var $hasInsertID = true;
+       var $hasAffectedRows = true;
+       var $upperCase = 'upper';
+    var $substr = 'substr';
+       var $metaTablesSQL="select tabname from systables";
+       var $metaColumnsSQL = 
+"select c.colname, c.coltype, c.collength, d.default 
+       from syscolumns c, systables t,sysdefaults d 
+       where c.tabid=t.tabid and d.tabid=t.tabid and d.colno=c.colno and tabname='%s'";
+
+//     var $metaColumnsSQL = "select colname, coltype, collength from syscolumns c, systables t where c.tabid=t.tabid and tabname='%s'";
+       var $concat_operator = '||';
+
+       var $lastQuery = false;
+       var $has_insertid = true;
+
+       var $_autocommit = true;
+       var $_bindInputArray = true;  // set to true if ADOConnection.Execute() permits binding of array parameters.
+       var $sysDate = 'TODAY';
+       var $sysTimeStamp = 'CURRENT';
+       var $cursorType = IFX_SCROLL; // IFX_SCROLL or IFX_HOLD or 0
+   
+       function ADODB_informix72()
+       {
+               // alternatively, use older method:
+               //putenv("DBDATE=Y4MD-");
+
+               // force ISO date format
+               putenv('GL_DATE=%Y-%m-%d');
+               
+               if (function_exists('ifx_byteasvarchar')) {
+                       ifx_byteasvarchar(1); // Mode "0" will return a blob id, and mode "1" will return a varchar with text content. 
+               ifx_textasvarchar(1); // Mode "0" will return a blob id, and mode "1" will return a varchar with text content. 
+               ifx_blobinfile_mode(0); // Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.
+               }
+       }
+       
+       function ServerInfo()
+       {
+           if (isset($this->version)) return $this->version;
+       
+           $arr['description'] = $this->GetOne("select DBINFO('version','full') from systables where tabid = 1");
+           $arr['version'] = $this->GetOne("select DBINFO('version','major')||"."||DBINFO('version','minor') from systables where tabid = 1");
+           $this->version = $arr;
+           return $arr;
+       }
+
+
+
+       function _insertid()
+       {
+               $sqlca =ifx_getsqlca($this->lastQuery);
+               return @$sqlca["sqlerrd1"];
+       }
+
+       function _affectedrows()
+       {
+               if ($this->lastQuery) {
+                  return @ifx_affected_rows ($this->lastQuery);
+               }
+               return 0;
+       }
+
+       function BeginTrans()
+       {
+               if ($this->transOff) return true;
+               $this->transCnt += 1;
+               $this->Execute('BEGIN');
+               $this->_autocommit = false;
+               return true;
+       }
+
+       function CommitTrans($ok=true) 
+       { 
+               if (!$ok) return $this->RollbackTrans();
+               if ($this->transOff) return true;
+               if ($this->transCnt) $this->transCnt -= 1;
+               $this->Execute('COMMIT');
+               $this->_autocommit = true;
+               return true;
+       }
+
+       function RollbackTrans()
+       {
+               if ($this->transOff) return true;
+               if ($this->transCnt) $this->transCnt -= 1;
+               $this->Execute('ROLLBACK');
+               $this->_autocommit = true;
+               return true;
+       }
+
+       function RowLock($tables,$where)
+       {
+               if ($this->_autocommit) $this->BeginTrans();
+               return $this->GetOne("select 1 as ignore from $tables where $where for update");
+       }
+
+       /*      Returns: the last error message from previous database operation
+               Note: This function is NOT available for Microsoft SQL Server.  */
+
+       function ErrorMsg() 
+       {
+               if (!empty($this->_logsql)) return $this->_errorMsg;
+               $this->_errorMsg = ifx_errormsg();
+               return $this->_errorMsg;
+       }
+
+       function ErrorNo()
+       {
+               preg_match("/.*SQLCODE=([^\]]*)/",ifx_error(),$parse); //!EOS
+               if (is_array($parse) && isset($parse[1])) return (int)$parse[1]; 
+               return 0;
+       }
+
+   
+    function &MetaColumns($table)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               if (!empty($this->metaColumnsSQL)) {
+                       $save = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
+                       if (isset($savem)) $this->SetFetchMode($savem);
+                       $ADODB_FETCH_MODE = $save;
+                       if ($rs === false) return false;
+
+                       $retarr = array();
+                       while (!$rs->EOF) { //print_r($rs->fields);
+                               $fld = new ADOFieldObject();
+                               $fld->name = $rs->fields[0];
+                               $fld->type = $rs->fields[1];
+                               $fld->max_length = $rs->fields[2];
+                               if (trim($rs->fields[3]) != "AAAAAA 0") {
+                                       $fld->has_default = 1;
+                                       $fld->default_value = $rs->fields[3];
+                               } else {
+                                       $fld->has_default = 0;
+                               }
+
+                $retarr[strtolower($fld->name)] = $fld;        
+                               $rs->MoveNext();
+                       }
+
+                       $rs->Close();
+                       return $retarr; 
+               }
+
+               return false;
+       }
+       
+   function &xMetaColumns($table)
+   {
+               return ADOConnection::MetaColumns($table,false);
+   }
+
+   function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB')
+   {
+               $type = ($blobtype == 'TEXT') ? 1 : 0;
+               $blobid = ifx_create_blob($type,0,$val);
+               return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blobid));
+   }
+
+   function BlobDecode($blobid)
+   {
+               return function_exists('ifx_byteasvarchar') ? $blobid : @ifx_get_blob($blobid);
+   }
+   
+       // returns true or false
+   function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (!function_exists('ifx_connect')) return false;
+               
+               $dbs = $argDatabasename . "@" . $argHostname;
+               if ($argHostname) putenv("INFORMIXSERVER=$argHostname"); 
+               putenv("INFORMIXSERVER=".trim($argHostname)); 
+               $this->_connectionID = ifx_connect($dbs,$argUsername,$argPassword);
+               if ($this->_connectionID === false) return false;
+               #if ($argDatabasename) return $this->SelectDB($argDatabasename);
+               return true;
+       }
+
+       // returns true or false
+   function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (!function_exists('ifx_connect')) return false;
+               
+               $dbs = $argDatabasename . "@" . $argHostname;
+               putenv("INFORMIXSERVER=".trim($argHostname)); 
+               $this->_connectionID = ifx_pconnect($dbs,$argUsername,$argPassword);
+               if ($this->_connectionID === false) return false;
+               #if ($argDatabasename) return $this->SelectDB($argDatabasename);
+               return true;
+       }
+/*
+       // ifx_do does not accept bind parameters - weird ???
+       function Prepare($sql)
+       {
+               $stmt = ifx_prepare($sql);
+               if (!$stmt) return $sql;
+               else return array($sql,$stmt);
+       }
+*/
+       // returns query ID if successful, otherwise false
+       function _query($sql,$inputarr)
+       {
+       global $ADODB_COUNTRECS;
+       
+         // String parameters have to be converted using ifx_create_char
+         if ($inputarr) {
+                foreach($inputarr as $v) {
+                       if (gettype($v) == 'string') {
+                          $tab[] = ifx_create_char($v);
+                       }
+                       else {
+                          $tab[] = $v;
+                       }
+                }
+         }
+
+         // In case of select statement, we use a scroll cursor in order
+         // to be able to call "move", or "movefirst" statements
+         if (!$ADODB_COUNTRECS && preg_match("/^\s*select/is", $sql)) {
+                if ($inputarr) {
+                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType, $tab);
+                }
+                else {
+                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $this->cursorType);
+                }
+         }
+         else {
+                if ($inputarr) {
+                       $this->lastQuery = ifx_query($sql,$this->_connectionID, $tab);
+                }
+                else {
+                       $this->lastQuery = ifx_query($sql,$this->_connectionID);
+                }
+         }
+
+         // Following line have been commented because autocommit mode is
+         // not supported by informix SE 7.2
+
+         //if ($this->_autocommit) ifx_query('COMMIT',$this->_connectionID);
+
+               return $this->lastQuery;
+       }
+
+       // returns true or false
+       function _close()
+       {
+               $this->lastQuery = false;
+               return ifx_close($this->_connectionID);
+       }
+}
+
+
+/*--------------------------------------------------------------------------------------
+        Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_informix72 extends ADORecordSet {
+
+       var $databaseType = "informix72";
+       var $canSeek = true;
+       var $_fieldprops = false;
+
+       function ADORecordset_informix72($id,$mode=false)
+       {
+               if ($mode === false) { 
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               $this->fetchMode = $mode;
+               return $this->ADORecordSet($id);
+       }
+
+
+
+       /*      Returns: an object containing field information.
+               Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+               fetchField() is retrieved.      */
+       function &FetchField($fieldOffset = -1)
+       {
+               if (empty($this->_fieldprops)) {
+                       $fp = ifx_fieldproperties($this->_queryID);
+                       foreach($fp as $k => $v) {
+                               $o = new ADOFieldObject;
+                               $o->name = $k;
+                               $arr = split(';',$v); //"SQLTYPE;length;precision;scale;ISNULLABLE"
+                               $o->type = $arr[0];
+                               $o->max_length = $arr[1];
+                               $this->_fieldprops[] = $o;
+                               $o->not_null = $arr[4]=="N";
+                       }
+               }
+               return $this->_fieldprops[$fieldOffset];
+       }
+
+       function _initrs()
+       {
+               $this->_numOfRows = -1; // ifx_affected_rows not reliable, only returns estimate -- ($ADODB_COUNTRECS)? ifx_affected_rows($this->_queryID):-1;
+               $this->_numOfFields = ifx_num_fields($this->_queryID);
+       }
+
+       function _seek($row)
+       {
+               return @ifx_fetch_row($this->_queryID, $row);
+       }
+
+   function MoveLast()
+   {
+         $this->fields = @ifx_fetch_row($this->_queryID, "LAST");
+         if ($this->fields) $this->EOF = false;
+         $this->_currentRow = -1;
+
+         if ($this->fetchMode == ADODB_FETCH_NUM) {
+                foreach($this->fields as $v) {
+                       $arr[] = $v;
+                }
+                $this->fields = $arr;
+         }
+
+         return true;
+   }
+
+   function MoveFirst()
+       {
+         $this->fields = @ifx_fetch_row($this->_queryID, "FIRST");
+         if ($this->fields) $this->EOF = false;
+         $this->_currentRow = 0;
+
+         if ($this->fetchMode == ADODB_FETCH_NUM) {
+                foreach($this->fields as $v) {
+                       $arr[] = $v;
+                }
+                $this->fields = $arr;
+         }
+
+         return true;
+   }
+
+   function _fetch($ignore_fields=false)
+   {
+
+               $this->fields = @ifx_fetch_row($this->_queryID);
+
+               if (!is_array($this->fields)) return false;
+
+               if ($this->fetchMode == ADODB_FETCH_NUM) {
+                       foreach($this->fields as $v) {
+                               $arr[] = $v;
+                       }
+                       $this->fields = $arr;
+               }
+               return true;
+       }
+
+       /*      close() only needs to be called if you are worried about using too much memory while your script
+               is running. All associated result memory for the specified result identifier will automatically be freed.       */
+       function _close()
+       {
+               return ifx_free_result($this->_queryID);
+       }
+
+}
 ?>
\ No newline at end of file
index 7a0247b649966c9edd6da000b007869c348e0d0a..30325f39848d8f6da24cd15cece7492e5c32ed68 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Native mssql driver. Requires mssql client. Works on Windows. \r
-  To configure for Unix, see \r
-       http://phpbuilder.com/columns/alberto20000919.php3\r
-       \r
-*/\r
-\r
-//----------------------------------------------------------------\r
-// MSSQL returns dates with the format Oct 13 2002 or 13 Oct 2002\r
-// and this causes tons of problems because localized versions of \r
-// MSSQL will return the dates in dmy or  mdy order; and also the \r
-// month strings depends on what language has been configured. The \r
-// following two variables allow you to control the localization\r
-// settings - Ugh.\r
-//\r
-// MORE LOCALIZATION INFO\r
-// ----------------------\r
-// To configure datetime, look for and modify sqlcommn.loc, \r
-//     typically found in c:\mssql\install\r
-// Also read :\r
-//      http://support.microsoft.com/default.aspx?scid=kb;EN-US;q220918\r
-// Alternatively use:\r
-//        CONVERT(char(12),datecol,120)\r
-//----------------------------------------------------------------\r
-\r
-\r
-// has datetime converstion to YYYY-MM-DD format, and also mssql_fetch_assoc\r
-if (ADODB_PHPVER >= 0x4300) {\r
-// docs say 4.2.0, but testing shows only since 4.3.0 does it work!\r
-       ini_set('mssql.datetimeconvert',0); \r
-} else {\r
-global $ADODB_mssql_mths;              // array, months must be upper-case\r
-\r
-\r
-       $ADODB_mssql_date_order = 'mdy'; \r
-       $ADODB_mssql_mths = array(\r
-               'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,\r
-               'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);\r
-}\r
-\r
-//---------------------------------------------------------------------------\r
-// Call this to autoset $ADODB_mssql_date_order at the beginning of your code,\r
-// just after you connect to the database. Supports mdy and dmy only.\r
-// Not required for PHP 4.2.0 and above.\r
-function AutoDetect_MSSQL_Date_Order($conn)\r
-{\r
-global $ADODB_mssql_date_order;\r
-       $adate = $conn->GetOne('select getdate()');\r
-       if ($adate) {\r
-               $anum = (int) $adate;\r
-               if ($anum > 0) {\r
-                       if ($anum > 31) {\r
-                               //ADOConnection::outp( "MSSQL: YYYY-MM-DD date format not supported currently");\r
-                       } else\r
-                               $ADODB_mssql_date_order = 'dmy';\r
-               } else\r
-                       $ADODB_mssql_date_order = 'mdy';\r
-       }\r
-}\r
-\r
-class ADODB_mssql extends ADOConnection {\r
-       var $databaseType = "mssql";    \r
-       var $dataProvider = "mssql";\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $fmtDate = "'Y-m-d'";\r
-       var $fmtTimeStamp = "'Y-m-d h:i:sA'";\r
-       var $hasInsertID = true;\r
-       var $substr = "substring";\r
-       var $length = 'len';\r
-       var $upperCase = 'upper';\r
-       var $hasAffectedRows = true;\r
-       var $metaDatabasesSQL = "select name from sysdatabases where name <> 'master'";\r
-       var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE','dtproperties'))";\r
-       var $metaColumnsSQL = # xtype==61 is datetime\r
-"select c.name,t.name,c.length,\r
-       (case when c.xusertype=61 then 0 else c.xprec end),\r
-       (case when c.xusertype=61 then 0 else c.xscale end) \r
-       from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";\r
-       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE\r
-       var $hasGenID = true;\r
-       var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';\r
-       var $sysTimeStamp = 'GetDate()';\r
-       var $_has_mssql_init;\r
-       var $maxParameterLen = 4000;\r
-       var $arrayClass = 'ADORecordSet_array_mssql';\r
-       var $uniqueSort = true;\r
-       var $leftOuter = '*=';\r
-       var $rightOuter = '=*';\r
-       var $ansiOuter = true; // for mssql7 or later\r
-       var $poorAffectedRows = true;\r
-       var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000\r
-       var $uniqueOrderBy = true;\r
-       var $_bindInputArray = true;\r
-       \r
-       \r
-       function ADODB_mssql() \r
-       {               \r
-               $this->_has_mssql_init = (strnatcmp(PHP_VERSION,'4.1.0')>=0);\r
-       }\r
-\r
-       function ServerInfo()\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $stmt = $this->PrepareSP('sp_server_info');\r
-               $val = 2;\r
-               if ($this->fetchMode === false) {\r
-                       $savem = $ADODB_FETCH_MODE;\r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               } else \r
-                       $savem = $this->SetFetchMode(ADODB_FETCH_NUM);\r
-               \r
-               \r
-               $this->Parameter($stmt,$val,'attribute_id');\r
-               $row = $this->GetRow($stmt);\r
-               \r
-               //$row = $this->GetRow("execute sp_server_info 2");\r
-               \r
-               if ($this->fetchMode === false) {\r
-                       $ADODB_FETCH_MODE = $savem;\r
-               } else\r
-                       $this->SetFetchMode($savem);\r
-               \r
-               $arr['description'] = $row[2];\r
-               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
-               return $arr;\r
-       }\r
-       \r
-       function IfNull( $field, $ifNull ) \r
-       {\r
-               return " ISNULL($field, $ifNull) "; // if MS SQL Server\r
-       }\r
-       \r
-       function _insertid()\r
-       {\r
-       // SCOPE_IDENTITY()\r
-       // Returns the last IDENTITY value inserted into an IDENTITY column in \r
-       // the same scope. A scope is a module -- a stored procedure, trigger, \r
-       // function, or batch. Thus, two statements are in the same scope if \r
-       // they are in the same stored procedure, function, or batch.\r
-                       return $this->GetOne($this->identitySQL);\r
-       }\r
-\r
-       function _affectedrows()\r
-       {\r
-               return $this->GetOne('select @@rowcount');\r
-       }\r
-\r
-       var $_dropSeqSQL = "drop table %s";\r
-       \r
-       function CreateSequence($seq='adodbseq',$start=1)\r
-       {\r
-               $start -= 1;\r
-               $this->Execute("create table $seq (id float(53))");\r
-               $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");\r
-               if (!$ok) {\r
-                               $this->Execute('ROLLBACK TRANSACTION adodbseq');\r
-                               return false;\r
-               }\r
-               $this->Execute('COMMIT TRANSACTION adodbseq'); \r
-               return true;\r
-       }\r
-\r
-       function GenID($seq='adodbseq',$start=1)\r
-       {\r
-               //$this->debug=1;\r
-               $this->Execute('BEGIN TRANSACTION adodbseq');\r
-               $ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1");\r
-               if (!$ok) {\r
-                       $this->Execute("create table $seq (id float(53))");\r
-                       $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");\r
-                       if (!$ok) {\r
-                               $this->Execute('ROLLBACK TRANSACTION adodbseq');\r
-                               return false;\r
-                       }\r
-                       $this->Execute('COMMIT TRANSACTION adodbseq'); \r
-                       return $start;\r
-               }\r
-               $num = $this->GetOne("select id from $seq");\r
-               $this->Execute('COMMIT TRANSACTION adodbseq'); \r
-               return $num;\r
-               \r
-               // in old implementation, pre 1.90, we returned GUID...\r
-               //return $this->GetOne("SELECT CONVERT(varchar(255), NEWID()) AS 'Char'");\r
-       }\r
-       \r
-\r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
-       {\r
-               if ($nrows > 0 && $offset <= 0) {\r
-                       $sql = preg_replace(\r
-                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);\r
-                       $rs =& $this->Execute($sql,$inputarr);\r
-               } else\r
-                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
-       \r
-               return $rs;\r
-       }\r
-       \r
-       \r
-       // Format date column in sql string given an input format that understands Y M D\r
-       function SQLDate($fmt, $col=false)\r
-       {       \r
-               if (!$col) $col = $this->sysTimeStamp;\r
-               $s = '';\r
-               \r
-               $len = strlen($fmt);\r
-               for ($i=0; $i < $len; $i++) {\r
-                       if ($s) $s .= '+';\r
-                       $ch = $fmt[$i];\r
-                       switch($ch) {\r
-                       case 'Y':\r
-                       case 'y':\r
-                               $s .= "datename(yyyy,$col)";\r
-                               break;\r
-                       case 'M':\r
-                               $s .= "convert(char(3),$col,0)";\r
-                               break;\r
-                       case 'm':\r
-                               $s .= "replace(str(month($col),2),' ','0')";\r
-                               break;\r
-                       case 'Q':\r
-                       case 'q':\r
-                               $s .= "datename(quarter,$col)";\r
-                               break;\r
-                       case 'D':\r
-                       case 'd':\r
-                               $s .= "replace(str(day($col),2),' ','0')";\r
-                               break;\r
-                       case 'h':\r
-                               $s .= "substring(convert(char(14),$col,0),13,2)";\r
-                               break;\r
-                       \r
-                       case 'H':\r
-                               $s .= "replace(str(datepart(hh,$col),2),' ','0')";\r
-                               break;\r
-                               \r
-                       case 'i':\r
-                               $s .= "replace(str(datepart(mi,$col),2),' ','0')";\r
-                               break;\r
-                       case 's':\r
-                               $s .= "replace(str(datepart(ss,$col),2),' ','0')";\r
-                               break;\r
-                       case 'a':\r
-                       case 'A':\r
-                               $s .= "substring(convert(char(19),$col,0),18,2)";\r
-                               break;\r
-                               \r
-                       default:\r
-                               if ($ch == '\\') {\r
-                                       $i++;\r
-                                       $ch = substr($fmt,$i,1);\r
-                               }\r
-                               $s .= $this->qstr($ch);\r
-                               break;\r
-                       }\r
-               }\r
-               return $s;\r
-       }\r
-\r
-       \r
-       function BeginTrans()\r
-       {\r
-               if ($this->transOff) return true; \r
-               $this->transCnt += 1;\r
-               $this->Execute('BEGIN TRAN');\r
-               return true;\r
-       }\r
-               \r
-       function CommitTrans($ok=true) \r
-       { \r
-               if ($this->transOff) return true; \r
-               if (!$ok) return $this->RollbackTrans();\r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $this->Execute('COMMIT TRAN');\r
-               return true;\r
-       }\r
-       function RollbackTrans()\r
-       {\r
-               if ($this->transOff) return true; \r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $this->Execute('ROLLBACK TRAN');\r
-               return true;\r
-       }\r
-       \r
-       /*\r
-               Usage:\r
-               \r
-               $this->BeginTrans();\r
-               $this->RowLock('table1,table2','table1.id=33 and table2.id=table1.id'); # lock row 33 for both tables\r
-               \r
-               # some operation on both tables table1 and table2\r
-               \r
-               $this->CommitTrans();\r
-               \r
-               See http://www.swynk.com/friends/achigrik/SQL70Locks.asp\r
-       */\r
-       function RowLock($tables,$where) \r
-       {\r
-               if (!$this->transCnt) $this->BeginTrans();\r
-               return $this->GetOne("select top 1 null as ignore from $tables with (ROWLOCK,HOLDLOCK) where $where");\r
-       }\r
-       \r
-       function MetaForeignKeys($table, $owner=false, $upper=false)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $table = $this->qstr(strtoupper($table));\r
-               \r
-               $sql = \r
-"select object_name(constid) as constraint_name,\r
-       col_name(fkeyid, fkey) as column_name,\r
-       object_name(rkeyid) as referenced_table_name,\r
-       col_name(rkeyid, rkey) as referenced_column_name\r
-from sysforeignkeys\r
-where upper(object_name(fkeyid)) = $table\r
-order by constraint_name, referenced_table_name, keyno";\r
-               \r
-               $constraints =& $this->GetArray($sql);\r
-               \r
-               $ADODB_FETCH_MODE = $save;\r
-               \r
-               $arr = false;\r
-               foreach($constraints as $constr) {\r
-                       //print_r($constr);\r
-                       $arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; \r
-               }\r
-               if (!$arr) return false;\r
-               \r
-               $arr2 = false;\r
-               \r
-               foreach($arr as $k => $v) {\r
-                       foreach($v as $a => $b) {\r
-                               if ($upper) $a = strtoupper($a);\r
-                               $arr2[$a] = $b;\r
-                       }\r
-               }\r
-               return $arr2;\r
-       }\r
-\r
-       //From: Fernando Moreira <FMoreira@imediata.pt>\r
-       function MetaDatabases() \r
-       { \r
-               if(@mssql_select_db("master")) { \r
-                                $qry=$this->metaDatabasesSQL; \r
-                                if($rs=@mssql_query($qry)){ \r
-                                                $tmpAr=$ar=array(); \r
-                                                while($tmpAr=@mssql_fetch_row($rs)) \r
-                                                                $ar[]=$tmpAr[0]; \r
-                                               @mssql_select_db($this->databaseName); \r
-                                                if(sizeof($ar)) \r
-                                                                return($ar); \r
-                                                else \r
-                                                                return(false); \r
-                                } else { \r
-                                                @mssql_select_db($this->databaseName); \r
-                                                return(false); \r
-                                } \r
-                } \r
-                return(false); \r
-       } \r
-\r
-       // "Stein-Aksel Basma" <basma@accelero.no>\r
-       // tested with MSSQL 2000\r
-       function MetaPrimaryKeys($table)\r
-       {\r
-               $sql = "select k.column_name from information_schema.key_column_usage k,\r
-               information_schema.table_constraints tc \r
-               where tc.constraint_name = k.constraint_name and tc.constraint_type =\r
-               'PRIMARY KEY' and k.table_name = '$table'";\r
-               \r
-               $a = $this->GetCol($sql);\r
-               if ($a && sizeof($a)>0) return $a;\r
-               return false;     \r
-       }\r
-\r
-       \r
-       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
-       {\r
-               if ($mask) {\r
-                       $save = $this->metaTablesSQL;\r
-                       $mask = $this->qstr(($mask));\r
-                       $this->metaTablesSQL .= " AND name like $mask";\r
-               }\r
-               $ret =& ADOConnection::MetaTables($ttype,$showSchema);\r
-               \r
-               if ($mask) {\r
-                       $this->metaTablesSQL = $save;\r
-               }\r
-               return $ret;\r
-       }\r
\r
-       function SelectDB($dbName) \r
-       {\r
-               $this->databaseName = $dbName;\r
-               if ($this->_connectionID) {\r
-                       return @mssql_select_db($dbName);               \r
-               }\r
-               else return false;      \r
-       }\r
-       \r
-       function ErrorMsg() \r
-       {\r
-               if (empty($this->_errorMsg)){\r
-                       $this->_errorMsg = mssql_get_last_message();\r
-               }\r
-               return $this->_errorMsg;\r
-       }\r
-       \r
-       function ErrorNo() \r
-       {\r
-               if ($this->_logsql && $this->_errorCode !== false) return $this->_errorCode;\r
-               if (empty($this->_errorMsg)) {\r
-                       $this->_errorMsg = mssql_get_last_message();\r
-               }\r
-               $id = @mssql_query("select @@ERROR",$this->_connectionID);\r
-               if (!$id) return false;\r
-               $arr = mssql_fetch_array($id);\r
-               @mssql_free_result($id);\r
-               if (is_array($arr)) return $arr[0];\r
-          else return -1;\r
-       }\r
-       \r
-       // returns true or false\r
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (!function_exists('mssql_pconnect')) return false;\r
-               $this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword);\r
-               if ($this->_connectionID === false) return false;\r
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-               return true;    \r
-       }\r
-       \r
-       \r
-       // returns true or false\r
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (!function_exists('mssql_pconnect')) return false;\r
-               $this->_connectionID = mssql_pconnect($argHostname,$argUsername,$argPassword);\r
-               if ($this->_connectionID === false) return false;\r
-               \r
-               // persistent connections can forget to rollback on crash, so we do it here.\r
-               if ($this->autoRollback) {\r
-                       $cnt = $this->GetOne('select @@TRANCOUNT');\r
-                       while (--$cnt >= 0) $this->Execute('ROLLBACK TRAN'); \r
-               }\r
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-               return true;    \r
-       }\r
-       \r
-       function Prepare($sql)\r
-       {\r
-               $sqlarr = explode('?',$sql);\r
-               if (sizeof($sqlarr) <= 1) return $sql;\r
-               $sql2 = $sqlarr[0];\r
-               for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {\r
-                       $sql2 .=  '@P'.($i-1) . $sqlarr[$i];\r
-               } \r
-               return array($sql,$this->qstr($sql2),$max);\r
-       }\r
-       \r
-       function PrepareSP($sql)\r
-       {\r
-               if (!$this->_has_mssql_init) {\r
-                       ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");\r
-                       return $sql;\r
-               }\r
-               $stmt = mssql_init($sql,$this->_connectionID);\r
-               if (!$stmt)  return $sql;\r
-               return array($sql,$stmt);\r
-       }\r
-       \r
-       /* \r
-       Usage:\r
-               $stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group\r
-               \r
-               # note that the parameter does not have @ in front!\r
-               $db->Parameter($stmt,$id,'myid');\r
-               $db->Parameter($stmt,$group,'group',false,64);\r
-               $db->Execute($stmt);\r
-               \r
-               @param $stmt Statement returned by Prepare() or PrepareSP().\r
-               @param $var PHP variable to bind to. Can set to null (for isNull support).\r
-               @param $name Name of stored procedure variable name to bind to.\r
-               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.\r
-               @param [$maxLen] Holds an maximum length of the variable.\r
-               @param [$type] The data type of $var. Legal values depend on driver.\r
-               \r
-               See mssql_bind documentation at php.net.\r
-       */\r
-       function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=4000, $type=false)\r
-       {\r
-               if (!$this->_has_mssql_init) {\r
-                       ADOConnection::outp( "Parameter: mssql_bind only available since PHP 4.1.0");\r
-                       return $sql;\r
-               }\r
-\r
-               $isNull = is_null($var); // php 4.0.4 and above...\r
-                       \r
-               if ($type === false) \r
-                       switch(gettype($var)) {\r
-                       default:\r
-                       case 'string': $type = SQLCHAR; break;\r
-                       case 'double': $type = SQLFLT8; break;\r
-                       case 'integer': $type = SQLINT4; break;\r
-                       case 'boolean': $type = SQLINT1; break; # SQLBIT not supported in 4.1.0\r
-                       }\r
-               \r
-               if  ($this->debug) {\r
-                       $prefix = ($isOutput) ? 'Out' : 'In';\r
-                       $ztype = (empty($type)) ? 'false' : $type;\r
-                       ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");\r
-               }\r
-               /*\r
-                       See http://phplens.com/lens/lensforum/msgs.php?id=7231\r
-                       \r
-                       RETVAL is HARD CODED into php_mssql extension:\r
-                       The return value (a long integer value) is treated like a special OUTPUT parameter, \r
-                       called "RETVAL" (without the @). See the example at mssql_execute to \r
-                       see how it works. - type: one of this new supported PHP constants. \r
-                               SQLTEXT, SQLVARCHAR,SQLCHAR, SQLINT1,SQLINT2, SQLINT4, SQLBIT,SQLFLT8 \r
-               */\r
-               if ($name !== 'RETVAL') $name = '@'.$name;\r
-               return mssql_bind($stmt[1], $name, $var, $type, $isOutput, $isNull, $maxLen);\r
-       }\r
-       \r
-       /* \r
-               Unfortunately, it appears that mssql cannot handle varbinary > 255 chars\r
-               So all your blobs must be of type "image".\r
-               \r
-               Remember to set in php.ini the following...\r
-               \r
-               ; Valid range 0 - 2147483647. Default = 4096. \r
-               mssql.textlimit = 0 ; zero to pass through \r
-\r
-               ; Valid range 0 - 2147483647. Default = 4096. \r
-               mssql.textsize = 0 ; zero to pass through \r
-       */\r
-       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
-       {\r
-               $sql = "UPDATE $table SET $column=0x".bin2hex($val)." WHERE $where";\r
-               return $this->Execute($sql) != false;\r
-       }\r
-       \r
-       // returns query ID if successful, otherwise false\r
-       function _query($sql,$inputarr)\r
-       {\r
-               $this->_errorMsg = false;\r
-               if (is_array($inputarr)) {\r
-                       \r
-                       # bind input params with sp_executesql: \r
-                       # see http://www.quest-pipelines.com/newsletter-v3/0402_F.htm\r
-                       # works only with sql server 7 and newer\r
-                       if (!is_array($sql)) $sql = $this->Prepare($sql);\r
-                       $params = '';\r
-                       $decl = '';\r
-                       $i = 0;\r
-                       foreach($inputarr as $v) {\r
-                               if ($decl) {\r
-                                       $decl .= ', ';\r
-                                       $params .= ', ';\r
-                               }       \r
-                               if (is_string($v)) {\r
-                                       $len = strlen($v);\r
-                                       if ($len == 0) $len = 1;\r
-                                       $decl .= "@P$i NVARCHAR($len)";\r
-                                       $params .= "@P$i=N". (strncmp($v,"'",1)==0? $v : $this->qstr($v));\r
-                               } else if (is_integer($v)) {\r
-                                       $decl .= "@P$i INT";\r
-                                       $params .= "@P$i=".$v;\r
-                               } else {\r
-                                       $decl .= "@P$i FLOAT";\r
-                                       $params .= "@P$i=".$v;\r
-                               }\r
-                               $i += 1;\r
-                       }\r
-                       $decl = $this->qstr($decl);\r
-                       if ($this->debug) ADOConnection::outp("<font size=-1>sp_executesql N{$sql[1]},N$decl,$params</font>");\r
-                       $rez = mssql_query("sp_executesql N{$sql[1]},N$decl,$params");\r
-                       \r
-               } else if (is_array($sql)) {\r
-                       # PrepareSP()\r
-                       $rez = mssql_execute($sql[1]);\r
-                       \r
-               } else {\r
-                       $rez = mssql_query($sql,$this->_connectionID);\r
-               }\r
-               return $rez;\r
-       }\r
-       \r
-       // returns true or false\r
-       function _close()\r
-       { \r
-               if ($this->transCnt) $this->RollbackTrans();\r
-               $rez = @mssql_close($this->_connectionID);\r
-               $this->_connectionID = false;\r
-               return $rez;\r
-       }\r
-       \r
-       // mssql uses a default date like Dec 30 2000 12:00AM\r
-       function UnixDate($v)\r
-       {\r
-               return ADORecordSet_array_mssql::UnixDate($v);\r
-       }\r
-       \r
-       function UnixTimeStamp($v)\r
-       {\r
-               return ADORecordSet_array_mssql::UnixTimeStamp($v);\r
-       }       \r
-}\r
-       \r
-/*--------------------------------------------------------------------------------------\r
-        Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordset_mssql extends ADORecordSet {        \r
-\r
-       var $databaseType = "mssql";\r
-       var $canSeek = true;\r
-       var $hasFetchAssoc; // see http://phplens.com/lens/lensforum/msgs.php?id=6083\r
-       // _mths works only in non-localised system\r
-       \r
-       function ADORecordset_mssql($id,$mode=false)\r
-       {\r
-               // freedts check...\r
-               $this->hasFetchAssoc = function_exists('mssql_fetch_assoc');\r
-\r
-               if ($mode === false) { \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               $this->fetchMode = $mode;\r
-               return $this->ADORecordSet($id,$mode);\r
-       }\r
-       \r
-       \r
-       function _initrs()\r
-       {\r
-       GLOBAL $ADODB_COUNTRECS;        \r
-               $this->_numOfRows = ($ADODB_COUNTRECS)? @mssql_num_rows($this->_queryID):-1;\r
-               $this->_numOfFields = @mssql_num_fields($this->_queryID);\r
-       }\r
-       \r
-\r
-       //Contributed by "Sven Axelsson" <sven.axelsson@bokochwebb.se>\r
-       // get next resultset - requires PHP 4.0.5 or later\r
-       function NextRecordSet()\r
-       {\r
-               if (!mssql_next_result($this->_queryID)) return false;\r
-               $this->_inited = false;\r
-               $this->bind = false;\r
-               $this->_currentRow = -1;\r
-               $this->Init();\r
-               return true;\r
-       }\r
-\r
-       /* Use associative array to get fields array */\r
-       function Fields($colname)\r
-       {\r
-               if ($this->fetchMode != ADODB_FETCH_NUM) return $this->fields[$colname];\r
-               if (!$this->bind) {\r
-                       $this->bind = array();\r
-                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                               $o = $this->FetchField($i);\r
-                               $this->bind[strtoupper($o->name)] = $i;\r
-                       }\r
-               }\r
-               \r
-                return $this->fields[$this->bind[strtoupper($colname)]];\r
-       }\r
-       \r
-       /*      Returns: an object containing field information. \r
-               Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
-               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
-               fetchField() is retrieved.      */\r
-\r
-       function FetchField($fieldOffset = -1) \r
-       {\r
-               if ($fieldOffset != -1) {\r
-                       return @mssql_fetch_field($this->_queryID, $fieldOffset);\r
-               }\r
-               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
-                       return @mssql_fetch_field($this->_queryID);\r
-               }\r
-               return null;\r
-       }\r
-       \r
-       function _seek($row) \r
-       {\r
-               return @mssql_data_seek($this->_queryID, $row);\r
-       }\r
-\r
-       // speedup\r
-       function MoveNext() \r
-       {\r
-               if ($this->EOF) return false;\r
-               \r
-               $this->_currentRow++;\r
-               \r
-               if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
-                       if ($this->fetchMode & ADODB_FETCH_NUM) {\r
-                               //ADODB_FETCH_BOTH mode\r
-                               $this->fields = @mssql_fetch_array($this->_queryID);\r
-                       }\r
-                       else {\r
-                               if ($this->hasFetchAssoc) {// only for PHP 4.2.0 or later\r
-                                        $this->fields = @mssql_fetch_assoc($this->_queryID);\r
-                               } else {\r
-                                       $flds = @mssql_fetch_array($this->_queryID);\r
-                                       if (is_array($flds)) {\r
-                                               $fassoc = array();\r
-                                               foreach($flds as $k => $v) {\r
-                                                       if (is_numeric($k)) continue;\r
-                                                       $fassoc[$k] = $v;\r
-                                               }\r
-                                               $this->fields = $fassoc;\r
-                                       } else\r
-                                               $this->fields = false;\r
-                               }\r
-                       }\r
-                       \r
-                       if (is_array($this->fields)) {\r
-                               if (ADODB_ASSOC_CASE == 0) {\r
-                                       foreach($this->fields as $k=>$v) {\r
-                                               $this->fields[strtolower($k)] = $v;\r
-                                       }\r
-                               } else if (ADODB_ASSOC_CASE == 1) {\r
-                                       foreach($this->fields as $k=>$v) {\r
-                                               $this->fields[strtoupper($k)] = $v;\r
-                                       }\r
-                               }\r
-                       }\r
-               } else {\r
-                       $this->fields = @mssql_fetch_row($this->_queryID);\r
-               }\r
-               if ($this->fields) return true;\r
-               $this->EOF = true;\r
-               \r
-               return false;\r
-       }\r
-\r
-       \r
-       // INSERT UPDATE DELETE returns false even if no error occurs in 4.0.4\r
-       // also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot!\r
-       function _fetch($ignore_fields=false) \r
-       {\r
-               if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
-                       if ($this->fetchMode & ADODB_FETCH_NUM) {\r
-                               //ADODB_FETCH_BOTH mode\r
-                               $this->fields = @mssql_fetch_array($this->_queryID);\r
-                       } else {\r
-                               if ($this->hasFetchAssoc) // only for PHP 4.2.0 or later\r
-                                       $this->fields = @mssql_fetch_assoc($this->_queryID);\r
-                               else {\r
-                                       $this->fields = @mssql_fetch_array($this->_queryID);\r
-                                       if (is_array($$this->fields)) {\r
-                                               $fassoc = array();\r
-                                               foreach($$this->fields as $k => $v) {\r
-                                                       if (is_integer($k)) continue;\r
-                                                       $fassoc[$k] = $v;\r
-                                               }\r
-                                               $this->fields = $fassoc;\r
-                                       }\r
-                               }\r
-                       }\r
-                       \r
-                       if (!$this->fields) {\r
-                       } else if (ADODB_ASSOC_CASE == 0) {\r
-                               foreach($this->fields as $k=>$v) {\r
-                                       $this->fields[strtolower($k)] = $v;\r
-                               }\r
-                       } else if (ADODB_ASSOC_CASE == 1) {\r
-                               foreach($this->fields as $k=>$v) {\r
-                                       $this->fields[strtoupper($k)] = $v;\r
-                               }\r
-                       }\r
-               } else {\r
-                       $this->fields = @mssql_fetch_row($this->_queryID);\r
-               }\r
-               return $this->fields;\r
-       }\r
-       \r
-       /*      close() only needs to be called if you are worried about using too much memory while your script\r
-               is running. All associated result memory for the specified result identifier will automatically be freed.       */\r
-\r
-       function _close() \r
-       {\r
-               $rez = mssql_free_result($this->_queryID);      \r
-               $this->_queryID = false;\r
-               return $rez;\r
-       }\r
-       // mssql uses a default date like Dec 30 2000 12:00AM\r
-       function UnixDate($v)\r
-       {\r
-               return ADORecordSet_array_mssql::UnixDate($v);\r
-       }\r
-       \r
-       function UnixTimeStamp($v)\r
-       {\r
-               return ADORecordSet_array_mssql::UnixTimeStamp($v);\r
-       }\r
-       \r
-}\r
-\r
-\r
-class ADORecordSet_array_mssql extends ADORecordSet_array {\r
-       function ADORecordSet_array_mssql($id=-1,$mode=false) \r
-       {\r
-               $this->ADORecordSet_array($id,$mode);\r
-       }\r
-       \r
-               // mssql uses a default date like Dec 30 2000 12:00AM\r
-       function UnixDate($v)\r
-       {\r
-       \r
-               if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v);\r
-               \r
-       global $ADODB_mssql_mths,$ADODB_mssql_date_order;\r
-       \r
-               //Dec 30 2000 12:00AM \r
-               if ($ADODB_mssql_date_order == 'dmy') {\r
-                       if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {\r
-                               return parent::UnixDate($v);\r
-                       }\r
-                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
-                       \r
-                       $theday = $rr[1];\r
-                       $themth =  substr(strtoupper($rr[2]),0,3);\r
-               } else {\r
-                       if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {\r
-                               return parent::UnixDate($v);\r
-                       }\r
-                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
-                       \r
-                       $theday = $rr[2];\r
-                       $themth = substr(strtoupper($rr[1]),0,3);\r
-               }\r
-               $themth = $ADODB_mssql_mths[$themth];\r
-               if ($themth <= 0) return false;\r
-               // h-m-s-MM-DD-YY\r
-               return  mktime(0,0,0,$themth,$theday,$rr[3]);\r
-       }\r
-       \r
-       function UnixTimeStamp($v)\r
-       {\r
-       \r
-               if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v);\r
-               \r
-       global $ADODB_mssql_mths,$ADODB_mssql_date_order;\r
-       \r
-               //Dec 30 2000 12:00AM\r
-                if ($ADODB_mssql_date_order == 'dmy') {\r
-                        if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"\r
-                       ,$v, $rr)) return parent::UnixTimeStamp($v);\r
-                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
-               \r
-                       $theday = $rr[1];\r
-                       $themth =  substr(strtoupper($rr[2]),0,3);\r
-               } else {\r
-                       if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"\r
-                       ,$v, $rr)) return parent::UnixTimeStamp($v);\r
-                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
-               \r
-                       $theday = $rr[2];\r
-                       $themth = substr(strtoupper($rr[1]),0,3);\r
-               }\r
-               \r
-               $themth = $ADODB_mssql_mths[$themth];\r
-               if ($themth <= 0) return false;\r
-               \r
-               switch (strtoupper($rr[6])) {\r
-               case 'P':\r
-                       if ($rr[4]<12) $rr[4] += 12;\r
-                       break;\r
-               case 'A':\r
-                       if ($rr[4]==12) $rr[4] = 0;\r
-                       break;\r
-               default:\r
-                       break;\r
-               }\r
-               // h-m-s-MM-DD-YY\r
-               return  mktime($rr[4],$rr[5],0,$themth,$theday,$rr[3]);\r
-       }\r
-}\r
-\r
-/*\r
-Code Example 1:\r
-\r
-select         object_name(constid) as constraint_name,\r
-               object_name(fkeyid) as table_name, \r
-        col_name(fkeyid, fkey) as column_name,\r
-       object_name(rkeyid) as referenced_table_name,\r
-       col_name(rkeyid, rkey) as referenced_column_name\r
-from sysforeignkeys\r
-where object_name(fkeyid) = x\r
-order by constraint_name, table_name, referenced_table_name,  keyno\r
-\r
-Code Example 2:\r
-select         constraint_name,\r
-       column_name,\r
-       ordinal_position\r
-from information_schema.key_column_usage\r
-where constraint_catalog = db_name()\r
-and table_name = x\r
-order by constraint_name, ordinal_position\r
-\r
-http://www.databasejournal.com/scripts/article.php/1440551\r
-*/\r
-\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Native mssql driver. Requires mssql client. Works on Windows. 
+  To configure for Unix, see 
+       http://phpbuilder.com/columns/alberto20000919.php3
+       
+*/
+
+//----------------------------------------------------------------
+// MSSQL returns dates with the format Oct 13 2002 or 13 Oct 2002
+// and this causes tons of problems because localized versions of 
+// MSSQL will return the dates in dmy or  mdy order; and also the 
+// month strings depends on what language has been configured. The 
+// following two variables allow you to control the localization
+// settings - Ugh.
+//
+// MORE LOCALIZATION INFO
+// ----------------------
+// To configure datetime, look for and modify sqlcommn.loc, 
+//     typically found in c:\mssql\install
+// Also read :
+//      http://support.microsoft.com/default.aspx?scid=kb;EN-US;q220918
+// Alternatively use:
+//        CONVERT(char(12),datecol,120)
+//----------------------------------------------------------------
+
+
+// has datetime converstion to YYYY-MM-DD format, and also mssql_fetch_assoc
+if (ADODB_PHPVER >= 0x4300) {
+// docs say 4.2.0, but testing shows only since 4.3.0 does it work!
+       ini_set('mssql.datetimeconvert',0); 
+} else {
+global $ADODB_mssql_mths;              // array, months must be upper-case
+
+
+       $ADODB_mssql_date_order = 'mdy'; 
+       $ADODB_mssql_mths = array(
+               'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,
+               'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
+}
+
+//---------------------------------------------------------------------------
+// Call this to autoset $ADODB_mssql_date_order at the beginning of your code,
+// just after you connect to the database. Supports mdy and dmy only.
+// Not required for PHP 4.2.0 and above.
+function AutoDetect_MSSQL_Date_Order($conn)
+{
+global $ADODB_mssql_date_order;
+       $adate = $conn->GetOne('select getdate()');
+       if ($adate) {
+               $anum = (int) $adate;
+               if ($anum > 0) {
+                       if ($anum > 31) {
+                               //ADOConnection::outp( "MSSQL: YYYY-MM-DD date format not supported currently");
+                       } else
+                               $ADODB_mssql_date_order = 'dmy';
+               } else
+                       $ADODB_mssql_date_order = 'mdy';
+       }
+}
+
+class ADODB_mssql extends ADOConnection {
+       var $databaseType = "mssql";    
+       var $dataProvider = "mssql";
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $fmtDate = "'Y-m-d'";
+       var $fmtTimeStamp = "'Y-m-d h:i:sA'";
+       var $hasInsertID = true;
+       var $substr = "substring";
+       var $length = 'len';
+       var $upperCase = 'upper';
+       var $hasAffectedRows = true;
+       var $metaDatabasesSQL = "select name from sysdatabases where name <> 'master'";
+       var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE','dtproperties'))";
+       var $metaColumnsSQL = # xtype==61 is datetime
+"select c.name,t.name,c.length,
+       (case when c.xusertype=61 then 0 else c.xprec end),
+       (case when c.xusertype=61 then 0 else c.xscale end) 
+       from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";
+       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE
+       var $hasGenID = true;
+       var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';
+       var $sysTimeStamp = 'GetDate()';
+       var $_has_mssql_init;
+       var $maxParameterLen = 4000;
+       var $arrayClass = 'ADORecordSet_array_mssql';
+       var $uniqueSort = true;
+       var $leftOuter = '*=';
+       var $rightOuter = '=*';
+       var $ansiOuter = true; // for mssql7 or later
+       var $poorAffectedRows = true;
+       var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000
+       var $uniqueOrderBy = true;
+       var $_bindInputArray = true;
+       
+       
+       function ADODB_mssql() 
+       {               
+               $this->_has_mssql_init = (strnatcmp(PHP_VERSION,'4.1.0')>=0);
+       }
+
+       function ServerInfo()
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $stmt = $this->PrepareSP('sp_server_info');
+               $val = 2;
+               if ($this->fetchMode === false) {
+                       $savem = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               } else 
+                       $savem = $this->SetFetchMode(ADODB_FETCH_NUM);
+               
+               
+               $this->Parameter($stmt,$val,'attribute_id');
+               $row = $this->GetRow($stmt);
+               
+               //$row = $this->GetRow("execute sp_server_info 2");
+               
+               if ($this->fetchMode === false) {
+                       $ADODB_FETCH_MODE = $savem;
+               } else
+                       $this->SetFetchMode($savem);
+               
+               $arr['description'] = $row[2];
+               $arr['version'] = ADOConnection::_findvers($arr['description']);
+               return $arr;
+       }
+       
+       function IfNull( $field, $ifNull ) 
+       {
+               return " ISNULL($field, $ifNull) "; // if MS SQL Server
+       }
+       
+       function _insertid()
+       {
+       // SCOPE_IDENTITY()
+       // Returns the last IDENTITY value inserted into an IDENTITY column in 
+       // the same scope. A scope is a module -- a stored procedure, trigger, 
+       // function, or batch. Thus, two statements are in the same scope if 
+       // they are in the same stored procedure, function, or batch.
+                       return $this->GetOne($this->identitySQL);
+       }
+
+       function _affectedrows()
+       {
+               return $this->GetOne('select @@rowcount');
+       }
+
+       var $_dropSeqSQL = "drop table %s";
+       
+       function CreateSequence($seq='adodbseq',$start=1)
+       {
+               $start -= 1;
+               $this->Execute("create table $seq (id float(53))");
+               $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
+               if (!$ok) {
+                               $this->Execute('ROLLBACK TRANSACTION adodbseq');
+                               return false;
+               }
+               $this->Execute('COMMIT TRANSACTION adodbseq'); 
+               return true;
+       }
+
+       function GenID($seq='adodbseq',$start=1)
+       {
+               //$this->debug=1;
+               $this->Execute('BEGIN TRANSACTION adodbseq');
+               $ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1");
+               if (!$ok) {
+                       $this->Execute("create table $seq (id float(53))");
+                       $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
+                       if (!$ok) {
+                               $this->Execute('ROLLBACK TRANSACTION adodbseq');
+                               return false;
+                       }
+                       $this->Execute('COMMIT TRANSACTION adodbseq'); 
+                       return $start;
+               }
+               $num = $this->GetOne("select id from $seq");
+               $this->Execute('COMMIT TRANSACTION adodbseq'); 
+               return $num;
+               
+               // in old implementation, pre 1.90, we returned GUID...
+               //return $this->GetOne("SELECT CONVERT(varchar(255), NEWID()) AS 'Char'");
+       }
+       
+
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+       {
+               if ($nrows > 0 && $offset <= 0) {
+                       $sql = preg_replace(
+                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);
+                       $rs =& $this->Execute($sql,$inputarr);
+               } else
+                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+       
+               return $rs;
+       }
+       
+       
+       // Format date column in sql string given an input format that understands Y M D
+       function SQLDate($fmt, $col=false)
+       {       
+               if (!$col) $col = $this->sysTimeStamp;
+               $s = '';
+               
+               $len = strlen($fmt);
+               for ($i=0; $i < $len; $i++) {
+                       if ($s) $s .= '+';
+                       $ch = $fmt[$i];
+                       switch($ch) {
+                       case 'Y':
+                       case 'y':
+                               $s .= "datename(yyyy,$col)";
+                               break;
+                       case 'M':
+                               $s .= "convert(char(3),$col,0)";
+                               break;
+                       case 'm':
+                               $s .= "replace(str(month($col),2),' ','0')";
+                               break;
+                       case 'Q':
+                       case 'q':
+                               $s .= "datename(quarter,$col)";
+                               break;
+                       case 'D':
+                       case 'd':
+                               $s .= "replace(str(day($col),2),' ','0')";
+                               break;
+                       case 'h':
+                               $s .= "substring(convert(char(14),$col,0),13,2)";
+                               break;
+                       
+                       case 'H':
+                               $s .= "replace(str(datepart(hh,$col),2),' ','0')";
+                               break;
+                               
+                       case 'i':
+                               $s .= "replace(str(datepart(mi,$col),2),' ','0')";
+                               break;
+                       case 's':
+                               $s .= "replace(str(datepart(ss,$col),2),' ','0')";
+                               break;
+                       case 'a':
+                       case 'A':
+                               $s .= "substring(convert(char(19),$col,0),18,2)";
+                               break;
+                               
+                       default:
+                               if ($ch == '\\') {
+                                       $i++;
+                                       $ch = substr($fmt,$i,1);
+                               }
+                               $s .= $this->qstr($ch);
+                               break;
+                       }
+               }
+               return $s;
+       }
+
+       
+       function BeginTrans()
+       {
+               if ($this->transOff) return true; 
+               $this->transCnt += 1;
+               $this->Execute('BEGIN TRAN');
+               return true;
+       }
+               
+       function CommitTrans($ok=true) 
+       { 
+               if ($this->transOff) return true; 
+               if (!$ok) return $this->RollbackTrans();
+               if ($this->transCnt) $this->transCnt -= 1;
+               $this->Execute('COMMIT TRAN');
+               return true;
+       }
+       function RollbackTrans()
+       {
+               if ($this->transOff) return true; 
+               if ($this->transCnt) $this->transCnt -= 1;
+               $this->Execute('ROLLBACK TRAN');
+               return true;
+       }
+       
+       /*
+               Usage:
+               
+               $this->BeginTrans();
+               $this->RowLock('table1,table2','table1.id=33 and table2.id=table1.id'); # lock row 33 for both tables
+               
+               # some operation on both tables table1 and table2
+               
+               $this->CommitTrans();
+               
+               See http://www.swynk.com/friends/achigrik/SQL70Locks.asp
+       */
+       function RowLock($tables,$where) 
+       {
+               if (!$this->transCnt) $this->BeginTrans();
+               return $this->GetOne("select top 1 null as ignore from $tables with (ROWLOCK,HOLDLOCK) where $where");
+       }
+       
+       function MetaForeignKeys($table, $owner=false, $upper=false)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $table = $this->qstr(strtoupper($table));
+               
+               $sql = 
+"select object_name(constid) as constraint_name,
+       col_name(fkeyid, fkey) as column_name,
+       object_name(rkeyid) as referenced_table_name,
+       col_name(rkeyid, rkey) as referenced_column_name
+from sysforeignkeys
+where upper(object_name(fkeyid)) = $table
+order by constraint_name, referenced_table_name, keyno";
+               
+               $constraints =& $this->GetArray($sql);
+               
+               $ADODB_FETCH_MODE = $save;
+               
+               $arr = false;
+               foreach($constraints as $constr) {
+                       //print_r($constr);
+                       $arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; 
+               }
+               if (!$arr) return false;
+               
+               $arr2 = false;
+               
+               foreach($arr as $k => $v) {
+                       foreach($v as $a => $b) {
+                               if ($upper) $a = strtoupper($a);
+                               $arr2[$a] = $b;
+                       }
+               }
+               return $arr2;
+       }
+
+       //From: Fernando Moreira <FMoreira@imediata.pt>
+       function MetaDatabases() 
+       { 
+               if(@mssql_select_db("master")) { 
+                                $qry=$this->metaDatabasesSQL; 
+                                if($rs=@mssql_query($qry)){ 
+                                                $tmpAr=$ar=array(); 
+                                                while($tmpAr=@mssql_fetch_row($rs)) 
+                                                                $ar[]=$tmpAr[0]; 
+                                               @mssql_select_db($this->databaseName); 
+                                                if(sizeof($ar)) 
+                                                                return($ar); 
+                                                else 
+                                                                return(false); 
+                                } else { 
+                                                @mssql_select_db($this->databaseName); 
+                                                return(false); 
+                                } 
+                } 
+                return(false); 
+       } 
+
+       // "Stein-Aksel Basma" <basma@accelero.no>
+       // tested with MSSQL 2000
+       function MetaPrimaryKeys($table)
+       {
+               $sql = "select k.column_name from information_schema.key_column_usage k,
+               information_schema.table_constraints tc 
+               where tc.constraint_name = k.constraint_name and tc.constraint_type =
+               'PRIMARY KEY' and k.table_name = '$table'";
+               
+               $a = $this->GetCol($sql);
+               if ($a && sizeof($a)>0) return $a;
+               return false;     
+       }
+
+       
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+       {
+               if ($mask) {
+                       $save = $this->metaTablesSQL;
+                       $mask = $this->qstr(($mask));
+                       $this->metaTablesSQL .= " AND name like $mask";
+               }
+               $ret =& ADOConnection::MetaTables($ttype,$showSchema);
+               
+               if ($mask) {
+                       $this->metaTablesSQL = $save;
+               }
+               return $ret;
+       }
+       function SelectDB($dbName) 
+       {
+               $this->databaseName = $dbName;
+               if ($this->_connectionID) {
+                       return @mssql_select_db($dbName);               
+               }
+               else return false;      
+       }
+       
+       function ErrorMsg() 
+       {
+               if (empty($this->_errorMsg)){
+                       $this->_errorMsg = mssql_get_last_message();
+               }
+               return $this->_errorMsg;
+       }
+       
+       function ErrorNo() 
+       {
+               if ($this->_logsql && $this->_errorCode !== false) return $this->_errorCode;
+               if (empty($this->_errorMsg)) {
+                       $this->_errorMsg = mssql_get_last_message();
+               }
+               $id = @mssql_query("select @@ERROR",$this->_connectionID);
+               if (!$id) return false;
+               $arr = mssql_fetch_array($id);
+               @mssql_free_result($id);
+               if (is_array($arr)) return $arr[0];
+          else return -1;
+       }
+       
+       // returns true or false
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (!function_exists('mssql_pconnect')) return false;
+               $this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword);
+               if ($this->_connectionID === false) return false;
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);
+               return true;    
+       }
+       
+       
+       // returns true or false
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (!function_exists('mssql_pconnect')) return false;
+               $this->_connectionID = mssql_pconnect($argHostname,$argUsername,$argPassword);
+               if ($this->_connectionID === false) return false;
+               
+               // persistent connections can forget to rollback on crash, so we do it here.
+               if ($this->autoRollback) {
+                       $cnt = $this->GetOne('select @@TRANCOUNT');
+                       while (--$cnt >= 0) $this->Execute('ROLLBACK TRAN'); 
+               }
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);
+               return true;    
+       }
+       
+       function Prepare($sql)
+       {
+               $sqlarr = explode('?',$sql);
+               if (sizeof($sqlarr) <= 1) return $sql;
+               $sql2 = $sqlarr[0];
+               for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {
+                       $sql2 .=  '@P'.($i-1) . $sqlarr[$i];
+               } 
+               return array($sql,$this->qstr($sql2),$max);
+       }
+       
+       function PrepareSP($sql)
+       {
+               if (!$this->_has_mssql_init) {
+                       ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
+                       return $sql;
+               }
+               $stmt = mssql_init($sql,$this->_connectionID);
+               if (!$stmt)  return $sql;
+               return array($sql,$stmt);
+       }
+       
+       /* 
+       Usage:
+               $stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group
+               
+               # note that the parameter does not have @ in front!
+               $db->Parameter($stmt,$id,'myid');
+               $db->Parameter($stmt,$group,'group',false,64);
+               $db->Execute($stmt);
+               
+               @param $stmt Statement returned by Prepare() or PrepareSP().
+               @param $var PHP variable to bind to. Can set to null (for isNull support).
+               @param $name Name of stored procedure variable name to bind to.
+               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
+               @param [$maxLen] Holds an maximum length of the variable.
+               @param [$type] The data type of $var. Legal values depend on driver.
+               
+               See mssql_bind documentation at php.net.
+       */
+       function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=4000, $type=false)
+       {
+               if (!$this->_has_mssql_init) {
+                       ADOConnection::outp( "Parameter: mssql_bind only available since PHP 4.1.0");
+                       return $sql;
+               }
+
+               $isNull = is_null($var); // php 4.0.4 and above...
+                       
+               if ($type === false) 
+                       switch(gettype($var)) {
+                       default:
+                       case 'string': $type = SQLCHAR; break;
+                       case 'double': $type = SQLFLT8; break;
+                       case 'integer': $type = SQLINT4; break;
+                       case 'boolean': $type = SQLINT1; break; # SQLBIT not supported in 4.1.0
+                       }
+               
+               if  ($this->debug) {
+                       $prefix = ($isOutput) ? 'Out' : 'In';
+                       $ztype = (empty($type)) ? 'false' : $type;
+                       ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");
+               }
+               /*
+                       See http://phplens.com/lens/lensforum/msgs.php?id=7231
+                       
+                       RETVAL is HARD CODED into php_mssql extension:
+                       The return value (a long integer value) is treated like a special OUTPUT parameter, 
+                       called "RETVAL" (without the @). See the example at mssql_execute to 
+                       see how it works. - type: one of this new supported PHP constants. 
+                               SQLTEXT, SQLVARCHAR,SQLCHAR, SQLINT1,SQLINT2, SQLINT4, SQLBIT,SQLFLT8 
+               */
+               if ($name !== 'RETVAL') $name = '@'.$name;
+               return mssql_bind($stmt[1], $name, $var, $type, $isOutput, $isNull, $maxLen);
+       }
+       
+       /* 
+               Unfortunately, it appears that mssql cannot handle varbinary > 255 chars
+               So all your blobs must be of type "image".
+               
+               Remember to set in php.ini the following...
+               
+               ; Valid range 0 - 2147483647. Default = 4096. 
+               mssql.textlimit = 0 ; zero to pass through 
+
+               ; Valid range 0 - 2147483647. Default = 4096. 
+               mssql.textsize = 0 ; zero to pass through 
+       */
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+       {
+               $sql = "UPDATE $table SET $column=0x".bin2hex($val)." WHERE $where";
+               return $this->Execute($sql) != false;
+       }
+       
+       // returns query ID if successful, otherwise false
+       function _query($sql,$inputarr)
+       {
+               $this->_errorMsg = false;
+               if (is_array($inputarr)) {
+                       
+                       # bind input params with sp_executesql: 
+                       # see http://www.quest-pipelines.com/newsletter-v3/0402_F.htm
+                       # works only with sql server 7 and newer
+                       if (!is_array($sql)) $sql = $this->Prepare($sql);
+                       $params = '';
+                       $decl = '';
+                       $i = 0;
+                       foreach($inputarr as $v) {
+                               if ($decl) {
+                                       $decl .= ', ';
+                                       $params .= ', ';
+                               }       
+                               if (is_string($v)) {
+                                       $len = strlen($v);
+                                       if ($len == 0) $len = 1;
+                                       
+                                       if ($len > 4000 ) {
+                                               // NVARCHAR is max 4000 chars. Let's use NTEXT
+                                               $decl .= "@P$i NTEXT";
+                                       } else {
+                                               $decl .= "@P$i NVARCHAR($len)";
+                                       }
+
+                                       $params .= "@P$i=N". (strncmp($v,"'",1)==0? $v : $this->qstr($v));
+                               } else if (is_integer($v)) {
+                                       $decl .= "@P$i INT";
+                                       $params .= "@P$i=".$v;
+                               } else {
+                                       $decl .= "@P$i FLOAT";
+                                       $params .= "@P$i=".$v;
+                               }
+                               $i += 1;
+                       }
+                       $decl = $this->qstr($decl);
+                       if ($this->debug) ADOConnection::outp("<font size=-1>sp_executesql N{$sql[1]},N$decl,$params</font>");
+                       $rez = mssql_query("sp_executesql N{$sql[1]},N$decl,$params");
+                       
+               } else if (is_array($sql)) {
+                       # PrepareSP()
+                       $rez = mssql_execute($sql[1]);
+                       
+               } else {
+                       $rez = mssql_query($sql,$this->_connectionID);
+               }
+               return $rez;
+       }
+       
+       // returns true or false
+       function _close()
+       { 
+               if ($this->transCnt) $this->RollbackTrans();
+               $rez = @mssql_close($this->_connectionID);
+               $this->_connectionID = false;
+               return $rez;
+       }
+       
+       // mssql uses a default date like Dec 30 2000 12:00AM
+       function UnixDate($v)
+       {
+               return ADORecordSet_array_mssql::UnixDate($v);
+       }
+       
+       function UnixTimeStamp($v)
+       {
+               return ADORecordSet_array_mssql::UnixTimeStamp($v);
+       }       
+}
+       
+/*--------------------------------------------------------------------------------------
+        Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_mssql extends ADORecordSet {        
+
+       var $databaseType = "mssql";
+       var $canSeek = true;
+       var $hasFetchAssoc; // see http://phplens.com/lens/lensforum/msgs.php?id=6083
+       // _mths works only in non-localised system
+       
+       function ADORecordset_mssql($id,$mode=false)
+       {
+               // freedts check...
+               $this->hasFetchAssoc = function_exists('mssql_fetch_assoc');
+
+               if ($mode === false) { 
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               $this->fetchMode = $mode;
+               return $this->ADORecordSet($id,$mode);
+       }
+       
+       
+       function _initrs()
+       {
+       GLOBAL $ADODB_COUNTRECS;        
+               $this->_numOfRows = ($ADODB_COUNTRECS)? @mssql_num_rows($this->_queryID):-1;
+               $this->_numOfFields = @mssql_num_fields($this->_queryID);
+       }
+       
+
+       //Contributed by "Sven Axelsson" <sven.axelsson@bokochwebb.se>
+       // get next resultset - requires PHP 4.0.5 or later
+       function NextRecordSet()
+       {
+               if (!mssql_next_result($this->_queryID)) return false;
+               $this->_inited = false;
+               $this->bind = false;
+               $this->_currentRow = -1;
+               $this->Init();
+               return true;
+       }
+
+       /* Use associative array to get fields array */
+       function Fields($colname)
+       {
+               if ($this->fetchMode != ADODB_FETCH_NUM) return $this->fields[$colname];
+               if (!$this->bind) {
+                       $this->bind = array();
+                       for ($i=0; $i < $this->_numOfFields; $i++) {
+                               $o = $this->FetchField($i);
+                               $this->bind[strtoupper($o->name)] = $i;
+                       }
+               }
+               
+                return $this->fields[$this->bind[strtoupper($colname)]];
+       }
+       
+       /*      Returns: an object containing field information. 
+               Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+               fetchField() is retrieved.      */
+
+       function FetchField($fieldOffset = -1) 
+       {
+               if ($fieldOffset != -1) {
+                       return @mssql_fetch_field($this->_queryID, $fieldOffset);
+               }
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */
+                       return @mssql_fetch_field($this->_queryID);
+               }
+               return null;
+       }
+       
+       function _seek($row) 
+       {
+               return @mssql_data_seek($this->_queryID, $row);
+       }
+
+       // speedup
+       function MoveNext() 
+       {
+               if ($this->EOF) return false;
+               
+               $this->_currentRow++;
+               
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+                       if ($this->fetchMode & ADODB_FETCH_NUM) {
+                               //ADODB_FETCH_BOTH mode
+                               $this->fields = @mssql_fetch_array($this->_queryID);
+                       }
+                       else {
+                               if ($this->hasFetchAssoc) {// only for PHP 4.2.0 or later
+                                        $this->fields = @mssql_fetch_assoc($this->_queryID);
+                               } else {
+                                       $flds = @mssql_fetch_array($this->_queryID);
+                                       if (is_array($flds)) {
+                                               $fassoc = array();
+                                               foreach($flds as $k => $v) {
+                                                       if (is_numeric($k)) continue;
+                                                       $fassoc[$k] = $v;
+                                               }
+                                               $this->fields = $fassoc;
+                                       } else
+                                               $this->fields = false;
+                               }
+                       }
+                       
+                       if (is_array($this->fields)) {
+                               if (ADODB_ASSOC_CASE == 0) {
+                                       foreach($this->fields as $k=>$v) {
+                                               $this->fields[strtolower($k)] = $v;
+                                       }
+                               } else if (ADODB_ASSOC_CASE == 1) {
+                                       foreach($this->fields as $k=>$v) {
+                                               $this->fields[strtoupper($k)] = $v;
+                                       }
+                               }
+                       }
+               } else {
+                       $this->fields = @mssql_fetch_row($this->_queryID);
+               }
+               if ($this->fields) return true;
+               $this->EOF = true;
+               
+               return false;
+       }
+
+       
+       // INSERT UPDATE DELETE returns false even if no error occurs in 4.0.4
+       // also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot!
+       function _fetch($ignore_fields=false) 
+       {
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+                       if ($this->fetchMode & ADODB_FETCH_NUM) {
+                               //ADODB_FETCH_BOTH mode
+                               $this->fields = @mssql_fetch_array($this->_queryID);
+                       } else {
+                               if ($this->hasFetchAssoc) // only for PHP 4.2.0 or later
+                                       $this->fields = @mssql_fetch_assoc($this->_queryID);
+                               else {
+                                       $this->fields = @mssql_fetch_array($this->_queryID);
+                                       if (is_array($$this->fields)) {
+                                               $fassoc = array();
+                                               foreach($$this->fields as $k => $v) {
+                                                       if (is_integer($k)) continue;
+                                                       $fassoc[$k] = $v;
+                                               }
+                                               $this->fields = $fassoc;
+                                       }
+                               }
+                       }
+                       
+                       if (!$this->fields) {
+                       } else if (ADODB_ASSOC_CASE == 0) {
+                               foreach($this->fields as $k=>$v) {
+                                       $this->fields[strtolower($k)] = $v;
+                               }
+                       } else if (ADODB_ASSOC_CASE == 1) {
+                               foreach($this->fields as $k=>$v) {
+                                       $this->fields[strtoupper($k)] = $v;
+                               }
+                       }
+               } else {
+                       $this->fields = @mssql_fetch_row($this->_queryID);
+               }
+               return $this->fields;
+       }
+       
+       /*      close() only needs to be called if you are worried about using too much memory while your script
+               is running. All associated result memory for the specified result identifier will automatically be freed.       */
+
+       function _close() 
+       {
+               $rez = mssql_free_result($this->_queryID);      
+               $this->_queryID = false;
+               return $rez;
+       }
+       // mssql uses a default date like Dec 30 2000 12:00AM
+       function UnixDate($v)
+       {
+               return ADORecordSet_array_mssql::UnixDate($v);
+       }
+       
+       function UnixTimeStamp($v)
+       {
+               return ADORecordSet_array_mssql::UnixTimeStamp($v);
+       }
+       
+}
+
+
+class ADORecordSet_array_mssql extends ADORecordSet_array {
+       function ADORecordSet_array_mssql($id=-1,$mode=false) 
+       {
+               $this->ADORecordSet_array($id,$mode);
+       }
+       
+               // mssql uses a default date like Dec 30 2000 12:00AM
+       function UnixDate($v)
+       {
+       
+               if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v);
+               
+       global $ADODB_mssql_mths,$ADODB_mssql_date_order;
+       
+               //Dec 30 2000 12:00AM 
+               if ($ADODB_mssql_date_order == 'dmy') {
+                       if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {
+                               return parent::UnixDate($v);
+                       }
+                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+                       
+                       $theday = $rr[1];
+                       $themth =  substr(strtoupper($rr[2]),0,3);
+               } else {
+                       if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {
+                               return parent::UnixDate($v);
+                       }
+                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+                       
+                       $theday = $rr[2];
+                       $themth = substr(strtoupper($rr[1]),0,3);
+               }
+               $themth = $ADODB_mssql_mths[$themth];
+               if ($themth <= 0) return false;
+               // h-m-s-MM-DD-YY
+               return  mktime(0,0,0,$themth,$theday,$rr[3]);
+       }
+       
+       function UnixTimeStamp($v)
+       {
+       
+               if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v);
+               
+       global $ADODB_mssql_mths,$ADODB_mssql_date_order;
+       
+               //Dec 30 2000 12:00AM
+                if ($ADODB_mssql_date_order == 'dmy') {
+                        if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"
+                       ,$v, $rr)) return parent::UnixTimeStamp($v);
+                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+               
+                       $theday = $rr[1];
+                       $themth =  substr(strtoupper($rr[2]),0,3);
+               } else {
+                       if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"
+                       ,$v, $rr)) return parent::UnixTimeStamp($v);
+                       if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+               
+                       $theday = $rr[2];
+                       $themth = substr(strtoupper($rr[1]),0,3);
+               }
+               
+               $themth = $ADODB_mssql_mths[$themth];
+               if ($themth <= 0) return false;
+               
+               switch (strtoupper($rr[6])) {
+               case 'P':
+                       if ($rr[4]<12) $rr[4] += 12;
+                       break;
+               case 'A':
+                       if ($rr[4]==12) $rr[4] = 0;
+                       break;
+               default:
+                       break;
+               }
+               // h-m-s-MM-DD-YY
+               return  mktime($rr[4],$rr[5],0,$themth,$theday,$rr[3]);
+       }
+}
+
+/*
+Code Example 1:
+
+select         object_name(constid) as constraint_name,
+               object_name(fkeyid) as table_name, 
+        col_name(fkeyid, fkey) as column_name,
+       object_name(rkeyid) as referenced_table_name,
+       col_name(rkeyid, rkey) as referenced_column_name
+from sysforeignkeys
+where object_name(fkeyid) = x
+order by constraint_name, table_name, referenced_table_name,  keyno
+
+Code Example 2:
+select         constraint_name,
+       column_name,
+       ordinal_position
+from information_schema.key_column_usage
+where constraint_catalog = db_name()
+and table_name = x
+order by constraint_name, ordinal_position
+
+http://www.databasejournal.com/scripts/article.php/1440551
+*/
+
 ?>
\ No newline at end of file
index d727def5fe0340b04afe510560398d859a2d0fab..4eca722672434f6d7e817d8cd791d28cc909d443 100644 (file)
@@ -1,59 +1,59 @@
-<?php\r
-/**\r
-* @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-* Released under both BSD license and Lesser GPL library license.\r
-* Whenever there is any discrepancy between the two licenses,\r
-* the BSD license will take precedence.\r
-*\r
-* Set tabs to 4 for best viewing.\r
-*\r
-* Latest version is available at http://php.weblogs.com\r
-*\r
-*  Portable MSSQL Driver that supports || instead of +\r
-*\r
-*/\r
-\r
-\r
-/*\r
-       The big difference between mssqlpo and it's parent mssql is that mssqlpo supports\r
-       the more standard || string concatenation operator.\r
-*/\r
-       \r
-include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php');\r
-\r
-class ADODB_mssqlpo extends ADODB_mssql {\r
-       var $databaseType = "mssqlpo";\r
-       var $concat_operator = '||'; \r
-       \r
-       function ADODB_mssqlpo()\r
-       {\r
-               ADODB_mssql::ADODB_mssql();\r
-       }\r
-\r
-       function PrepareSP($sql)\r
-       {\r
-               if (!$this->_has_mssql_init) {\r
-                       ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");\r
-                       return $sql;\r
-               }\r
-               if (is_string($sql)) $sql = str_replace('||','+',$sql);\r
-               $stmt = mssql_init($sql,$this->_connectionID);\r
-               if (!$stmt)  return $sql;\r
-               return array($sql,$stmt);\r
-       }\r
-       \r
-       function _query($sql,$inputarr)\r
-       {\r
-               if (is_string($sql)) $sql = str_replace('||','+',$sql);\r
-               return ADODB_mssql::_query($sql,$inputarr);\r
-       }\r
-}\r
-\r
-class ADORecordset_mssqlpo extends ADORecordset_mssql {\r
-       var $databaseType = "mssqlpo";\r
-       function ADORecordset_mssqlpo($id,$mode=false)\r
-       {\r
-               $this->ADORecordset_mssql($id,$mode);\r
-       }\r
-}\r
+<?php
+/**
+* @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+* Released under both BSD license and Lesser GPL library license.
+* Whenever there is any discrepancy between the two licenses,
+* the BSD license will take precedence.
+*
+* Set tabs to 4 for best viewing.
+*
+* Latest version is available at http://php.weblogs.com
+*
+*  Portable MSSQL Driver that supports || instead of +
+*
+*/
+
+
+/*
+       The big difference between mssqlpo and it's parent mssql is that mssqlpo supports
+       the more standard || string concatenation operator.
+*/
+       
+include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php');
+
+class ADODB_mssqlpo extends ADODB_mssql {
+       var $databaseType = "mssqlpo";
+       var $concat_operator = '||'; 
+       
+       function ADODB_mssqlpo()
+       {
+               ADODB_mssql::ADODB_mssql();
+       }
+
+       function PrepareSP($sql)
+       {
+               if (!$this->_has_mssql_init) {
+                       ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
+                       return $sql;
+               }
+               if (is_string($sql)) $sql = str_replace('||','+',$sql);
+               $stmt = mssql_init($sql,$this->_connectionID);
+               if (!$stmt)  return $sql;
+               return array($sql,$stmt);
+       }
+       
+       function _query($sql,$inputarr)
+       {
+               if (is_string($sql)) $sql = str_replace('||','+',$sql);
+               return ADODB_mssql::_query($sql,$inputarr);
+       }
+}
+
+class ADORecordset_mssqlpo extends ADORecordset_mssql {
+       var $databaseType = "mssqlpo";
+       function ADORecordset_mssqlpo($id,$mode=false)
+       {
+               $this->ADORecordset_mssql($id,$mode);
+       }
+}
 ?>
\ No newline at end of file
index e5b79ad631c424288148da249af9da4991bf2537..354845a010a391d8ab46f05f5f3e1c6e7294b43e 100644 (file)
-<?php\r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 8.\r
-  \r
-  MySQL code that does not support transactions. Use mysqlt if you need transactions.\r
-  Requires mysql client. Works on Windows and Unix.\r
-  \r
- 28 Feb 2001: MetaColumns bug fix - suggested by  Freek Dijkstra (phpeverywhere@macfreek.com)\r
-*/ \r
-\r
-if (! defined("_ADODB_MYSQL_LAYER")) {\r
- define("_ADODB_MYSQL_LAYER", 1 );\r
-\r
-class ADODB_mysql extends ADOConnection {\r
-       var $databaseType = 'mysql';\r
-       var $dataProvider = 'mysql';\r
-       var $hasInsertID = true;\r
-       var $hasAffectedRows = true;    \r
-       var $metaTablesSQL = "SHOW TABLES";     \r
-       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";\r
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
-       var $hasLimit = true;\r
-       var $hasMoveFirst = true;\r
-       var $hasGenID = true;\r
-       var $upperCase = 'upper';\r
-       var $isoDates = true; // accepts dates in ISO format\r
-       var $sysDate = 'CURDATE()';\r
-       var $sysTimeStamp = 'NOW()';\r
-       var $hasTransactions = false;\r
-       var $forceNewConnect = false;\r
-       var $poorAffectedRows = true;\r
-       var $clientFlags = 0;\r
-       var $substr = "substring";\r
-       var $nameQuote = '`';           /// string to use to quote identifiers and names\r
-       \r
-       function ADODB_mysql() \r
-       {                       \r
-       }\r
-       \r
-       function ServerInfo()\r
-       {\r
-               $arr['description'] = ADOConnection::GetOne("select version()");\r
-               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
-               return $arr;\r
-       }\r
-       \r
-       function IfNull( $field, $ifNull ) \r
-       {\r
-               return " IFNULL($field, $ifNull) "; // if MySQL\r
-       }\r
-       \r
-       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
-       {       \r
-               if ($mask) {\r
-                       $save = $this->metaTablesSQL;\r
-                       $mask = $this->qstr($mask);\r
-                       $this->metaTablesSQL .= " like $mask";\r
-               }\r
-               $ret =& ADOConnection::MetaTables($ttype,$showSchema);\r
-               \r
-               if ($mask) {\r
-                       $this->metaTablesSQL = $save;\r
-               }\r
-               return $ret;\r
-       }\r
-       \r
-       \r
-       function &MetaIndexes ($table, $primary = FALSE, $owner=false)\r
-       {\r
-        // save old fetch mode\r
-        global $ADODB_FETCH_MODE;\r
-        \r
-        $save = $ADODB_FETCH_MODE;\r
-        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-        if ($this->fetchMode !== FALSE) {\r
-               $savem = $this->SetFetchMode(FALSE);\r
-        }\r
-        \r
-        // get index details\r
-        $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table));\r
-        \r
-        // restore fetchmode\r
-        if (isset($savem)) {\r
-                $this->SetFetchMode($savem);\r
-        }\r
-        $ADODB_FETCH_MODE = $save;\r
-        \r
-        if (!is_object($rs)) {\r
-                return FALSE;\r
-        }\r
-        \r
-        $indexes = array ();\r
-        \r
-        // parse index data into array\r
-        while ($row = $rs->FetchRow()) {\r
-                if ($primary == FALSE AND $row[2] == 'PRIMARY') {\r
-                        continue;\r
-                }\r
-                \r
-                if (!isset($indexes[$row[2]])) {\r
-                        $indexes[$row[2]] = array(\r
-                                'unique' => ($row[1] == 0),\r
-                                'columns' => array()\r
-                        );\r
-                }\r
-                \r
-                $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];\r
-        }\r
-        \r
-        // sort columns by order in the index\r
-        foreach ( array_keys ($indexes) as $index )\r
-        {\r
-                ksort ($indexes[$index]['columns']);\r
-        }\r
-        \r
-        return $indexes;\r
-       }\r
-\r
-       \r
-       // if magic quotes disabled, use mysql_real_escape_string()\r
-       function qstr($s,$magic_quotes=false)\r
-       {\r
-               if (!$magic_quotes) {\r
-               \r
-                       if (ADODB_PHPVER >= 0x4300) {\r
-                               if (is_resource($this->_connectionID))\r
-                                       return "'".mysql_real_escape_string($s,$this->_connectionID)."'";\r
-                       }\r
-                       if ($this->replaceQuote[0] == '\\'){\r
-                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);\r
-                       }\r
-                       return  "'".str_replace("'",$this->replaceQuote,$s)."'"; \r
-               }\r
-               \r
-               // undo magic quotes for "\r
-               $s = str_replace('\\"','"',$s);\r
-               return "'$s'";\r
-       }\r
-       \r
-       function _insertid()\r
-       {\r
-               return mysql_insert_id($this->_connectionID);\r
-       }\r
-       \r
-       function GetOne($sql,$inputarr=false)\r
-       {\r
-               $rs =& $this->SelectLimit($sql,1,-1,$inputarr);\r
-               if ($rs) {\r
-                       $rs->Close();\r
-                       if ($rs->EOF) return false;\r
-                       return reset($rs->fields);\r
-               }\r
-               \r
-               return false;\r
-       }\r
-       \r
-       function _affectedrows()\r
-       {\r
-                       return mysql_affected_rows($this->_connectionID);\r
-       }\r
-  \r
-       // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html\r
-       // Reference on Last_Insert_ID on the recommended way to simulate sequences\r
-       var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";\r
-       var $_genSeqSQL = "create table %s (id int not null)";\r
-       var $_genSeq2SQL = "insert into %s values (%s)";\r
-       var $_dropSeqSQL = "drop table %s";\r
-       \r
-       function CreateSequence($seqname='adodbseq',$startID=1)\r
-       {\r
-               if (empty($this->_genSeqSQL)) return false;\r
-               $u = strtoupper($seqname);\r
-               \r
-               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
-               if (!$ok) return false;\r
-               return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));\r
-       }\r
-       \r
-\r
-       function GenID($seqname='adodbseq',$startID=1)\r
-       {\r
-               // post-nuke sets hasGenID to false\r
-               if (!$this->hasGenID) return false;\r
-               \r
-               $savelog = $this->_logsql;\r
-               $this->_logsql = false;\r
-               $getnext = sprintf($this->_genIDSQL,$seqname);\r
-               $holdtransOK = $this->_transOK; // save the current status\r
-               $rs = @$this->Execute($getnext);\r
-               if (!$rs) {\r
-                       if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset\r
-                       $u = strtoupper($seqname);\r
-                       $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
-                       $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));\r
-                       $rs = $this->Execute($getnext);\r
-               }\r
-               $this->genID = mysql_insert_id($this->_connectionID);\r
-               \r
-               if ($rs) $rs->Close();\r
-               \r
-               $this->_logsql = $savelog;\r
-               return $this->genID;\r
-       }\r
-       \r
-       function &MetaDatabases()\r
-       {\r
-               $qid = mysql_list_dbs($this->_connectionID);\r
-               $arr = array();\r
-               $i = 0;\r
-               $max = mysql_num_rows($qid);\r
-               while ($i < $max) {\r
-                       $db = mysql_tablename($qid,$i);\r
-                       if ($db != 'mysql') $arr[] = $db;\r
-                       $i += 1;\r
-               }\r
-               return $arr;\r
-       }\r
-       \r
-               \r
-       // Format date column in sql string given an input format that understands Y M D\r
-       function SQLDate($fmt, $col=false)\r
-       {       \r
-               if (!$col) $col = $this->sysTimeStamp;\r
-               $s = 'DATE_FORMAT('.$col.",'";\r
-               $concat = false;\r
-               $len = strlen($fmt);\r
-               for ($i=0; $i < $len; $i++) {\r
-                       $ch = $fmt[$i];\r
-                       switch($ch) {\r
-                       case 'Y':\r
-                       case 'y':\r
-                               $s .= '%Y';\r
-                               break;\r
-                       case 'Q':\r
-                       case 'q':\r
-                               $s .= "'),Quarter($col)";\r
-                               \r
-                               if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";\r
-                               else $s .= ",('";\r
-                               $concat = true;\r
-                               break;\r
-                       case 'M':\r
-                               $s .= '%b';\r
-                               break;\r
-                               \r
-                       case 'm':\r
-                               $s .= '%m';\r
-                               break;\r
-                       case 'D':\r
-                       case 'd':\r
-                               $s .= '%d';\r
-                               break;\r
-                       \r
-                       case 'H': \r
-                               $s .= '%H';\r
-                               break;\r
-                               \r
-                       case 'h':\r
-                               $s .= '%I';\r
-                               break;\r
-                               \r
-                       case 'i':\r
-                               $s .= '%i';\r
-                               break;\r
-                               \r
-                       case 's':\r
-                               $s .= '%s';\r
-                               break;\r
-                               \r
-                       case 'a':\r
-                       case 'A':\r
-                               $s .= '%p';\r
-                               break;\r
-                               \r
-                       default:\r
-                               \r
-                               if ($ch == '\\') {\r
-                                       $i++;\r
-                                       $ch = substr($fmt,$i,1);\r
-                               }\r
-                               $s .= $ch;\r
-                               break;\r
-                       }\r
-               }\r
-               $s.="')";\r
-               if ($concat) $s = "CONCAT($s)";\r
-               return $s;\r
-       }\r
-       \r
-\r
-       // returns concatenated string\r
-       // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator\r
-       function Concat()\r
-       {\r
-               $s = "";\r
-               $arr = func_get_args();\r
-               \r
-               // suggestion by andrew005@mnogo.ru\r
-               $s = implode(',',$arr); \r
-               if (strlen($s) > 0) return "CONCAT($s)";\r
-               else return '';\r
-       }\r
-       \r
-       function OffsetDate($dayFraction,$date=false)\r
-       {               \r
-               if (!$date) $date = $this->sysDate;\r
-               return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";\r
-       }\r
-       \r
-       // returns true or false\r
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (ADODB_PHPVER >= 0x4300)\r
-                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,\r
-                                                                                               $this->forceNewConnect,$this->clientFlags);\r
-               else if (ADODB_PHPVER >= 0x4200)\r
-                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,\r
-                                                                                               $this->forceNewConnect);\r
-               else\r
-                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword);\r
-       \r
-               if ($this->_connectionID === false) return false;\r
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-               return true;    \r
-       }\r
-       \r
-       // returns true or false\r
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (ADODB_PHPVER >= 0x4300)\r
-                       $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);\r
-               else\r
-                       $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword);\r
-               if ($this->_connectionID === false) return false;\r
-               if ($this->autoRollback) $this->RollbackTrans();\r
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-               return true;    \r
-       }\r
-       \r
-       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               $this->forceNewConnect = true;\r
-               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);\r
-       }\r
-       \r
-       function &MetaColumns($table) \r
-       {\r
-       \r
-               if ($this->metaColumnsSQL) {\r
-               global $ADODB_FETCH_MODE;\r
-               \r
-                       $save = $ADODB_FETCH_MODE;\r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
-                       \r
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));\r
-                       \r
-                       if (isset($savem)) $this->SetFetchMode($savem);\r
-                       $ADODB_FETCH_MODE = $save;\r
-                       \r
-                       if ($rs === false) return false;\r
-                       \r
-                       $retarr = array();\r
-                       while (!$rs->EOF){\r
-                               $fld = new ADOFieldObject();\r
-                               $fld->name = $rs->fields[0];\r
-                               $type = $rs->fields[1];\r
-                               \r
-                               \r
-                               // split type into type(length):\r
-                               $fld->scale = null;\r
-                               if (strpos($type,',') && preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {\r
-                                       $fld->type = $query_array[1];\r
-                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;\r
-                                       $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;\r
-                               } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {\r
-                                       $fld->type = $query_array[1];\r
-                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;\r
-                               } else {\r
-                                       $fld->max_length = -1;\r
-                                       $fld->type = $type;\r
-                               }\r
-                               /*\r
-                               // split type into type(length):\r
-                               if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {\r
-                                       $fld->type = $query_array[1];\r
-                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;\r
-                               } else {\r
-                                       $fld->max_length = -1;\r
-                                       $fld->type = $type;\r
-                               }*/\r
-                               $fld->not_null = ($rs->fields[2] != 'YES');\r
-                               $fld->primary_key = ($rs->fields[3] == 'PRI');\r
-                               $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);\r
-                               $fld->binary = (strpos($fld->type,'blob') !== false);\r
-                               \r
-                               if (!$fld->binary) {\r
-                                       $d = $rs->fields[4];\r
-                                       if ($d != "" && $d != "NULL") {\r
-                                               $fld->has_default = true;\r
-                                               $fld->default_value = $d;\r
-                                       } else {\r
-                                               $fld->has_default = false;\r
-                                       }\r
-                               }\r
-                               if ($save == ADODB_FETCH_NUM) $retarr[] = $fld; \r
-                               else $retarr[strtoupper($fld->name)] = $fld;\r
-                               $rs->MoveNext();\r
-                       }\r
-                       $rs->Close();\r
-                       return $retarr; \r
-               }\r
-               return false;\r
-       }\r
-               \r
-       // returns true or false\r
-       function SelectDB($dbName) \r
-       {\r
-               $this->databaseName = $dbName;\r
-               if ($this->_connectionID) {\r
-                       return @mysql_select_db($dbName,$this->_connectionID);          \r
-               }\r
-               else return false;      \r
-       }\r
-       \r
-       // parameters use PostgreSQL convention, not MySQL\r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)\r
-       {\r
-               $offsetStr =($offset>=0) ? "$offset," : '';\r
-               \r
-               if ($secs)\r
-                       $rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr);\r
-               else\r
-                       $rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr);\r
-               return $rs;\r
-       }\r
-       \r
-       \r
-       // returns queryID or false\r
-       function _query($sql,$inputarr)\r
-       {\r
-       //global $ADODB_COUNTRECS;\r
-               //if($ADODB_COUNTRECS) \r
-               return mysql_query($sql,$this->_connectionID);\r
-               //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6\r
-       }\r
-\r
-       /*      Returns: the last error message from previous database operation        */      \r
-       function ErrorMsg() \r
-       {\r
-       \r
-               if ($this->_logsql) return $this->_errorMsg;\r
-               if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();\r
-               else $this->_errorMsg = @mysql_error($this->_connectionID);\r
-               return $this->_errorMsg;\r
-       }\r
-       \r
-       /*      Returns: the last error number from previous database operation */      \r
-       function ErrorNo() \r
-       {\r
-               if ($this->_logsql) return $this->_errorCode;\r
-               if (empty($this->_connectionID))  return @mysql_errno();\r
-               else return @mysql_errno($this->_connectionID);\r
-       }\r
-       \r
-\r
-       \r
-       // returns true or false\r
-       function _close()\r
-       {\r
-               @mysql_close($this->_connectionID);\r
-               $this->_connectionID = false;\r
-       }\r
-\r
-       \r
-       /*\r
-       * Maximum size of C field\r
-       */\r
-       function CharMax()\r
-       {\r
-               return 255; \r
-       }\r
-       \r
-       /*\r
-       * Maximum size of X field\r
-       */\r
-       function TextMax()\r
-       {\r
-               return 4294967295; \r
-       }\r
-       \r
-}\r
-       \r
-/*--------------------------------------------------------------------------------------\r
-        Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordSet_mysql extends ADORecordSet{ \r
-       \r
-       var $databaseType = "mysql";\r
-       var $canSeek = true;\r
-       \r
-       function ADORecordSet_mysql($queryID,$mode=false) \r
-       {\r
-               if ($mode === false) { \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               switch ($mode)\r
-               {\r
-               case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;\r
-               case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;\r
-               default:\r
-               case ADODB_FETCH_DEFAULT:\r
-               case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;\r
-               }\r
-       \r
-               $this->ADORecordSet($queryID);  \r
-       }\r
-       \r
-       function _initrs()\r
-       {\r
-       //GLOBAL $ADODB_COUNTRECS;\r
-       //      $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;\r
-               $this->_numOfRows = @mysql_num_rows($this->_queryID);\r
-               $this->_numOfFields = @mysql_num_fields($this->_queryID);\r
-       }\r
-       \r
-       function &FetchField($fieldOffset = -1) \r
-       {       \r
-       \r
-               if ($fieldOffset != -1) {\r
-                       $o = @mysql_fetch_field($this->_queryID, $fieldOffset);\r
-                       $f = @mysql_field_flags($this->_queryID,$fieldOffset);\r
-                       $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com)\r
-                       //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable\r
-                       $o->binary = (strpos($f,'binary')!== false);\r
-               }\r
-               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
-                       $o = @mysql_fetch_field($this->_queryID);\r
-                       $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com)\r
-                       //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable\r
-               }\r
-                       \r
-               return $o;\r
-       }\r
-\r
-       function &GetRowAssoc($upper=true)\r
-       {\r
-               if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields;\r
-               $row =& ADORecordSet::GetRowAssoc($upper);\r
-               return $row;\r
-       }\r
-       \r
-       /* Use associative array to get fields array */\r
-       function Fields($colname)\r
-       {       \r
-               // added @ by "Michael William Miller" <mille562@pilot.msu.edu>\r
-               if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname];\r
-               \r
-               if (!$this->bind) {\r
-                       $this->bind = array();\r
-                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                               $o = $this->FetchField($i);\r
-                               $this->bind[strtoupper($o->name)] = $i;\r
-                       }\r
-               }\r
-                return $this->fields[$this->bind[strtoupper($colname)]];\r
-       }\r
-       \r
-       function _seek($row)\r
-       {\r
-               if ($this->_numOfRows == 0) return false;\r
-               return @mysql_data_seek($this->_queryID,$row);\r
-       }\r
-       \r
-       \r
-       // 10% speedup to move MoveNext to child class\r
-       function MoveNext() \r
-       {\r
-       //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this);\r
-       \r
-               if ($this->EOF) return false;\r
-                               \r
-               $this->_currentRow++;\r
-               $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);\r
-               if (is_array($this->fields)) return true;\r
-               \r
-               $this->EOF = true;\r
-               \r
-               /* -- tested raising an error -- appears pointless\r
-               $conn = $this->connection;\r
-               if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {\r
-                       $fn = $conn->raiseErrorFn;\r
-                       $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);\r
-               }\r
-               */\r
-               return false;\r
-       }       \r
-       \r
-       function _fetch()\r
-       {\r
-               $this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);\r
-               return is_array($this->fields);\r
-       }\r
-       \r
-       function _close() {\r
-               @mysql_free_result($this->_queryID);    \r
-               $this->_queryID = false;        \r
-       }\r
-       \r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               \r
-               $len = -1; // mysql max_length is not accurate\r
-               switch (strtoupper($t)) {\r
-               case 'STRING': \r
-               case 'CHAR':\r
-               case 'VARCHAR': \r
-               case 'TINYBLOB': \r
-               case 'TINYTEXT': \r
-               case 'ENUM': \r
-               case 'SET': \r
-                       if ($len <= $this->blobSize) return 'C';\r
-                       \r
-               case 'TEXT':\r
-               case 'LONGTEXT': \r
-               case 'MEDIUMTEXT':\r
-                       return 'X';\r
-                       \r
-               // php_mysql extension always returns 'blob' even if 'text'\r
-               // so we have to check whether binary...\r
-               case 'IMAGE':\r
-               case 'LONGBLOB': \r
-               case 'BLOB':\r
-               case 'MEDIUMBLOB':\r
-                       return !empty($fieldobj->binary) ? 'B' : 'X';\r
-                       \r
-               case 'YEAR':\r
-               case 'DATE': return 'D';\r
-               \r
-               case 'TIME':\r
-               case 'DATETIME':\r
-               case 'TIMESTAMP': return 'T';\r
-               \r
-               case 'INT': \r
-               case 'INTEGER':\r
-               case 'BIGINT':\r
-               case 'TINYINT':\r
-               case 'MEDIUMINT':\r
-               case 'SMALLINT': \r
-                       \r
-                       if (!empty($fieldobj->primary_key)) return 'R';\r
-                       else return 'I';\r
-               \r
-               default: return 'N';\r
-               }\r
-       }\r
-\r
-}\r
-}\r
+<?php
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+  
+  MySQL code that does not support transactions. Use mysqlt if you need transactions.
+  Requires mysql client. Works on Windows and Unix.
+  
+ 28 Feb 2001: MetaColumns bug fix - suggested by  Freek Dijkstra (phpeverywhere@macfreek.com)
+*/ 
+
+if (! defined("_ADODB_MYSQL_LAYER")) {
+ define("_ADODB_MYSQL_LAYER", 1 );
+
+class ADODB_mysql extends ADOConnection {
+       var $databaseType = 'mysql';
+       var $dataProvider = 'mysql';
+       var $hasInsertID = true;
+       var $hasAffectedRows = true;    
+       var $metaTablesSQL = "SHOW TABLES";     
+       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";
+       var $hasLimit = true;
+       var $hasMoveFirst = true;
+       var $hasGenID = true;
+       var $upperCase = 'upper';
+       var $isoDates = true; // accepts dates in ISO format
+       var $sysDate = 'CURDATE()';
+       var $sysTimeStamp = 'NOW()';
+       var $hasTransactions = false;
+       var $forceNewConnect = false;
+       var $poorAffectedRows = true;
+       var $clientFlags = 0;
+       var $substr = "substring";
+       var $nameQuote = '`';           /// string to use to quote identifiers and names
+       
+       function ADODB_mysql() 
+       {                       
+       }
+       
+       function ServerInfo()
+       {
+               $arr['description'] = ADOConnection::GetOne("select version()");
+               $arr['version'] = ADOConnection::_findvers($arr['description']);
+               return $arr;
+       }
+       
+       function IfNull( $field, $ifNull ) 
+       {
+               return " IFNULL($field, $ifNull) "; // if MySQL
+       }
+       
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+       {       
+               if ($mask) {
+                       $save = $this->metaTablesSQL;
+                       $mask = $this->qstr($mask);
+                       $this->metaTablesSQL .= " like $mask";
+               }
+               $ret =& ADOConnection::MetaTables($ttype,$showSchema);
+               
+               if ($mask) {
+                       $this->metaTablesSQL = $save;
+               }
+               return $ret;
+       }
+       
+       
+       function &MetaIndexes ($table, $primary = FALSE, $owner=false)
+       {
+        // save old fetch mode
+        global $ADODB_FETCH_MODE;
+        
+        $save = $ADODB_FETCH_MODE;
+        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+        if ($this->fetchMode !== FALSE) {
+               $savem = $this->SetFetchMode(FALSE);
+        }
+        
+        // get index details
+        $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
+        
+        // restore fetchmode
+        if (isset($savem)) {
+                $this->SetFetchMode($savem);
+        }
+        $ADODB_FETCH_MODE = $save;
+        
+        if (!is_object($rs)) {
+                return FALSE;
+        }
+        
+        $indexes = array ();
+        
+        // parse index data into array
+        while ($row = $rs->FetchRow()) {
+                if ($primary == FALSE AND $row[2] == 'PRIMARY') {
+                        continue;
+                }
+                
+                if (!isset($indexes[$row[2]])) {
+                        $indexes[$row[2]] = array(
+                                'unique' => ($row[1] == 0),
+                                'columns' => array()
+                        );
+                }
+                
+                $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
+        }
+        
+        // sort columns by order in the index
+        foreach ( array_keys ($indexes) as $index )
+        {
+                ksort ($indexes[$index]['columns']);
+        }
+        
+        return $indexes;
+       }
+
+       
+       // if magic quotes disabled, use mysql_real_escape_string()
+       function qstr($s,$magic_quotes=false)
+       {
+               if (!$magic_quotes) {
+               
+                       if (ADODB_PHPVER >= 0x4300) {
+                               if (is_resource($this->_connectionID))
+                                       return "'".mysql_real_escape_string($s,$this->_connectionID)."'";
+                       }
+                       if ($this->replaceQuote[0] == '\\'){
+                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
+                       }
+                       return  "'".str_replace("'",$this->replaceQuote,$s)."'"; 
+               }
+               
+               // undo magic quotes for "
+               $s = str_replace('\\"','"',$s);
+               return "'$s'";
+       }
+       
+       function _insertid()
+       {
+               return mysql_insert_id($this->_connectionID);
+       }
+       
+       function GetOne($sql,$inputarr=false)
+       {
+               $rs =& $this->SelectLimit($sql,1,-1,$inputarr);
+               if ($rs) {
+                       $rs->Close();
+                       if ($rs->EOF) return false;
+                       return reset($rs->fields);
+               }
+               
+               return false;
+       }
+       
+       function _affectedrows()
+       {
+                       return mysql_affected_rows($this->_connectionID);
+       }
+  
+       // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
+       // Reference on Last_Insert_ID on the recommended way to simulate sequences
+       var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
+       var $_genSeqSQL = "create table %s (id int not null)";
+       var $_genSeq2SQL = "insert into %s values (%s)";
+       var $_dropSeqSQL = "drop table %s";
+       
+       function CreateSequence($seqname='adodbseq',$startID=1)
+       {
+               if (empty($this->_genSeqSQL)) return false;
+               $u = strtoupper($seqname);
+               
+               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+               if (!$ok) return false;
+               return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
+       }
+       
+
+       function GenID($seqname='adodbseq',$startID=1)
+       {
+               // post-nuke sets hasGenID to false
+               if (!$this->hasGenID) return false;
+               
+               $savelog = $this->_logsql;
+               $this->_logsql = false;
+               $getnext = sprintf($this->_genIDSQL,$seqname);
+               $holdtransOK = $this->_transOK; // save the current status
+               $rs = @$this->Execute($getnext);
+               if (!$rs) {
+                       if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
+                       $u = strtoupper($seqname);
+                       $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+                       $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
+                       $rs = $this->Execute($getnext);
+               }
+               $this->genID = mysql_insert_id($this->_connectionID);
+               
+               if ($rs) $rs->Close();
+               
+               $this->_logsql = $savelog;
+               return $this->genID;
+       }
+       
+       function &MetaDatabases()
+       {
+               $qid = mysql_list_dbs($this->_connectionID);
+               $arr = array();
+               $i = 0;
+               $max = mysql_num_rows($qid);
+               while ($i < $max) {
+                       $db = mysql_tablename($qid,$i);
+                       if ($db != 'mysql') $arr[] = $db;
+                       $i += 1;
+               }
+               return $arr;
+       }
+       
+               
+       // Format date column in sql string given an input format that understands Y M D
+       function SQLDate($fmt, $col=false)
+       {       
+               if (!$col) $col = $this->sysTimeStamp;
+               $s = 'DATE_FORMAT('.$col.",'";
+               $concat = false;
+               $len = strlen($fmt);
+               for ($i=0; $i < $len; $i++) {
+                       $ch = $fmt[$i];
+                       switch($ch) {
+                       case 'Y':
+                       case 'y':
+                               $s .= '%Y';
+                               break;
+                       case 'Q':
+                       case 'q':
+                               $s .= "'),Quarter($col)";
+                               
+                               if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
+                               else $s .= ",('";
+                               $concat = true;
+                               break;
+                       case 'M':
+                               $s .= '%b';
+                               break;
+                               
+                       case 'm':
+                               $s .= '%m';
+                               break;
+                       case 'D':
+                       case 'd':
+                               $s .= '%d';
+                               break;
+                       
+                       case 'H': 
+                               $s .= '%H';
+                               break;
+                               
+                       case 'h':
+                               $s .= '%I';
+                               break;
+                               
+                       case 'i':
+                               $s .= '%i';
+                               break;
+                               
+                       case 's':
+                               $s .= '%s';
+                               break;
+                               
+                       case 'a':
+                       case 'A':
+                               $s .= '%p';
+                               break;
+                               
+                       default:
+                               
+                               if ($ch == '\\') {
+                                       $i++;
+                                       $ch = substr($fmt,$i,1);
+                               }
+                               $s .= $ch;
+                               break;
+                       }
+               }
+               $s.="')";
+               if ($concat) $s = "CONCAT($s)";
+               return $s;
+       }
+       
+
+       // returns concatenated string
+       // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
+       function Concat()
+       {
+               $s = "";
+               $arr = func_get_args();
+               
+               // suggestion by andrew005@mnogo.ru
+               $s = implode(',',$arr); 
+               if (strlen($s) > 0) return "CONCAT($s)";
+               else return '';
+       }
+       
+       function OffsetDate($dayFraction,$date=false)
+       {               
+               if (!$date) $date = $this->sysDate;
+               return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";
+       }
+       
+       // returns true or false
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (ADODB_PHPVER >= 0x4300)
+                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
+                                                                                               $this->forceNewConnect,$this->clientFlags);
+               else if (ADODB_PHPVER >= 0x4200)
+                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
+                                                                                               $this->forceNewConnect);
+               else
+                       $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword);
+       
+               if ($this->_connectionID === false) return false;
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);
+               return true;    
+       }
+       
+       // returns true or false
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (ADODB_PHPVER >= 0x4300)
+                       $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);
+               else
+                       $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword);
+               if ($this->_connectionID === false) return false;
+               if ($this->autoRollback) $this->RollbackTrans();
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);
+               return true;    
+       }
+       
+       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               $this->forceNewConnect = true;
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
+       }
+       
+       function &MetaColumns($table) 
+       {
+       
+               if ($this->metaColumnsSQL) {
+               global $ADODB_FETCH_MODE;
+               
+                       $save = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                       if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+                       
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
+                       
+                       if (isset($savem)) $this->SetFetchMode($savem);
+                       $ADODB_FETCH_MODE = $save;
+                       
+                       if ($rs === false) return false;
+                       
+                       $retarr = array();
+                       while (!$rs->EOF){
+                               $fld = new ADOFieldObject();
+                               $fld->name = $rs->fields[0];
+                               $type = $rs->fields[1];
+                               
+                               
+                               // split type into type(length):
+                               $fld->scale = null;
+                               if (strpos($type,',') && preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
+                                       $fld->type = $query_array[1];
+                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
+                                       $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
+                               } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
+                                       $fld->type = $query_array[1];
+                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
+                               } else {
+                                       $fld->max_length = -1;
+                                       $fld->type = $type;
+                               }
+                               /*
+                               // split type into type(length):
+                               if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
+                                       $fld->type = $query_array[1];
+                                       $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
+                               } else {
+                                       $fld->max_length = -1;
+                                       $fld->type = $type;
+                               }*/
+                               $fld->not_null = ($rs->fields[2] != 'YES');
+                               $fld->primary_key = ($rs->fields[3] == 'PRI');
+                               $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
+                               $fld->binary = (strpos($fld->type,'blob') !== false);
+                               
+                               if (!$fld->binary) {
+                                       $d = $rs->fields[4];
+                                       if ($d != "" && $d != "NULL") {
+                                               $fld->has_default = true;
+                                               $fld->default_value = $d;
+                                       } else {
+                                               $fld->has_default = false;
+                                       }
+                               }
+                               if ($save == ADODB_FETCH_NUM) $retarr[] = $fld; 
+                               else $retarr[strtoupper($fld->name)] = $fld;
+                               $rs->MoveNext();
+                       }
+                       $rs->Close();
+                       return $retarr; 
+               }
+               return false;
+       }
+               
+       // returns true or false
+       function SelectDB($dbName) 
+       {
+               $this->databaseName = $dbName;
+               if ($this->_connectionID) {
+                       return @mysql_select_db($dbName,$this->_connectionID);          
+               }
+               else return false;      
+       }
+       
+       // parameters use PostgreSQL convention, not MySQL
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
+       {
+               $offsetStr =($offset>=0) ? "$offset," : '';
+               
+               if ($secs)
+                       $rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr);
+               else
+                       $rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr);
+               return $rs;
+       }
+       
+       
+       // returns queryID or false
+       function _query($sql,$inputarr)
+       {
+       //global $ADODB_COUNTRECS;
+               //if($ADODB_COUNTRECS) 
+               return mysql_query($sql,$this->_connectionID);
+               //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6
+       }
+
+       /*      Returns: the last error message from previous database operation        */      
+       function ErrorMsg() 
+       {
+       
+               if ($this->_logsql) return $this->_errorMsg;
+               if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();
+               else $this->_errorMsg = @mysql_error($this->_connectionID);
+               return $this->_errorMsg;
+       }
+       
+       /*      Returns: the last error number from previous database operation */      
+       function ErrorNo() 
+       {
+               if ($this->_logsql) return $this->_errorCode;
+               if (empty($this->_connectionID))  return @mysql_errno();
+               else return @mysql_errno($this->_connectionID);
+       }
+       
+
+       
+       // returns true or false
+       function _close()
+       {
+               @mysql_close($this->_connectionID);
+               $this->_connectionID = false;
+       }
+
+       
+       /*
+       * Maximum size of C field
+       */
+       function CharMax()
+       {
+               return 255; 
+       }
+       
+       /*
+       * Maximum size of X field
+       */
+       function TextMax()
+       {
+               return 4294967295; 
+       }
+       
+}
+       
+/*--------------------------------------------------------------------------------------
+        Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_mysql extends ADORecordSet{ 
+       
+       var $databaseType = "mysql";
+       var $canSeek = true;
+       
+       function ADORecordSet_mysql($queryID,$mode=false) 
+       {
+               if ($mode === false) { 
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               switch ($mode)
+               {
+               case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
+               case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
+               default:
+               case ADODB_FETCH_DEFAULT:
+               case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break;
+               }
+       
+               $this->ADORecordSet($queryID);  
+       }
+       
+       function _initrs()
+       {
+       //GLOBAL $ADODB_COUNTRECS;
+       //      $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;
+               $this->_numOfRows = @mysql_num_rows($this->_queryID);
+               $this->_numOfFields = @mysql_num_fields($this->_queryID);
+       }
+       
+       function &FetchField($fieldOffset = -1) 
+       {       
+       
+               if ($fieldOffset != -1) {
+                       $o = @mysql_fetch_field($this->_queryID, $fieldOffset);
+                       $f = @mysql_field_flags($this->_queryID,$fieldOffset);
+                       $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com)
+                       //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
+                       $o->binary = (strpos($f,'binary')!== false);
+               }
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */
+                       $o = @mysql_fetch_field($this->_queryID);
+                       $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com)
+                       //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
+               }
+                       
+               return $o;
+       }
+
+       function &GetRowAssoc($upper=true)
+       {
+               if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields;
+               $row =& ADORecordSet::GetRowAssoc($upper);
+               return $row;
+       }
+       
+       /* Use associative array to get fields array */
+       function Fields($colname)
+       {       
+               // added @ by "Michael William Miller" <mille562@pilot.msu.edu>
+               if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname];
+               
+               if (!$this->bind) {
+                       $this->bind = array();
+                       for ($i=0; $i < $this->_numOfFields; $i++) {
+                               $o = $this->FetchField($i);
+                               $this->bind[strtoupper($o->name)] = $i;
+                       }
+               }
+                return $this->fields[$this->bind[strtoupper($colname)]];
+       }
+       
+       function _seek($row)
+       {
+               if ($this->_numOfRows == 0) return false;
+               return @mysql_data_seek($this->_queryID,$row);
+       }
+       
+       
+       // 10% speedup to move MoveNext to child class
+       function MoveNext() 
+       {
+       //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this);
+       
+               if ($this->EOF) return false;
+                               
+               $this->_currentRow++;
+               $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
+               if (is_array($this->fields)) return true;
+               
+               $this->EOF = true;
+               
+               /* -- tested raising an error -- appears pointless
+               $conn = $this->connection;
+               if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
+                       $fn = $conn->raiseErrorFn;
+                       $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
+               }
+               */
+               return false;
+       }       
+       
+       function _fetch()
+       {
+               $this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);
+               return is_array($this->fields);
+       }
+       
+       function _close() {
+               @mysql_free_result($this->_queryID);    
+               $this->_queryID = false;        
+       }
+       
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               
+               $len = -1; // mysql max_length is not accurate
+               switch (strtoupper($t)) {
+               case 'STRING': 
+               case 'CHAR':
+               case 'VARCHAR': 
+               case 'TINYBLOB': 
+               case 'TINYTEXT': 
+               case 'ENUM': 
+               case 'SET': 
+                       if ($len <= $this->blobSize) return 'C';
+                       
+               case 'TEXT':
+               case 'LONGTEXT': 
+               case 'MEDIUMTEXT':
+                       return 'X';
+                       
+               // php_mysql extension always returns 'blob' even if 'text'
+               // so we have to check whether binary...
+               case 'IMAGE':
+               case 'LONGBLOB': 
+               case 'BLOB':
+               case 'MEDIUMBLOB':
+                       return !empty($fieldobj->binary) ? 'B' : 'X';
+                       
+               case 'YEAR':
+               case 'DATE': return 'D';
+               
+               case 'TIME':
+               case 'DATETIME':
+               case 'TIMESTAMP': return 'T';
+               
+               case 'INT': 
+               case 'INTEGER':
+               case 'BIGINT':
+               case 'TINYINT':
+               case 'MEDIUMINT':
+               case 'SMALLINT': 
+                       
+                       if (!empty($fieldobj->primary_key)) return 'R';
+                       else return 'I';
+               
+               default: return 'N';
+               }
+       }
+
+}
+}
 ?>
\ No newline at end of file
index a9daa02e482659c46beaed17217efdafcc5947ee..28ecd5947933d3fc5fe10cace728da8a05868e85 100644 (file)
-<?php\r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 8.\r
-  \r
-  MySQL code that does not support transactions. Use mysqlt if you need transactions.\r
-  Requires mysql client. Works on Windows and Unix.\r
\r
-21 October 2003: MySQLi extension implementation by Arjen de Rijke (a.de.rijke@xs4all.nl)\r
-Based on adodb 3.40\r
-*/ \r
-if (! defined("_ADODB_MYSQL_LAYER")) {\r
- define("_ADODB_MYSQL_LAYER", 1 );\r
\r
-class ADODB_mysqli extends ADOConnection {\r
-       var $databaseType = 'mysqli';\r
-       var $dataProvider = 'native';\r
-       var $hasInsertID = true;\r
-       var $hasAffectedRows = true;    \r
-       var $metaTablesSQL = "SHOW TABLES";     \r
-       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";\r
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
-       var $hasLimit = true;\r
-       var $hasMoveFirst = true;\r
-       var $hasGenID = true;\r
-       var $upperCase = 'upper';\r
-       var $isoDates = true; // accepts dates in ISO format\r
-       var $sysDate = 'CURDATE()';\r
-       var $sysTimeStamp = 'NOW()';\r
-       var $hasTransactions = false;\r
-       var $forceNewConnect = false;\r
-       var $poorAffectedRows = true;\r
-       var $clientFlags = 0;\r
-       var $executeOnly = true;\r
-       var $substr = "substring";\r
-       var $nameQuote = '`';           /// string to use to quote identifiers and names\r
-       //var $_bindInputArray = true;\r
-       \r
-       function ADODB_mysqli() \r
-       {                       \r
-         if(!extension_loaded("mysqli"))\r
-           {\r
-             trigger_error("You must have the MySQLi extension.", E_USER_ERROR);\r
-           }\r
-       }\r
-       \r
-       function IfNull( $field, $ifNull ) \r
-       {\r
-               return " IFNULL($field, $ifNull) "; // if MySQL\r
-       }\r
-       \r
-       function ServerInfo()\r
-       {\r
-               $arr['description'] = $this->GetOne("select version()");\r
-               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
-               return $arr;\r
-       }\r
-       \r
-       \r
-       function BeginTrans()\r
-       {         \r
-               if ($this->transOff) return true;\r
-               $this->transCnt += 1;\r
-               $this->Execute('SET AUTOCOMMIT=0');\r
-               $this->Execute('BEGIN');\r
-               return true;\r
-       }\r
-       \r
-       function CommitTrans($ok=true) \r
-       {\r
-               if ($this->transOff) return true; \r
-               if (!$ok) return $this->RollbackTrans();\r
-               \r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $this->Execute('COMMIT');\r
-               $this->Execute('SET AUTOCOMMIT=1');\r
-               return true;\r
-       }\r
-       \r
-       function RollbackTrans()\r
-       {\r
-               if ($this->transOff) return true;\r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $this->Execute('ROLLBACK');\r
-               $this->Execute('SET AUTOCOMMIT=1');\r
-               return true;\r
-       }\r
-       \r
-       // if magic quotes disabled, use mysql_real_escape_string()\r
-       // From readme.htm:\r
-       // Quotes a string to be sent to the database. The $magic_quotes_enabled\r
-       // parameter may look funny, but the idea is if you are quoting a \r
-       // string extracted from a POST/GET variable, then \r
-       // pass get_magic_quotes_gpc() as the second parameter. This will \r
-       // ensure that the variable is not quoted twice, once by qstr and once \r
-       // by the magic_quotes_gpc.\r
-       //\r
-       //Eg. $s = $db->qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());\r
-       function qstr($s, $magic_quotes = false)\r
-       {\r
-         if (!$magic_quotes) {\r
-           if (ADODB_PHPVER >= 0x5000) {\r
-           //  $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);\r
-             return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'";\r
-           }\r
-           else\r
-             {\r
-               trigger_error("phpver < 5 not implemented", E_USER_ERROR);\r
-             }\r
-           \r
-           if ($this->replaceQuote[0] == '\\')\r
-             {\r
-               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);\r
-             }\r
-           return  "'".str_replace("'",$this->replaceQuote,$s)."'"; \r
-         }\r
-         // undo magic quotes for "\r
-         $s = str_replace('\\"','"',$s);\r
-         return "'$s'";\r
-       }\r
-       \r
-       function _insertid()\r
-       {\r
-//       $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);\r
-         $result = @mysqli_insert_id($this->_connectionID);\r
-         if ($result == -1){\r
-             if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : "  . $this->ErrorMsg());\r
-         }\r
-         return $result;\r
-       }\r
-       \r
-       // Only works for INSERT, UPDATE and DELETE query's\r
-       function _affectedrows()\r
-       {\r
-       //  $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);\r
-         $result =  @mysqli_affected_rows($this->_connectionID);\r
-         if ($result == -1) {\r
-             if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : "  . $this->ErrorMsg());\r
-         }\r
-         return $result;\r
-       }\r
-  \r
-       // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html\r
-       // Reference on Last_Insert_ID on the recommended way to simulate sequences\r
-       var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";\r
-       var $_genSeqSQL = "create table %s (id int not null)";\r
-       var $_genSeq2SQL = "insert into %s values (%s)";\r
-       var $_dropSeqSQL = "drop table %s";\r
-       \r
-       function CreateSequence($seqname='adodbseq',$startID=1)\r
-       {\r
-               if (empty($this->_genSeqSQL)) return false;\r
-               $u = strtoupper($seqname);\r
-               \r
-               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
-               if (!$ok) return false;\r
-               return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));\r
-       }\r
-       \r
-       function GenID($seqname='adodbseq',$startID=1)\r
-       {\r
-               // post-nuke sets hasGenID to false\r
-               if (!$this->hasGenID) return false;\r
-               \r
-               $getnext = sprintf($this->_genIDSQL,$seqname);\r
-               $holdtransOK = $this->_transOK; // save the current status\r
-               $rs = @$this->Execute($getnext);\r
-               if (!$rs) {\r
-                       if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset\r
-                       $u = strtoupper($seqname);\r
-                       $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
-                       $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));\r
-                       $rs = $this->Execute($getnext);\r
-               }\r
-               $this->genID = mysqli_insert_id($this->_connectionID);\r
-               \r
-               if ($rs) $rs->Close();\r
-               \r
-               return $this->genID;\r
-       }\r
-       \r
-       function &MetaDatabases()\r
-         {\r
-           $query = "SHOW DATABASES";\r
-           $ret =& $this->Execute($query);\r
-               return $ret;\r
-         }\r
-\r
-         \r
-       function &MetaIndexes ($table, $primary = FALSE)\r
-       {\r
-               // save old fetch mode\r
-               global $ADODB_FETCH_MODE;\r
-               \r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               if ($this->fetchMode !== FALSE) {\r
-                      $savem = $this->SetFetchMode(FALSE);\r
-               }\r
-               \r
-               // get index details\r
-               $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table));\r
-               \r
-               // restore fetchmode\r
-               if (isset($savem)) {\r
-                       $this->SetFetchMode($savem);\r
-               }\r
-               $ADODB_FETCH_MODE = $save;\r
-               \r
-               if (!is_object($rs)) {\r
-                       return FALSE;\r
-               }\r
-               \r
-               $indexes = array ();\r
-               \r
-               // parse index data into array\r
-               while ($row = $rs->FetchRow()) {\r
-                       if ($primary == FALSE AND $row[2] == 'PRIMARY') {\r
-                               continue;\r
-                       }\r
-                       \r
-                       if (!isset($indexes[$row[2]])) {\r
-                               $indexes[$row[2]] = array(\r
-                                       'unique' => ($row[1] == 0),\r
-                                       'columns' => array()\r
-                               );\r
-                       }\r
-                       \r
-                       $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];\r
-               }\r
-               \r
-               // sort columns by order in the index\r
-               foreach ( array_keys ($indexes) as $index )\r
-               {\r
-                       ksort ($indexes[$index]['columns']);\r
-               }\r
-               \r
-               return $indexes;\r
-       }\r
-\r
-       \r
-       // Format date column in sql string given an input format that understands Y M D\r
-       function SQLDate($fmt, $col=false)\r
-       {       \r
-               if (!$col) $col = $this->sysTimeStamp;\r
-               $s = 'DATE_FORMAT('.$col.",'";\r
-               $concat = false;\r
-               $len = strlen($fmt);\r
-               for ($i=0; $i < $len; $i++) {\r
-                       $ch = $fmt[$i];\r
-                       switch($ch) {\r
-                       case 'Y':\r
-                       case 'y':\r
-                               $s .= '%Y';\r
-                               break;\r
-                       case 'Q':\r
-                       case 'q':\r
-                               $s .= "'),Quarter($col)";\r
-                               \r
-                               if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";\r
-                               else $s .= ",('";\r
-                               $concat = true;\r
-                               break;\r
-                       case 'M':\r
-                               $s .= '%b';\r
-                               break;\r
-                               \r
-                       case 'm':\r
-                               $s .= '%m';\r
-                               break;\r
-                       case 'D':\r
-                       case 'd':\r
-                               $s .= '%d';\r
-                               break;\r
-                       \r
-                       case 'H': \r
-                               $s .= '%H';\r
-                               break;\r
-                               \r
-                       case 'h':\r
-                               $s .= '%I';\r
-                               break;\r
-                               \r
-                       case 'i':\r
-                               $s .= '%i';\r
-                               break;\r
-                               \r
-                       case 's':\r
-                               $s .= '%s';\r
-                               break;\r
-                               \r
-                       case 'a':\r
-                       case 'A':\r
-                               $s .= '%p';\r
-                               break;\r
-                               \r
-                       default:\r
-                               \r
-                               if ($ch == '\\') {\r
-                                       $i++;\r
-                                       $ch = substr($fmt,$i,1);\r
-                               }\r
-                               $s .= $ch;\r
-                               break;\r
-                       }\r
-               }\r
-               $s.="')";\r
-               if ($concat) $s = "CONCAT($s)";\r
-               return $s;\r
-       }\r
-       \r
-       // returns concatenated string\r
-       // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator\r
-       function Concat()\r
-       {\r
-               $s = "";\r
-               $arr = func_get_args();\r
-               \r
-               // suggestion by andrew005@mnogo.ru\r
-               $s = implode(',',$arr); \r
-               if (strlen($s) > 0) return "CONCAT($s)";\r
-               else return '';\r
-       }\r
-       \r
-       // dayFraction is a day in floating point\r
-       function OffsetDate($dayFraction,$date=false)\r
-       {               \r
-               if (!$date) \r
-                 $date = $this->sysDate;\r
-               return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";\r
-       }\r
-       \r
-       // returns true or false\r
-       // To add: parameter int $port,\r
-       //         parameter string $socket\r
-       function _connect($argHostname = NULL, \r
-                         $argUsername = NULL, \r
-                         $argPassword = NULL, \r
-                         $argDatabasename = NULL)\r
-         {\r
-           // @ means: error surpression on\r
-           $this->_connectionID = @mysqli_init();\r
-           \r
-           if (is_null($this->_connectionID))\r
-           {\r
-             // mysqli_init only fails if insufficient memory\r
-             if ($this->debug) \r
-               ADOConnection::outp("mysqli_init() failed : "  . $this->ErrorMsg());\r
-             return false;\r
-           }\r
-           // Set connection options\r
-           // Not implemented now\r
-           // mysqli_options($this->_connection,,);\r
-           if (mysqli_real_connect($this->_connectionID,\r
-                                   $argHostname,\r
-                                   $argUsername,\r
-                                   $argPassword,\r
-                                   $argDatabasename))\r
-             {\r
-               if ($argDatabasename) \r
-                 {\r
-                   return $this->SelectDB($argDatabasename);\r
-                 }\r
-               \r
-               return true;\r
-             }\r
-           else\r
-             {\r
-               if ($this->debug) \r
-                 ADOConnection::outp("Could't connect : "  . $this->ErrorMsg());\r
-               return false;\r
-             }\r
-         }\r
-       \r
-       // returns true or false\r
-       // How to force a persistent connection\r
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-         {\r
-           // not implemented in mysqli (yet)?\r
-           $this->_connectionID = mysqli_connect($argHostname,\r
-                                                 $argUsername,\r
-                                                 $argPassword,\r
-                                                 $argDatabasename);\r
-           if ($this->_connectionID === false) return false;\r
-           //      if ($this->autoRollback) $this->RollbackTrans();\r
-           if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-           return true;        \r
-         }\r
-       \r
-       // When is this used? Close old connection first?\r
-       // In _connect(), check $this->forceNewConnect? \r
-       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-         {\r
-           $this->forceNewConnect = true;\r
-           $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);\r
-         }\r
-       \r
-       function &MetaColumns($table) \r
-       {\r
-         if ($this->metaColumnsSQL) {\r
-           global $ADODB_FETCH_MODE;\r
-           $save = $ADODB_FETCH_MODE;\r
-           $rs = false;\r
-           switch($ADODB_FETCH_MODE)\r
-             {\r
-             case ADODB_FETCH_NUM:\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $rs = $this->Execute(sprintf($this->metaColumnsSQL,\r
-                                            $table));\r
-               \r
-               $ADODB_FETCH_MODE = $save;\r
-               if ($rs === false) break;\r
-               $retarr = array();\r
-               while (!$rs->EOF){\r
-                 $fld = new ADOFieldObject();\r
-                 $fld->name = $rs->fields[0];\r
-                 $fld->type = $rs->fields[1];\r
-                 // split type into type(length):\r
-                 if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array))\r
-                   {\r
-                     $fld->type = $query_array[1];\r
-                     $fld->max_length = $query_array[2];\r
-                   }\r
-                 else\r
-                   {\r
-                     $fld->max_length = -1;\r
-                   }\r
-                 $fld->not_null = ($rs->fields[2] != 'YES');\r
-                 $fld->primary_key = ($rs->fields[3] == 'PRI');\r
-                 $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);\r
-                 $fld->binary = (strpos($fld->type,'blob') !== false);\r
-                 if (!$fld->binary) \r
-                   {\r
-                     $d = $rs->fields[4];\r
-                     $d = $rs->fields['Default'];\r
-                     if ($d != "" && $d != "NULL")\r
-                       {\r
-                         $fld->has_default = true;\r
-                         $fld->default_value = $d;\r
-                       } \r
-                     else \r
-                       {\r
-                         $fld->has_default = false;\r
-                       }\r
-                   }\r
-                 $retarr[strtoupper($fld->name)] = $fld;       \r
-                 $rs->MoveNext();\r
-               }\r
-               break;\r
-             case ADODB_FETCH_ASSOC:\r
-             case ADODB_FETCH_DEFAULT:\r
-             case ADODB_FETCH_BOTH:\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-               $rs = $this->Execute(sprintf($this->metaColumnsSQL,\r
-                                            $table));\r
-               $ADODB_FETCH_MODE = $save;\r
-               if ($rs === false) break;\r
-               $retarr = array();\r
-               while (!$rs->EOF){\r
-                 $fld = new ADOFieldObject();\r
-                 $fld->name = $rs->fields['Field'];\r
-                 $fld->type = $rs->fields['Type'];\r
-                               \r
-                 // split type into type(length):\r
-                 if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array))\r
-                   {\r
-                     $fld->type = $query_array[1];\r
-                     $fld->max_length = $query_array[2];\r
-                   }\r
-                 else\r
-                   {\r
-                     $fld->max_length = -1;\r
-                   }\r
-                 $fld->not_null = ($rs->fields['Null'] != 'YES');\r
-                 $fld->primary_key = ($rs->fields['Key'] == 'PRI');\r
-                 $fld->auto_increment = (strpos($rs->fields['Extra'], 'auto_increment') !== false);\r
-                 $fld->binary = (strpos($fld->type,'blob') !== false);\r
-                 if (!$fld->binary) \r
-                   {\r
-                     $d = $rs->fields['Default'];\r
-                     if ($d != "" && $d != "NULL")\r
-                       {\r
-                         $fld->has_default = true;\r
-                         $fld->default_value = $d;\r
-                       } \r
-                     else \r
-                       {\r
-                         $fld->has_default = false;\r
-                       }\r
-                   }\r
-                 $retarr[strtoupper($fld->name)] = $fld;       \r
-                 $rs->MoveNext();\r
-               }\r
-               break;\r
-             default:\r
-             }\r
-           \r
-           if ($rs === false) return false;\r
-           $rs->Close();\r
-           return $retarr;     \r
-         }\r
-         return false;\r
-       }\r
-               \r
-       // returns true or false\r
-       function SelectDB($dbName) \r
-       {\r
-//         $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);\r
-           $this->databaseName = $dbName;\r
-           if ($this->_connectionID) {\r
-               $result = @mysqli_select_db($this->_connectionID, $dbName);\r
-                       if (!$result) {\r
-                       ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg());\r
-                       }\r
-                       return $result;         \r
-               }\r
-           return false;       \r
-       }\r
-       \r
-       // parameters use PostgreSQL convention, not MySQL\r
-       function &SelectLimit($sql,\r
-                             $nrows = -1,\r
-                             $offset = -1,\r
-                             $inputarr = false, \r
-                             $arg3 = false,\r
-                             $secs = 0)\r
-       {\r
-               $offsetStr = ($offset >= 0) ? "$offset," : '';\r
-               \r
-               if ($secs)\r
-                       $rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);\r
-               else\r
-                       $rs =& $this->Execute($sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);\r
-                       \r
-               return $rs;\r
-       }\r
-       \r
-       \r
-       function Prepare($sql)\r
-       {\r
-               return $sql;\r
-               \r
-               $stmt = mysqli_prepare($this->_connectionID,$sql);\r
-               if (!$stmt) return false;\r
-               return array($sql,$stmt);\r
-       }\r
-       \r
-       \r
-       // returns queryID or false\r
-       function _query($sql, $inputarr)\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-       \r
-               if (is_array($sql)) {\r
-                       $stmt = $sql[1];\r
-                       foreach($inputarr as $k => $v) {\r
-                               if (is_string($v)) $a[] = MYSQLI_BIND_STRING;\r
-                               else if (is_integer($v)) $a[] = MYSQLI_BIND_INT; \r
-                               else $a[] = MYSQLI_BIND_DOUBLE;\r
-                               \r
-                               $fnarr =& array_merge( array($stmt,$a) , $inputarr);\r
-                               $ret = call_user_func_array('mysqli_bind_param',$fnarr);\r
-                       }\r
-                       $ret = mysqli_execute($stmt);\r
-                       return $ret;\r
-               }\r
-               if (!$mysql_res =  mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) {\r
-                   if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());\r
-                   return false;\r
-               }\r
-               \r
-               return $mysql_res;\r
-       }\r
-\r
-       /*      Returns: the last error message from previous database operation        */      \r
-       function ErrorMsg() \r
-         {\r
-           if (empty($this->_connectionID)) \r
-             $this->_errorMsg = @mysqli_error();\r
-           else \r
-             $this->_errorMsg = @mysqli_error($this->_connectionID);\r
-           return $this->_errorMsg;\r
-         }\r
-       \r
-       /*      Returns: the last error number from previous database operation */      \r
-       function ErrorNo() \r
-         {\r
-           if (empty($this->_connectionID))  \r
-             return @mysqli_errno();\r
-           else \r
-             return @mysqli_errno($this->_connectionID);\r
-         }\r
-       \r
-       // returns true or false\r
-       function _close()\r
-         {\r
-           @mysqli_close($this->_connectionID);\r
-           $this->_connectionID = false;\r
-         }\r
-\r
-       /*\r
-       * Maximum size of C field\r
-       */\r
-       function CharMax()\r
-       {\r
-               return 255; \r
-       }\r
-       \r
-       /*\r
-       * Maximum size of X field\r
-       */\r
-       function TextMax()\r
-       {\r
-         return 4294967295; \r
-       }\r
-\r
-\r
-}\r
\r
-/*--------------------------------------------------------------------------------------\r
-        Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordSet_mysqli extends ADORecordSet{        \r
-       \r
-       var $databaseType = "mysqli";\r
-       var $canSeek = true;\r
-       \r
-       function ADORecordSet_mysqli($queryID, $mode = false) \r
-       {\r
-         if ($mode === false) \r
-           { \r
-             global $ADODB_FETCH_MODE;\r
-             $mode = $ADODB_FETCH_MODE;\r
-           }\r
-         switch ($mode)\r
-           {\r
-           case ADODB_FETCH_NUM: \r
-             $this->fetchMode = MYSQLI_NUM; \r
-             break;\r
-           case ADODB_FETCH_ASSOC:\r
-             $this->fetchMode = MYSQLI_ASSOC; \r
-             break;\r
-           case ADODB_FETCH_DEFAULT:\r
-           case ADODB_FETCH_BOTH:\r
-           default:\r
-             $this->fetchMode = MYSQLI_ASSOC; \r
-             break;\r
-           }\r
-         $this->ADORecordSet($queryID);        \r
-       }\r
-       \r
-       function _initrs()\r
-       {\r
-           // mysqli_num_rows only return correct number, depens\r
-           // on the use of mysql_store_result and mysql_use_result\r
-           if (!$this->Connection->executeOnly) {\r
-                       $this->_numOfRows = @mysqli_num_rows($this->_queryID);\r
-                       $this->_numOfFields = @mysqli_num_fields($this->_queryID);\r
-           }\r
-           else {\r
-                       $this->_numOfRows = 0;\r
-                       $this->_numOfFields = 0;\r
-           }\r
-       }\r
-       \r
-       function &FetchField($fieldOffset = -1) \r
-       {       \r
-         $fieldnr = $fieldOffset;\r
-         if ($fieldOffset != -1) {\r
-           $fieldOffset = mysqi_field_seek($this->_queryID, $fieldnr);\r
-         }\r
-         $o = mysqli_fetch_field($this->_queryID);\r
-         return $o;\r
-       }\r
-\r
-       function &GetRowAssoc($upper = true)\r
-       {\r
-         if ($this->fetchMode == MYSQLI_ASSOC && !$upper) \r
-           return $this->fields;\r
-         $row =& ADORecordSet::GetRowAssoc($upper);\r
-         return $row;\r
-       }\r
-       \r
-       /* Use associative array to get fields array */\r
-       function Fields($colname)\r
-       {       \r
-         if ($this->fetchMode != MYSQLI_NUM) \r
-           return @$this->fields[$colname];\r
-               \r
-         if (!$this->bind) {\r
-           $this->bind = array();\r
-           for ($i = 0; $i < $this->_numOfFields; $i++) {\r
-             $o = $this->FetchField($i);\r
-             $this->bind[strtoupper($o->name)] = $i;\r
-           }\r
-         }\r
-         return $this->fields[$this->bind[strtoupper($colname)]];\r
-       }\r
-       \r
-       function _seek($row)\r
-       {\r
-         if ($this->_numOfRows == 0) \r
-           return false;\r
-\r
-         if ($row < 0)\r
-           return false;\r
-\r
-         mysqli_data_seek($this->_queryID, $row);\r
-         $this->EOF = false;\r
-         return true;\r
-       }\r
-               \r
-       // 10% speedup to move MoveNext to child class\r
-       // This is the only implementation that works now (23-10-2003).\r
-       // Other functions return no or the wrong results.\r
-       function MoveNext() \r
-       {\r
-         if ($this->EOF) \r
-           return false;\r
-         $this->_currentRow++;\r
-         switch($this->fetchMode)\r
-           {\r
-           case MYSQLI_NUM:\r
-             $this->fields = mysqli_fetch_array($this->_queryID);\r
-             break;\r
-           case MYSQLI_ASSOC:\r
-           case MYSQLI_BOTH:\r
-             $this->fields = mysqli_fetch_assoc($this->_queryID);\r
-             break;\r
-           default:\r
-           }\r
-         if (is_array($this->fields)) \r
-           return true;\r
-         $this->EOF = true;\r
-         return false;\r
-       }       \r
-       \r
-       function _fetch()\r
-       {\r
-         // mysqli_fetch_array($this->_queryID, MYSQLI_NUM) does not\r
-         // work (22-10-2003). But mysqli_fetch_array($this->_queryID) gives\r
-         // int resulttype should default to MYSQLI_BOTH,but give MYSQLI_NUM.\r
-\r
-         //      $this->fields =  mysqli_fetch_fields($this->_queryID);\r
-         //      $this->fields =  mysqli_fetch_array($this->_queryID); //, $this->fetchMode);\r
-                 \r
-         $this->fields =  mysqli_fetch_assoc($this->_queryID); // $this->fetchMode);\r
-         return is_array($this->fields);\r
-       }\r
-       \r
-       function _close() \r
-       {\r
-         mysqli_free_result($this->_queryID); \r
-         $this->_queryID = false;      \r
-       }\r
-       \r
-       function MetaType($t, $len = -1, $fieldobj = false)\r
-       {\r
-         if (is_object($t)) \r
-           {\r
-             $fieldobj = $t;\r
-             $t = $fieldobj->type;\r
-             $len = $fieldobj->max_length;\r
-           }\r
-               \r
-         $len = -1; // mysql max_length is not accurate\r
-         switch (strtoupper($t)) {\r
-         case 'STRING': \r
-         case 'CHAR':\r
-         case 'VARCHAR': \r
-         case 'TINYBLOB': \r
-         case 'TINYTEXT': \r
-         case 'ENUM': \r
-         case 'SET': \r
-           if ($len <= $this->blobSize) return 'C';\r
-           \r
-         case 'TEXT':\r
-         case 'LONGTEXT': \r
-         case 'MEDIUMTEXT':\r
-           return 'X';\r
-                       \r
-           // php_mysql extension always returns 'blob' even if 'text'\r
-           // so we have to check whether binary...\r
-         case 'IMAGE':\r
-         case 'LONGBLOB': \r
-         case 'BLOB':\r
-         case 'MEDIUMBLOB':\r
-           return !empty($fieldobj->binary) ? 'B' : 'X';\r
-         case 'YEAR':\r
-         case 'DATE': \r
-           return 'D';\r
-               \r
-         case 'TIME':\r
-         case 'DATETIME':\r
-         case 'TIMESTAMP': return 'T';\r
-               \r
-         case 'INT': \r
-         case 'INTEGER':\r
-         case 'BIGINT':\r
-         case 'TINYINT':\r
-         case 'MEDIUMINT':\r
-         case 'SMALLINT': \r
-                       \r
-           if (!empty($fieldobj->primary_key)) return 'R';\r
-           else return 'I';\r
-           // Added floating-point types\r
-           // Maybe not necessery.\r
-         case 'FLOAT':\r
-         case 'DOUBLE':\r
-           //          case 'DOUBLE PRECISION':\r
-         case 'DECIMAL':\r
-         case 'DEC':\r
-         case 'FIXED':\r
-         default: \r
-           return 'N';\r
-         }\r
-       }\r
-       \r
-\r
-}\r
\r
-}\r
-\r
+<?php
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+  
+  MySQL code that does not support transactions. Use mysqlt if you need transactions.
+  Requires mysql client. Works on Windows and Unix.
+21 October 2003: MySQLi extension implementation by Arjen de Rijke (a.de.rijke@xs4all.nl)
+Based on adodb 3.40
+*/ 
+if (! defined("_ADODB_MYSQL_LAYER")) {
+ define("_ADODB_MYSQL_LAYER", 1 );
+class ADODB_mysqli extends ADOConnection {
+       var $databaseType = 'mysqli';
+       var $dataProvider = 'native';
+       var $hasInsertID = true;
+       var $hasAffectedRows = true;    
+       var $metaTablesSQL = "SHOW TABLES";     
+       var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";
+       var $hasLimit = true;
+       var $hasMoveFirst = true;
+       var $hasGenID = true;
+       var $upperCase = 'upper';
+       var $isoDates = true; // accepts dates in ISO format
+       var $sysDate = 'CURDATE()';
+       var $sysTimeStamp = 'NOW()';
+       var $hasTransactions = false;
+       var $forceNewConnect = false;
+       var $poorAffectedRows = true;
+       var $clientFlags = 0;
+       var $executeOnly = true;
+       var $substr = "substring";
+       var $nameQuote = '`';           /// string to use to quote identifiers and names
+       //var $_bindInputArray = true;
+       
+       function ADODB_mysqli() 
+       {                       
+         if(!extension_loaded("mysqli"))
+           {
+             trigger_error("You must have the MySQLi extension.", E_USER_ERROR);
+           }
+       }
+       
+       function IfNull( $field, $ifNull ) 
+       {
+               return " IFNULL($field, $ifNull) "; // if MySQL
+       }
+       
+       function ServerInfo()
+       {
+               $arr['description'] = $this->GetOne("select version()");
+               $arr['version'] = ADOConnection::_findvers($arr['description']);
+               return $arr;
+       }
+       
+       
+       function BeginTrans()
+       {         
+               if ($this->transOff) return true;
+               $this->transCnt += 1;
+               $this->Execute('SET AUTOCOMMIT=0');
+               $this->Execute('BEGIN');
+               return true;
+       }
+       
+       function CommitTrans($ok=true) 
+       {
+               if ($this->transOff) return true; 
+               if (!$ok) return $this->RollbackTrans();
+               
+               if ($this->transCnt) $this->transCnt -= 1;
+               $this->Execute('COMMIT');
+               $this->Execute('SET AUTOCOMMIT=1');
+               return true;
+       }
+       
+       function RollbackTrans()
+       {
+               if ($this->transOff) return true;
+               if ($this->transCnt) $this->transCnt -= 1;
+               $this->Execute('ROLLBACK');
+               $this->Execute('SET AUTOCOMMIT=1');
+               return true;
+       }
+       
+       // if magic quotes disabled, use mysql_real_escape_string()
+       // From readme.htm:
+       // Quotes a string to be sent to the database. The $magic_quotes_enabled
+       // parameter may look funny, but the idea is if you are quoting a 
+       // string extracted from a POST/GET variable, then 
+       // pass get_magic_quotes_gpc() as the second parameter. This will 
+       // ensure that the variable is not quoted twice, once by qstr and once 
+       // by the magic_quotes_gpc.
+       //
+       //Eg. $s = $db->qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());
+       function qstr($s, $magic_quotes = false)
+       {
+         if (!$magic_quotes) {
+           if (ADODB_PHPVER >= 0x5000) {
+           //  $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
+             return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'";
+           }
+           else
+             {
+               trigger_error("phpver < 5 not implemented", E_USER_ERROR);
+             }
+           
+           if ($this->replaceQuote[0] == '\\')
+             {
+               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
+             }
+           return  "'".str_replace("'",$this->replaceQuote,$s)."'"; 
+         }
+         // undo magic quotes for "
+         $s = str_replace('\\"','"',$s);
+         return "'$s'";
+       }
+       
+       function _insertid()
+       {
+//       $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
+         $result = @mysqli_insert_id($this->_connectionID);
+         if ($result == -1){
+             if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : "  . $this->ErrorMsg());
+         }
+         return $result;
+       }
+       
+       // Only works for INSERT, UPDATE and DELETE query's
+       function _affectedrows()
+       {
+       //  $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
+         $result =  @mysqli_affected_rows($this->_connectionID);
+         if ($result == -1) {
+             if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : "  . $this->ErrorMsg());
+         }
+         return $result;
+       }
+  
+       // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
+       // Reference on Last_Insert_ID on the recommended way to simulate sequences
+       var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
+       var $_genSeqSQL = "create table %s (id int not null)";
+       var $_genSeq2SQL = "insert into %s values (%s)";
+       var $_dropSeqSQL = "drop table %s";
+       
+       function CreateSequence($seqname='adodbseq',$startID=1)
+       {
+               if (empty($this->_genSeqSQL)) return false;
+               $u = strtoupper($seqname);
+               
+               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+               if (!$ok) return false;
+               return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
+       }
+       
+       function GenID($seqname='adodbseq',$startID=1)
+       {
+               // post-nuke sets hasGenID to false
+               if (!$this->hasGenID) return false;
+               
+               $getnext = sprintf($this->_genIDSQL,$seqname);
+               $holdtransOK = $this->_transOK; // save the current status
+               $rs = @$this->Execute($getnext);
+               if (!$rs) {
+                       if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
+                       $u = strtoupper($seqname);
+                       $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+                       $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
+                       $rs = $this->Execute($getnext);
+               }
+               $this->genID = mysqli_insert_id($this->_connectionID);
+               
+               if ($rs) $rs->Close();
+               
+               return $this->genID;
+       }
+       
+       function &MetaDatabases()
+         {
+           $query = "SHOW DATABASES";
+           $ret =& $this->Execute($query);
+               return $ret;
+         }
+
+         
+       function &MetaIndexes ($table, $primary = FALSE)
+       {
+               // save old fetch mode
+               global $ADODB_FETCH_MODE;
+               
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               if ($this->fetchMode !== FALSE) {
+                      $savem = $this->SetFetchMode(FALSE);
+               }
+               
+               // get index details
+               $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table));
+               
+               // restore fetchmode
+               if (isset($savem)) {
+                       $this->SetFetchMode($savem);
+               }
+               $ADODB_FETCH_MODE = $save;
+               
+               if (!is_object($rs)) {
+                       return FALSE;
+               }
+               
+               $indexes = array ();
+               
+               // parse index data into array
+               while ($row = $rs->FetchRow()) {
+                       if ($primary == FALSE AND $row[2] == 'PRIMARY') {
+                               continue;
+                       }
+                       
+                       if (!isset($indexes[$row[2]])) {
+                               $indexes[$row[2]] = array(
+                                       'unique' => ($row[1] == 0),
+                                       'columns' => array()
+                               );
+                       }
+                       
+                       $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
+               }
+               
+               // sort columns by order in the index
+               foreach ( array_keys ($indexes) as $index )
+               {
+                       ksort ($indexes[$index]['columns']);
+               }
+               
+               return $indexes;
+       }
+
+       
+       // Format date column in sql string given an input format that understands Y M D
+       function SQLDate($fmt, $col=false)
+       {       
+               if (!$col) $col = $this->sysTimeStamp;
+               $s = 'DATE_FORMAT('.$col.",'";
+               $concat = false;
+               $len = strlen($fmt);
+               for ($i=0; $i < $len; $i++) {
+                       $ch = $fmt[$i];
+                       switch($ch) {
+                       case 'Y':
+                       case 'y':
+                               $s .= '%Y';
+                               break;
+                       case 'Q':
+                       case 'q':
+                               $s .= "'),Quarter($col)";
+                               
+                               if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
+                               else $s .= ",('";
+                               $concat = true;
+                               break;
+                       case 'M':
+                               $s .= '%b';
+                               break;
+                               
+                       case 'm':
+                               $s .= '%m';
+                               break;
+                       case 'D':
+                       case 'd':
+                               $s .= '%d';
+                               break;
+                       
+                       case 'H': 
+                               $s .= '%H';
+                               break;
+                               
+                       case 'h':
+                               $s .= '%I';
+                               break;
+                               
+                       case 'i':
+                               $s .= '%i';
+                               break;
+                               
+                       case 's':
+                               $s .= '%s';
+                               break;
+                               
+                       case 'a':
+                       case 'A':
+                               $s .= '%p';
+                               break;
+                               
+                       default:
+                               
+                               if ($ch == '\\') {
+                                       $i++;
+                                       $ch = substr($fmt,$i,1);
+                               }
+                               $s .= $ch;
+                               break;
+                       }
+               }
+               $s.="')";
+               if ($concat) $s = "CONCAT($s)";
+               return $s;
+       }
+       
+       // returns concatenated string
+       // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
+       function Concat()
+       {
+               $s = "";
+               $arr = func_get_args();
+               
+               // suggestion by andrew005@mnogo.ru
+               $s = implode(',',$arr); 
+               if (strlen($s) > 0) return "CONCAT($s)";
+               else return '';
+       }
+       
+       // dayFraction is a day in floating point
+       function OffsetDate($dayFraction,$date=false)
+       {               
+               if (!$date) 
+                 $date = $this->sysDate;
+               return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)";
+       }
+       
+       // returns true or false
+       // To add: parameter int $port,
+       //         parameter string $socket
+       function _connect($argHostname = NULL, 
+                         $argUsername = NULL, 
+                         $argPassword = NULL, 
+                         $argDatabasename = NULL)
+         {
+           // @ means: error surpression on
+           $this->_connectionID = @mysqli_init();
+           
+           if (is_null($this->_connectionID))
+           {
+             // mysqli_init only fails if insufficient memory
+             if ($this->debug) 
+               ADOConnection::outp("mysqli_init() failed : "  . $this->ErrorMsg());
+             return false;
+           }
+           // Set connection options
+           // Not implemented now
+           // mysqli_options($this->_connection,,);
+           if (mysqli_real_connect($this->_connectionID,
+                                   $argHostname,
+                                   $argUsername,
+                                   $argPassword,
+                                   $argDatabasename))
+             {
+               if ($argDatabasename) 
+                 {
+                   return $this->SelectDB($argDatabasename);
+                 }
+               
+               return true;
+             }
+           else
+             {
+               if ($this->debug) 
+                 ADOConnection::outp("Could't connect : "  . $this->ErrorMsg());
+               return false;
+             }
+         }
+       
+       // returns true or false
+       // How to force a persistent connection
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+         {
+           // not implemented in mysqli (yet)?
+           $this->_connectionID = mysqli_connect($argHostname,
+                                                 $argUsername,
+                                                 $argPassword,
+                                                 $argDatabasename);
+           if ($this->_connectionID === false) return false;
+           //      if ($this->autoRollback) $this->RollbackTrans();
+           if ($argDatabasename) return $this->SelectDB($argDatabasename);
+           return true;        
+         }
+       
+       // When is this used? Close old connection first?
+       // In _connect(), check $this->forceNewConnect? 
+       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+         {
+           $this->forceNewConnect = true;
+           $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
+         }
+       
+       function &MetaColumns($table) 
+       {
+         if ($this->metaColumnsSQL) {
+           global $ADODB_FETCH_MODE;
+           $save = $ADODB_FETCH_MODE;
+           $rs = false;
+           switch($ADODB_FETCH_MODE)
+             {
+             case ADODB_FETCH_NUM:
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $rs = $this->Execute(sprintf($this->metaColumnsSQL,
+                                            $table));
+               
+               $ADODB_FETCH_MODE = $save;
+               if ($rs === false) break;
+               $retarr = array();
+               while (!$rs->EOF){
+                 $fld = new ADOFieldObject();
+                 $fld->name = $rs->fields[0];
+                 $fld->type = $rs->fields[1];
+                 // split type into type(length):
+                 if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array))
+                   {
+                     $fld->type = $query_array[1];
+                     $fld->max_length = $query_array[2];
+                   }
+                 else
+                   {
+                     $fld->max_length = -1;
+                   }
+                 $fld->not_null = ($rs->fields[2] != 'YES');
+                 $fld->primary_key = ($rs->fields[3] == 'PRI');
+                 $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
+                 $fld->binary = (strpos($fld->type,'blob') !== false);
+                 if (!$fld->binary) 
+                   {
+                     $d = $rs->fields[4];
+                     $d = $rs->fields['Default'];
+                     if ($d != "" && $d != "NULL")
+                       {
+                         $fld->has_default = true;
+                         $fld->default_value = $d;
+                       } 
+                     else 
+                       {
+                         $fld->has_default = false;
+                       }
+                   }
+                 $retarr[strtoupper($fld->name)] = $fld;       
+                 $rs->MoveNext();
+               }
+               break;
+             case ADODB_FETCH_ASSOC:
+             case ADODB_FETCH_DEFAULT:
+             case ADODB_FETCH_BOTH:
+               $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+               $rs = $this->Execute(sprintf($this->metaColumnsSQL,
+                                            $table));
+               $ADODB_FETCH_MODE = $save;
+               if ($rs === false) break;
+               $retarr = array();
+               while (!$rs->EOF){
+                 $fld = new ADOFieldObject();
+                 $fld->name = $rs->fields['Field'];
+                 $fld->type = $rs->fields['Type'];
+                               
+                 // split type into type(length):
+                 if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array))
+                   {
+                     $fld->type = $query_array[1];
+                     $fld->max_length = $query_array[2];
+                   }
+                 else
+                   {
+                     $fld->max_length = -1;
+                   }
+                 $fld->not_null = ($rs->fields['Null'] != 'YES');
+                 $fld->primary_key = ($rs->fields['Key'] == 'PRI');
+                 $fld->auto_increment = (strpos($rs->fields['Extra'], 'auto_increment') !== false);
+                 $fld->binary = (strpos($fld->type,'blob') !== false);
+                 if (!$fld->binary) 
+                   {
+                     $d = $rs->fields['Default'];
+                     if ($d != "" && $d != "NULL")
+                       {
+                         $fld->has_default = true;
+                         $fld->default_value = $d;
+                       } 
+                     else 
+                       {
+                         $fld->has_default = false;
+                       }
+                   }
+                 $retarr[strtoupper($fld->name)] = $fld;       
+                 $rs->MoveNext();
+               }
+               break;
+             default:
+             }
+           
+           if ($rs === false) return false;
+           $rs->Close();
+           return $retarr;     
+         }
+         return false;
+       }
+               
+       // returns true or false
+       function SelectDB($dbName) 
+       {
+//         $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
+           $this->databaseName = $dbName;
+           if ($this->_connectionID) {
+               $result = @mysqli_select_db($this->_connectionID, $dbName);
+                       if (!$result) {
+                       ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg());
+                       }
+                       return $result;         
+               }
+           return false;       
+       }
+       
+       // parameters use PostgreSQL convention, not MySQL
+       function &SelectLimit($sql,
+                             $nrows = -1,
+                             $offset = -1,
+                             $inputarr = false, 
+                             $arg3 = false,
+                             $secs = 0)
+       {
+               $offsetStr = ($offset >= 0) ? "$offset," : '';
+               
+               if ($secs)
+                       $rs =& $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);
+               else
+                       $rs =& $this->Execute($sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3);
+                       
+               return $rs;
+       }
+       
+       
+       function Prepare($sql)
+       {
+               return $sql;
+               
+               $stmt = mysqli_prepare($this->_connectionID,$sql);
+               if (!$stmt) return false;
+               return array($sql,$stmt);
+       }
+       
+       
+       // returns queryID or false
+       function _query($sql, $inputarr)
+       {
+       global $ADODB_COUNTRECS;
+       
+               if (is_array($sql)) {
+                       $stmt = $sql[1];
+                       foreach($inputarr as $k => $v) {
+                               if (is_string($v)) $a[] = MYSQLI_BIND_STRING;
+                               else if (is_integer($v)) $a[] = MYSQLI_BIND_INT; 
+                               else $a[] = MYSQLI_BIND_DOUBLE;
+                               
+                               $fnarr =& array_merge( array($stmt,$a) , $inputarr);
+                               $ret = call_user_func_array('mysqli_bind_param',$fnarr);
+                       }
+                       $ret = mysqli_execute($stmt);
+                       return $ret;
+               }
+               if (!$mysql_res =  mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) {
+                   if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
+                   return false;
+               }
+               
+               return $mysql_res;
+       }
+
+       /*      Returns: the last error message from previous database operation        */      
+       function ErrorMsg() 
+         {
+           if (empty($this->_connectionID)) 
+             $this->_errorMsg = @mysqli_error();
+           else 
+             $this->_errorMsg = @mysqli_error($this->_connectionID);
+           return $this->_errorMsg;
+         }
+       
+       /*      Returns: the last error number from previous database operation */      
+       function ErrorNo() 
+         {
+           if (empty($this->_connectionID))  
+             return @mysqli_errno();
+           else 
+             return @mysqli_errno($this->_connectionID);
+         }
+       
+       // returns true or false
+       function _close()
+         {
+           @mysqli_close($this->_connectionID);
+           $this->_connectionID = false;
+         }
+
+       /*
+       * Maximum size of C field
+       */
+       function CharMax()
+       {
+               return 255; 
+       }
+       
+       /*
+       * Maximum size of X field
+       */
+       function TextMax()
+       {
+         return 4294967295; 
+       }
+
+
+}
+/*--------------------------------------------------------------------------------------
+        Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_mysqli extends ADORecordSet{        
+       
+       var $databaseType = "mysqli";
+       var $canSeek = true;
+       
+       function ADORecordSet_mysqli($queryID, $mode = false) 
+       {
+         if ($mode === false) 
+           { 
+             global $ADODB_FETCH_MODE;
+             $mode = $ADODB_FETCH_MODE;
+           }
+         switch ($mode)
+           {
+           case ADODB_FETCH_NUM: 
+             $this->fetchMode = MYSQLI_NUM; 
+             break;
+           case ADODB_FETCH_ASSOC:
+             $this->fetchMode = MYSQLI_ASSOC; 
+             break;
+           case ADODB_FETCH_DEFAULT:
+           case ADODB_FETCH_BOTH:
+           default:
+             $this->fetchMode = MYSQLI_ASSOC; 
+             break;
+           }
+         $this->ADORecordSet($queryID);        
+       }
+       
+       function _initrs()
+       {
+           // mysqli_num_rows only return correct number, depens
+           // on the use of mysql_store_result and mysql_use_result
+           if (!$this->Connection->executeOnly) {
+                       $this->_numOfRows = @mysqli_num_rows($this->_queryID);
+                       $this->_numOfFields = @mysqli_num_fields($this->_queryID);
+           }
+           else {
+                       $this->_numOfRows = 0;
+                       $this->_numOfFields = 0;
+           }
+       }
+       
+       function &FetchField($fieldOffset = -1) 
+       {       
+         $fieldnr = $fieldOffset;
+         if ($fieldOffset != -1) {
+           $fieldOffset = mysqi_field_seek($this->_queryID, $fieldnr);
+         }
+         $o = mysqli_fetch_field($this->_queryID);
+         return $o;
+       }
+
+       function &GetRowAssoc($upper = true)
+       {
+         if ($this->fetchMode == MYSQLI_ASSOC && !$upper) 
+           return $this->fields;
+         $row =& ADORecordSet::GetRowAssoc($upper);
+         return $row;
+       }
+       
+       /* Use associative array to get fields array */
+       function Fields($colname)
+       {       
+         if ($this->fetchMode != MYSQLI_NUM) 
+           return @$this->fields[$colname];
+               
+         if (!$this->bind) {
+           $this->bind = array();
+           for ($i = 0; $i < $this->_numOfFields; $i++) {
+             $o = $this->FetchField($i);
+             $this->bind[strtoupper($o->name)] = $i;
+           }
+         }
+         return $this->fields[$this->bind[strtoupper($colname)]];
+       }
+       
+       function _seek($row)
+       {
+         if ($this->_numOfRows == 0) 
+           return false;
+
+         if ($row < 0)
+           return false;
+
+         mysqli_data_seek($this->_queryID, $row);
+         $this->EOF = false;
+         return true;
+       }
+               
+       // 10% speedup to move MoveNext to child class
+       // This is the only implementation that works now (23-10-2003).
+       // Other functions return no or the wrong results.
+       function MoveNext() 
+       {
+         if ($this->EOF) 
+           return false;
+         $this->_currentRow++;
+         switch($this->fetchMode)
+           {
+           case MYSQLI_NUM:
+             $this->fields = mysqli_fetch_array($this->_queryID);
+             break;
+           case MYSQLI_ASSOC:
+           case MYSQLI_BOTH:
+             $this->fields = mysqli_fetch_assoc($this->_queryID);
+             break;
+           default:
+           }
+         if (is_array($this->fields)) 
+           return true;
+         $this->EOF = true;
+         return false;
+       }       
+       
+       function _fetch()
+       {
+         // mysqli_fetch_array($this->_queryID, MYSQLI_NUM) does not
+         // work (22-10-2003). But mysqli_fetch_array($this->_queryID) gives
+         // int resulttype should default to MYSQLI_BOTH,but give MYSQLI_NUM.
+
+         //      $this->fields =  mysqli_fetch_fields($this->_queryID);
+         //      $this->fields =  mysqli_fetch_array($this->_queryID); //, $this->fetchMode);
+                 
+         $this->fields =  mysqli_fetch_assoc($this->_queryID); // $this->fetchMode);
+         return is_array($this->fields);
+       }
+       
+       function _close() 
+       {
+         mysqli_free_result($this->_queryID); 
+         $this->_queryID = false;      
+       }
+       
+       function MetaType($t, $len = -1, $fieldobj = false)
+       {
+         if (is_object($t)) 
+           {
+             $fieldobj = $t;
+             $t = $fieldobj->type;
+             $len = $fieldobj->max_length;
+           }
+               
+         $len = -1; // mysql max_length is not accurate
+         switch (strtoupper($t)) {
+         case 'STRING': 
+         case 'CHAR':
+         case 'VARCHAR': 
+         case 'TINYBLOB': 
+         case 'TINYTEXT': 
+         case 'ENUM': 
+         case 'SET': 
+           if ($len <= $this->blobSize) return 'C';
+           
+         case 'TEXT':
+         case 'LONGTEXT': 
+         case 'MEDIUMTEXT':
+           return 'X';
+                       
+           // php_mysql extension always returns 'blob' even if 'text'
+           // so we have to check whether binary...
+         case 'IMAGE':
+         case 'LONGBLOB': 
+         case 'BLOB':
+         case 'MEDIUMBLOB':
+           return !empty($fieldobj->binary) ? 'B' : 'X';
+         case 'YEAR':
+         case 'DATE': 
+           return 'D';
+               
+         case 'TIME':
+         case 'DATETIME':
+         case 'TIMESTAMP': return 'T';
+               
+         case 'INT': 
+         case 'INTEGER':
+         case 'BIGINT':
+         case 'TINYINT':
+         case 'MEDIUMINT':
+         case 'SMALLINT': 
+                       
+           if (!empty($fieldobj->primary_key)) return 'R';
+           else return 'I';
+           // Added floating-point types
+           // Maybe not necessery.
+         case 'FLOAT':
+         case 'DOUBLE':
+           //          case 'DOUBLE PRECISION':
+         case 'DECIMAL':
+         case 'DEC':
+         case 'FIXED':
+         default: 
+           return 'N';
+         }
+       }
+       
+
+}
+}
+
 ?>
\ No newline at end of file
index 8b82ea50ba721fe86c41e5fddf7712fc4e36e9f5..5d8fcdaf46f1bed788ee6bd30416cb579d61d250 100644 (file)
@@ -1,76 +1,76 @@
-<?php\r
-\r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 8.\r
-  \r
-  MySQL code that supports transactions. For MySQL 3.23 or later.\r
-  Code from James Poon <jpoon88@yahoo.com>\r
-  \r
-  Requires mysql client. Works on Windows and Unix.\r
-*/\r
-\r
-\r
-include_once(ADODB_DIR."/drivers/adodb-mysql.inc.php");\r
-\r
-\r
-class ADODB_mysqlt extends ADODB_mysql {\r
-       var $databaseType = 'mysqlt';\r
-       var $ansiOuter = true; // for Version 3.23.17 or later\r
-       var $hasTransactions = true;\r
-       \r
-       function BeginTrans()\r
-       {         \r
-               if ($this->transOff) return true;\r
-               $this->transCnt += 1;\r
-               $this->Execute('SET AUTOCOMMIT=0');\r
-               $this->Execute('BEGIN');\r
-               return true;\r
-       }\r
-       \r
-       function CommitTrans($ok=true) \r
-       {\r
-               if ($this->transOff) return true; \r
-               if (!$ok) return $this->RollbackTrans();\r
-               \r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $this->Execute('COMMIT');\r
-               $this->Execute('SET AUTOCOMMIT=1');\r
-               return true;\r
-       }\r
-       \r
-       function RollbackTrans()\r
-       {\r
-               if ($this->transOff) return true;\r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $this->Execute('ROLLBACK');\r
-               $this->Execute('SET AUTOCOMMIT=1');\r
-               return true;\r
-       }\r
-       \r
-}\r
-\r
-class ADORecordSet_mysqlt extends ADORecordSet_mysql{  \r
-       var $databaseType = "mysqlt";\r
-       \r
-       function ADORecordSet_mysqlt($queryID,$mode=false) {\r
-               return $this->ADORecordSet_mysql($queryID,$mode);\r
-       }\r
-       \r
-       function MoveNext() \r
-       {       \r
-               if ($this->EOF) return false;\r
-\r
-               $this->_currentRow++;\r
-               // using & below slows things down by 20%!\r
-               $this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);\r
-               if ($this->fields) return true;\r
-               $this->EOF = true;\r
-               \r
-               return false;\r
-       }       \r
-}\r
+<?php
+
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+  
+  MySQL code that supports transactions. For MySQL 3.23 or later.
+  Code from James Poon <jpoon88@yahoo.com>
+  
+  Requires mysql client. Works on Windows and Unix.
+*/
+
+
+include_once(ADODB_DIR."/drivers/adodb-mysql.inc.php");
+
+
+class ADODB_mysqlt extends ADODB_mysql {
+       var $databaseType = 'mysqlt';
+       var $ansiOuter = true; // for Version 3.23.17 or later
+       var $hasTransactions = true;
+       
+       function BeginTrans()
+       {         
+               if ($this->transOff) return true;
+               $this->transCnt += 1;
+               $this->Execute('SET AUTOCOMMIT=0');
+               $this->Execute('BEGIN');
+               return true;
+       }
+       
+       function CommitTrans($ok=true) 
+       {
+               if ($this->transOff) return true; 
+               if (!$ok) return $this->RollbackTrans();
+               
+               if ($this->transCnt) $this->transCnt -= 1;
+               $this->Execute('COMMIT');
+               $this->Execute('SET AUTOCOMMIT=1');
+               return true;
+       }
+       
+       function RollbackTrans()
+       {
+               if ($this->transOff) return true;
+               if ($this->transCnt) $this->transCnt -= 1;
+               $this->Execute('ROLLBACK');
+               $this->Execute('SET AUTOCOMMIT=1');
+               return true;
+       }
+       
+}
+
+class ADORecordSet_mysqlt extends ADORecordSet_mysql{  
+       var $databaseType = "mysqlt";
+       
+       function ADORecordSet_mysqlt($queryID,$mode=false) {
+               return $this->ADORecordSet_mysql($queryID,$mode);
+       }
+       
+       function MoveNext() 
+       {       
+               if ($this->EOF) return false;
+
+               $this->_currentRow++;
+               // using & below slows things down by 20%!
+               $this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);
+               if ($this->fields) return true;
+               $this->EOF = true;
+               
+               return false;
+       }       
+}
 ?>
\ No newline at end of file
index ae6563e2d8a861bf8dc0e1c18dd9de3af1d027fa..efabaf4b38afd055867bb98bf092aeaca800434c 100644 (file)
-<?php\r
-/*\r
-\r
-  version V4.11 27 Jan 2004 (c) 2000-2004 John Lim. All rights reserved.\r
-\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-\r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Code contributed by George Fourlanos <fou@infomap.gr>\r
-  \r
-  13 Nov 2000 jlim - removed all ora_* references.\r
-*/\r
-\r
-/*\r
-NLS_Date_Format\r
-Allows you to use a date format other than the Oracle Lite default. When a literal\r
-character string appears where a date value is expected, the Oracle Lite database\r
-tests the string to see if it matches the formats of Oracle, SQL-92, or the value\r
-specified for this parameter in the POLITE.INI file. Setting this parameter also\r
-defines the default format used in the TO_CHAR or TO_DATE functions when no\r
-other format string is supplied.\r
-\r
-For Oracle the default is dd-mon-yy or dd-mon-yyyy, and for SQL-92 the default is\r
-yy-mm-dd or yyyy-mm-dd.\r
-\r
-Using 'RR' in the format forces two-digit years less than or equal to 49 to be\r
-interpreted as years in the 21st century (2000\962049), and years over 50 as years in\r
-the 20th century (1950\961999). Setting the RR format as the default for all two-digit\r
-year entries allows you to become year-2000 compliant. For example:\r
-NLS_DATE_FORMAT='RR-MM-DD'\r
-\r
-You can also modify the date format using the ALTER SESSION command. \r
-*/\r
-\r
-class ADODB_oci8 extends ADOConnection {\r
-       var $databaseType = 'oci8';\r
-       var $dataProvider = 'oci8';\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $concat_operator='||';\r
-       var $sysDate = "TRUNC(SYSDATE)";\r
-       var $sysTimeStamp = 'SYSDATE';\r
-       var $metaDatabasesSQL = "SELECT USERNAME FROM ALL_USERS WHERE USERNAME NOT IN ('SYS','SYSTEM','DBSNMP','OUTLN') ORDER BY 1";\r
-       var $_stmt;\r
-       var $_commit = OCI_COMMIT_ON_SUCCESS;\r
-       var $_initdate = true; // init date to YYYY-MM-DD\r
-       var $metaTablesSQL = "select table_name,table_type from cat where table_type in ('TABLE','VIEW')";\r
-       var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net\r
-       var $_bindInputArray = true;\r
-       var $hasGenID = true;\r
-       var $_genIDSQL = "SELECT (%s.nextval) FROM DUAL";\r
-       var $_genSeqSQL = "CREATE SEQUENCE %s START WITH %s";\r
-       var $_dropSeqSQL = "DROP SEQUENCE %s";\r
-       var $hasAffectedRows = true;\r
-       var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)";\r
-       var $noNullStrings = false;\r
-       var $connectSID = false;\r
-       var $_bind = false;\r
-       var $_hasOCIFetchStatement = false;\r
-       var $_getarray = false; // currently not working\r
-       var $leftOuter = '';  // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER\r
-       var $session_sharing_force_blob = false; // alter session on updateblob if set to true \r
-       var $firstrows = true; // enable first rows optimization on SelectLimit()\r
-       var $selectOffsetAlg1 = 100; // when to use 1st algorithm of selectlimit.\r
-       var $NLS_DATE_FORMAT = 'YYYY-MM-DD';  // To include time, use 'RRRR-MM-DD HH24:MI:SS'\r
-       var $useDBDateFormatForTextInput=false;\r
-       var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true)\r
-       \r
-       // var $ansiOuter = true; // if oracle9\r
-    \r
-       function ADODB_oci8() \r
-       {\r
-               $this->_hasOCIFetchStatement = ADODB_PHPVER >= 0x4200;\r
-       }\r
-       \r
-       /*  Function &MetaColumns($table) added by smondino@users.sourceforge.net*/\r
-       function &MetaColumns($table) \r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
-               \r
-               $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));\r
-               \r
-               if (isset($savem)) $this->SetFetchMode($savem);\r
-               $ADODB_FETCH_MODE = $save;\r
-               if (!$rs) return false;\r
-               $retarr = array();\r
-               while (!$rs->EOF) { //print_r($rs->fields);\r
-                       $fld = new ADOFieldObject();\r
-                       $fld->name = $rs->fields[0];\r
-                       $fld->type = $rs->fields[1];\r
-                       $fld->max_length = $rs->fields[2];\r
-                       $fld->scale = $rs->fields[3];\r
-                       if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) {\r
-                               $fld->type ='INT';\r
-                       $fld->max_length = $rs->fields[4];\r
-               }       \r
-                       $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);\r
-                       $fld->binary = (strpos($fld->type,'BLOB') !== false);\r
-                       $fld->default_value = $rs->fields[6];\r
-                       \r
-                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
-                       else $retarr[strtoupper($fld->name)] = $fld;\r
-                       $rs->MoveNext();\r
-               }\r
-               $rs->Close();\r
-               return $retarr;\r
-       }\r
\r
-/*\r
-\r
-  Multiple modes of connection are supported:\r
-  \r
-  a. Local Database\r
-    $conn->Connect(false,'scott','tiger');\r
-  \r
-  b. From tnsnames.ora\r
-    $conn->Connect(false,'scott','tiger',$tnsname); \r
-    $conn->Connect($tnsname,'scott','tiger'); \r
-  \r
-  c. Server + service name\r
-    $conn->Connect($serveraddress,'scott,'tiger',$service_name);\r
-  \r
-  d. Server + SID\r
-       $conn->connectSID = true;\r
-       $conn->Connect($serveraddress,'scott,'tiger',$SID);\r
-\r
-\r
-Example TNSName:\r
----------------\r
-NATSOFT.DOMAIN =\r
-  (DESCRIPTION =\r
-       (ADDRESS_LIST =\r
-         (ADDRESS = (PROTOCOL = TCP)(HOST = kermit)(PORT = 1523))\r
-       )\r
-       (CONNECT_DATA =\r
-         (SERVICE_NAME = natsoft.domain)\r
-       )\r
-  )\r
-  \r
-  There are 3 connection modes, 0 = non-persistent, 1 = persistent, 2 = force new connection\r
-       \r
-*/\r
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$mode=0)\r
-       {\r
-               if (!function_exists('OCIPLogon')) return false;\r
-               \r
-               \r
-        $this->_errorMsg = false;\r
-               $this->_errorCode = false;\r
-               \r
-               if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>\r
-                       if (empty($argDatabasename)) $argDatabasename = $argHostname;\r
-                       else {\r
-                               if(strpos($argHostname,":")) {\r
-                                       $argHostinfo=explode(":",$argHostname);\r
-                                       $argHostname=$argHostinfo[0];\r
-                                       $argHostport=$argHostinfo[1];\r
-                               } else {\r
-                                       $argHostport="1521";\r
-                               }\r
-                               \r
-                               if ($this->connectSID) {\r
-                                       $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname\r
-                                       .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";\r
-                               } else\r
-                                       $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname\r
-                                       .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";\r
-                       }\r
-               }\r
-                               \r
-               //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";\r
-               if ($mode==1) {\r
-                       $this->_connectionID = OCIPLogon($argUsername,$argPassword, $argDatabasename);\r
-                       if ($this->_connectionID && $this->autoRollback)  OCIrollback($this->_connectionID);\r
-               } else if ($mode==2) {\r
-                       $this->_connectionID = OCINLogon($argUsername,$argPassword, $argDatabasename);\r
-               } else {\r
-                       $this->_connectionID = OCILogon($argUsername,$argPassword, $argDatabasename);\r
-               }\r
-               if ($this->_connectionID === false) return false;\r
-               if ($this->_initdate) {\r
-                       $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");\r
-               }\r
-               \r
-               // looks like: \r
-               // Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production With the Partitioning option JServer Release 8.1.7.0.0 - Production\r
-               // $vers = OCIServerVersion($this->_connectionID);\r
-               // if (strpos($vers,'8i') !== false) $this->ansiOuter = true;\r
-               return true;\r
-       }\r
-       \r
-       function ServerInfo()\r
-       {\r
-               $arr['compat'] = $this->GetOne('select value from sys.database_compatible_level');\r
-               $arr['description'] = @OCIServerVersion($this->_connectionID);\r
-               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
-               return $arr;\r
-       }\r
-               // returns true or false\r
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,1);\r
-       }\r
-       \r
-       \r
-       \r
-       // returns true or false\r
-       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,2);\r
-       }\r
-       \r
-       function _affectedrows()\r
-       {\r
-               if (is_resource($this->_stmt)) return OCIRowCount($this->_stmt);\r
-               return 0;\r
-       }\r
-       \r
-       function IfNull( $field, $ifNull ) \r
-       {\r
-               return " NVL($field, $ifNull) "; // if Oracle\r
-       }\r
-       \r
-       // format and return date string in database date format\r
-       function DBDate($d)\r
-       {\r
-               if (empty($d) && $d !== 0) return 'null';\r
-               \r
-               if (is_string($d)) $d = ADORecordSet::UnixDate($d);\r
-               return "TO_DATE(".adodb_date($this->fmtDate,$d).",'".$this->NLS_DATE_FORMAT."')";\r
-       }\r
-\r
-       \r
-       // format and return date string in database timestamp format\r
-       function DBTimeStamp($ts)\r
-       {\r
-               if (empty($ts) && $ts !== 0) return 'null';\r
-               if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);\r
-               return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";\r
-       }\r
-       \r
-       function RowLock($tables,$where) \r
-       {\r
-               if ($this->autoCommit) $this->BeginTrans();\r
-               return $this->GetOne("select 1 as ignore from $tables where $where for update");\r
-       }\r
-       \r
-       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
-       {\r
-               if ($mask) {\r
-                       $save = $this->metaTablesSQL;\r
-                       $mask = $this->qstr(strtoupper($mask));\r
-                       $this->metaTablesSQL .= " AND table_name like $mask";\r
-               }\r
-               $ret =& ADOConnection::MetaTables($ttype,$showSchema);\r
-               \r
-               if ($mask) {\r
-                       $this->metaTablesSQL = $save;\r
-               }\r
-               return $ret;\r
-       }\r
-       \r
-       function BeginTrans()\r
-       {       \r
-               if ($this->transOff) return true;\r
-               $this->transCnt += 1;\r
-               $this->autoCommit = false;\r
-               $this->_commit = OCI_DEFAULT;\r
-               return true;\r
-       }\r
-       \r
-       function CommitTrans($ok=true) \r
-       { \r
-               if ($this->transOff) return true;\r
-               if (!$ok) return $this->RollbackTrans();\r
-               \r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $ret = OCIcommit($this->_connectionID);\r
-               $this->_commit = OCI_COMMIT_ON_SUCCESS;\r
-               $this->autoCommit = true;\r
-               return $ret;\r
-       }\r
-       \r
-       function RollbackTrans()\r
-       {\r
-               if ($this->transOff) return true;\r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $ret = OCIrollback($this->_connectionID);\r
-               $this->_commit = OCI_COMMIT_ON_SUCCESS;\r
-               $this->autoCommit = true;\r
-               return $ret;\r
-       }\r
-       \r
-       \r
-       function SelectDB($dbName) \r
-       {\r
-               return false;\r
-       }\r
-\r
-       function ErrorMsg() \r
-       {\r
-               if ($this->_errorMsg !== false) return $this->_errorMsg;\r
-\r
-               if (is_resource($this->_stmt)) $arr = @OCIerror($this->_stmt);\r
-               if (empty($arr)) {\r
-                       $arr = @OCIerror($this->_connectionID);\r
-                       if ($arr === false) $arr = @OCIError();\r
-                       if ($arr === false) return '';\r
-               }\r
-               $this->_errorMsg = $arr['message'];\r
-               $this->_errorCode = $arr['code'];\r
-               return $this->_errorMsg;\r
-       }\r
-\r
-       function ErrorNo() \r
-       {\r
-               if ($this->_errorCode !== false) return $this->_errorCode;\r
-               \r
-               if (is_resource($this->_stmt)) $arr = @OCIError($this->_stmt);\r
-               if (empty($arr)) {\r
-                       $arr = @OCIError($this->_connectionID);\r
-                       if ($arr == false) $arr = @OCIError();\r
-                       if ($arr == false) return '';\r
-               }\r
-               \r
-               $this->_errorMsg = $arr['message'];\r
-               $this->_errorCode = $arr['code'];\r
-               \r
-               return $arr['code'];\r
-       }\r
-       \r
-       // Format date column in sql string given an input format that understands Y M D\r
-       function SQLDate($fmt, $col=false)\r
-       {       \r
-               if (!$col) $col = $this->sysTimeStamp;\r
-               $s = 'TO_CHAR('.$col.",'";\r
-               \r
-               $len = strlen($fmt);\r
-               for ($i=0; $i < $len; $i++) {\r
-                       $ch = $fmt[$i];\r
-                       switch($ch) {\r
-                       case 'Y':\r
-                       case 'y':\r
-                               $s .= 'YYYY';\r
-                               break;\r
-                       case 'Q':\r
-                       case 'q':\r
-                               $s .= 'Q';\r
-                               break;\r
-                               \r
-                       case 'M':\r
-                               $s .= 'Mon';\r
-                               break;\r
-                               \r
-                       case 'm':\r
-                               $s .= 'MM';\r
-                               break;\r
-                       case 'D':\r
-                       case 'd':\r
-                               $s .= 'DD';\r
-                               break;\r
-                       \r
-                       case 'H':\r
-                               $s.= 'HH24';\r
-                               break;\r
-                               \r
-                       case 'h':\r
-                               $s .= 'HH';\r
-                               break;\r
-                               \r
-                       case 'i':\r
-                               $s .= 'MI';\r
-                               break;\r
-                       \r
-                       case 's':\r
-                               $s .= 'SS';\r
-                               break;\r
-                       \r
-                       case 'a':\r
-                       case 'A':\r
-                               $s .= 'AM';\r
-                               break;\r
-                               \r
-                       default:\r
-                       // handle escape characters...\r
-                               if ($ch == '\\') {\r
-                                       $i++;\r
-                                       $ch = substr($fmt,$i,1);\r
-                               }\r
-                               if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;\r
-                               else $s .= '"'.$ch.'"';\r
-                               \r
-                       }\r
-               }\r
-               return $s. "')";\r
-       }\r
-       \r
-       \r
-       /*\r
-       This algorithm makes use of\r
-       \r
-       a. FIRST_ROWS hint\r
-       The FIRST_ROWS hint explicitly chooses the approach to optimize response time, \r
-       that is, minimum resource usage to return the first row. Results will be returned \r
-       as soon as they are identified. \r
-\r
-       b. Uses rownum tricks to obtain only the required rows from a given offset.\r
-        As this uses complicated sql statements, we only use this if the $offset >= 100. \r
-        This idea by Tomas V V Cox.\r
-        \r
-        This implementation does not appear to work with oracle 8.0.5 or earlier. Comment\r
-        out this function then, and the slower SelectLimit() in the base class will be used.\r
-       */\r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
-       {\r
-               // seems that oracle only supports 1 hint comment in 8i\r
-               if ($this->firstrows) {\r
-                       if (strpos($sql,'/*+') !== false)\r
-                               $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);\r
-                       else\r
-                               $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);\r
-               }\r
-               \r
-               if ($offset < $this->selectOffsetAlg1) {\r
-                       if ($nrows > 0) {       \r
-                               if ($offset > 0) $nrows += $offset;\r
-                               //$inputarr['adodb_rownum'] = $nrows;\r
-                               if ($this->databaseType == 'oci8po') {\r
-                                       $sql = "select * from ($sql) where rownum <= ?";\r
-                               } else {\r
-                                       $sql = "select * from ($sql) where rownum <= :adodb_offset";\r
-                               } \r
-                               $inputarr['adodb_offset'] = $nrows;\r
-                               $nrows = -1;\r
-                       }\r
-                       // note that $nrows = 0 still has to work ==> no rows returned\r
-\r
-                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
-                       return $rs;\r
-                       \r
-               } else {\r
-                        // Algorithm by Tomas V V Cox, from PEAR DB oci8.php\r
-                       \r
-                        // Let Oracle return the name of the columns\r
-                        $q_fields = "SELECT * FROM ($sql) WHERE NULL = NULL";\r
-                        if (!$stmt = OCIParse($this->_connectionID, $q_fields)) {\r
-                                return false;\r
-                        }\r
-                        \r
-                        if (is_array($inputarr)) {\r
-                               foreach($inputarr as $k => $v) {\r
-                                       if (is_array($v)) {\r
-                                               if (sizeof($v) == 2) // suggested by g.giunta@libero.\r
-                                                       OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);\r
-                                               else\r
-                                                       OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);\r
-                                       } else {\r
-                                               $len = -1;\r
-                                               if ($v === ' ') $len = 1;\r
-                                               if (isset($bindarr)) {  // is prepared sql, so no need to ocibindbyname again\r
-                                                       $bindarr[$k] = $v;\r
-                                               } else {                                // dynamic sql, so rebind every time\r
-                                                       OCIBindByName($stmt,":$k",$inputarr[$k],$len);\r
-                                               }\r
-                                       }\r
-                               }\r
-                       }\r
-                       \r
-                        if (!OCIExecute($stmt, OCI_DEFAULT)) {\r
-                                OCIFreeStatement($stmt); \r
-                                return false;\r
-                        }\r
-                        \r
-                        $ncols = OCINumCols($stmt);\r
-                        for ( $i = 1; $i <= $ncols; $i++ ) {\r
-                                $cols[] = '"'.OCIColumnName($stmt, $i).'"';\r
-                        }\r
-                        $result = false;\r
-                       \r
-                        OCIFreeStatement($stmt); \r
-                        $fields = implode(',', $cols);\r
-                        $nrows += $offset;\r
-                        $offset += 1; // in Oracle rownum starts at 1\r
-                       \r
-                       if ($this->databaseType == 'oci8po') {\r
-                                        $sql = "SELECT $fields FROM".\r
-                                         "(SELECT rownum as adodb_rownum, $fields FROM".\r
-                                         " ($sql) WHERE rownum <= ?".\r
-                                         ") WHERE adodb_rownum >= ?";\r
-                               } else {\r
-                                        $sql = "SELECT $fields FROM".\r
-                                         "(SELECT rownum as adodb_rownum, $fields FROM".\r
-                                         " ($sql) WHERE rownum <= :adodb_nrows".\r
-                                         ") WHERE adodb_rownum >= :adodb_offset";\r
-                               } \r
-                               $inputarr['adodb_nrows'] = $nrows;\r
-                               $inputarr['adodb_offset'] = $offset;\r
-                               \r
-                       if ($secs2cache>0) $rs =& $this->CacheExecute($secs2cache, $sql,$inputarr);\r
-                       else $rs =& $this->Execute($sql,$inputarr);\r
-                       return $rs;\r
-               }\r
-       \r
-       }\r
-       \r
-       /**\r
-       * Usage:\r
-       * Store BLOBs and CLOBs\r
-       *\r
-       * Example: to store $var in a blob\r
-       *\r
-       *       $conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())');\r
-       *       $conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB');\r
-       *       \r
-       *       $blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'.\r
-       *\r
-       *  to get length of LOB:\r
-       *       select DBMS_LOB.GETLENGTH(ablob) from TABLE\r
-       *\r
-       * If you are using CURSOR_SHARING = force, it appears this will case a segfault\r
-       * under oracle 8.1.7.0. Run:\r
-       *        $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');\r
-       * before UpdateBlob() then...\r
-       */\r
-\r
-       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
-       {\r
-               \r
-               //if (strlen($val) < 4000) return $this->Execute("UPDATE $table SET $column=:blob WHERE $where",array('blob'=>$val)) != false;\r
-               \r
-               switch(strtoupper($blobtype)) {\r
-               default: ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;\r
-               case 'BLOB': $type = OCI_B_BLOB; break;\r
-               case 'CLOB': $type = OCI_B_CLOB; break;\r
-               }\r
-               \r
-               if ($this->databaseType == 'oci8po') \r
-                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";\r
-               else \r
-                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";\r
-               \r
-               $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);\r
-               $arr['blob'] = array($desc,-1,$type);\r
-               if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');\r
-               $commit = $this->autoCommit;\r
-               if ($commit) $this->BeginTrans();\r
-               $rs = ADODB_oci8::Execute($sql,$arr);\r
-               if ($rez = !empty($rs)) $desc->save($val);\r
-               $desc->free();\r
-               if ($commit) $this->CommitTrans();\r
-               if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE');\r
-               \r
-               if ($rez) $rs->Close();\r
-               return $rez;\r
-       }\r
-       \r
-       /**\r
-       * Usage:  store file pointed to by $var in a blob\r
-       */\r
-       function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB')\r
-       {\r
-               switch(strtoupper($blobtype)) {\r
-               default: ADOConnection::outp( "<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;\r
-               case 'BLOB': $type = OCI_B_BLOB; break;\r
-               case 'CLOB': $type = OCI_B_CLOB; break;\r
-               }\r
-               \r
-               if ($this->databaseType == 'oci8po') \r
-                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";\r
-               else \r
-                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";\r
-               \r
-               $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);\r
-               $arr['blob'] = array($desc,-1,$type);\r
-               \r
-               $this->BeginTrans();\r
-               $rs = ADODB_oci8::Execute($sql,$arr);\r
-               if ($rez = !empty($rs)) $desc->savefile($val);\r
-               $desc->free();\r
-               $this->CommitTrans();\r
-               \r
-               if ($rez) $rs->Close();\r
-               return $rez;\r
-       }\r
-       \r
-       /*\r
-               Example of usage:\r
-               \r
-               $stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)');\r
-       */\r
-       function Prepare($sql,$cursor=false)\r
-       {\r
-       static $BINDNUM = 0;\r
-       \r
-               $stmt = OCIParse($this->_connectionID,$sql);\r
-\r
-               if (!$stmt) return $sql; // error in statement, let Execute() handle the error\r
-               \r
-               $BINDNUM += 1;\r
-               \r
-               if (@OCIStatementType($stmt) == 'BEGIN') {\r
-                       return array($sql,$stmt,0,$BINDNUM, ($cursor) ? false : OCINewCursor($this->_connectionID));\r
-               } \r
-               \r
-               return array($sql,$stmt,0,$BINDNUM);\r
-       }\r
-       \r
-       /*\r
-               Call an oracle stored procedure and return a cursor variable. \r
-               Convert the cursor variable into a recordset. \r
-               Concept by Robert Tuttle robert@ud.com\r
-               \r
-               Example:\r
-                       Note: we return a cursor variable in :RS2\r
-                       $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS2); END;",'RS2');\r
-                       \r
-                       $rs = $db->ExecuteCursor(\r
-                               "BEGIN :RS2 = adodb.getdata(:VAR1); END;", \r
-                               'RS2',\r
-                               array('VAR1' => 'Mr Bean'));\r
-                       \r
-       */\r
-       function &ExecuteCursor($sql,$cursorName='rs',$params=false)\r
-       {\r
-               $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor\r
-                       \r
-               if (is_array($stmt) && sizeof($stmt) >= 5) {\r
-                       $this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR);\r
-                       if ($params) {\r
-                               foreach($params as $k => $v) {\r
-                                       $this->Parameter($stmt,$params[$k], $k);\r
-                               }\r
-                       }\r
-               }\r
-               return $this->Execute($stmt);\r
-       }\r
-       \r
-       /*\r
-               Bind a variable -- very, very fast for executing repeated statements in oracle. \r
-               Better than using\r
-                       for ($i = 0; $i < $max; $i++) { \r
-                               $p1 = ?; $p2 = ?; $p3 = ?;\r
-                               $this->Execute("insert into table (col0, col1, col2) values (:0, :1, :2)", \r
-                                       array($p1,$p2,$p3));\r
-                       }\r
-               \r
-               Usage:\r
-                       $stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)");\r
-                       $DB->Bind($stmt, $p1);\r
-                       $DB->Bind($stmt, $p2);\r
-                       $DB->Bind($stmt, $p3);\r
-                       for ($i = 0; $i < $max; $i++) { \r
-                               $p1 = ?; $p2 = ?; $p3 = ?;\r
-                               $DB->Execute($stmt);\r
-                       }\r
-                       \r
-               Some timings:           \r
-                       ** Test table has 3 cols, and 1 index. Test to insert 1000 records\r
-                       Time 0.6081s (1644.60 inserts/sec) with direct OCIParse/OCIExecute\r
-                       Time 0.6341s (1577.16 inserts/sec) with ADOdb Prepare/Bind/Execute\r
-                       Time 1.5533s ( 643.77 inserts/sec) with pure SQL using Execute\r
-                       \r
-               Now if PHP only had batch/bulk updating like Java or PL/SQL...\r
-       \r
-               Note that the order of parameters differs from OCIBindByName,\r
-               because we default the names to :0, :1, :2\r
-       */\r
-       function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false)\r
-       {\r
-               if (!is_array($stmt)) return false;\r
-        \r
-        if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) { \r
-            return OCIBindByName($stmt[1],":".$name,$stmt[4],$size,$type);\r
-        }\r
-        \r
-               if ($name == false) {\r
-                       if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type);\r
-                       else $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator\r
-                       $stmt[2] += 1;\r
-               } else {\r
-                       if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type);\r
-                       else $rez = OCIBindByName($stmt[1],":".$name,$var,$size); // +1 byte for null terminator\r
-               }\r
-               \r
-               return $rez;\r
-       }\r
-       \r
-       function Param($name)\r
-       {\r
-               return ':'.$name;\r
-       }\r
-       \r
-       /* \r
-       Usage:\r
-               $stmt = $db->Prepare('select * from table where id =:myid and group=:group');\r
-               $db->Parameter($stmt,$id,'myid');\r
-               $db->Parameter($stmt,$group,'group');\r
-               $db->Execute($stmt);\r
-               \r
-               @param $stmt Statement returned by Prepare() or PrepareSP().\r
-               @param $var PHP variable to bind to\r
-               @param $name Name of stored procedure variable name to bind to.\r
-               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.\r
-               @param [$maxLen] Holds an maximum length of the variable.\r
-               @param [$type] The data type of $var. Legal values depend on driver.\r
-               \r
-               See OCIBindByName documentation at php.net.\r
-       */\r
-       function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)\r
-       {\r
-                       if  ($this->debug) {\r
-                               $prefix = ($isOutput) ? 'Out' : 'In';\r
-                               $ztype = (empty($type)) ? 'false' : $type;\r
-                               ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");\r
-                       }\r
-                       return $this->Bind($stmt,$var,$maxLen,$type,$name);\r
-       }\r
-       \r
-       /*\r
-       returns query ID if successful, otherwise false\r
-       this version supports:\r
-       \r
-          1. $db->execute('select * from table');\r
-          \r
-          2. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');\r
-                 $db->execute($prepared_statement, array(1,2,3));\r
-                 \r
-          3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3));\r
-          \r
-          4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');\r
-                 $db->$bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3); \r
-                 $db->execute($stmt);\r
-       */ \r
-       function _query($sql,$inputarr)\r
-       {\r
-               \r
-               if (is_array($sql)) { // is prepared sql\r
-                       $stmt = $sql[1];\r
-                       \r
-                       // we try to bind to permanent array, so that OCIBindByName is persistent\r
-                       // and carried out once only - note that max array element size is 4000 chars\r
-                       if (is_array($inputarr)) {\r
-                               $bindpos = $sql[3];\r
-                               if (isset($this->_bind[$bindpos])) {\r
-                               // all tied up already\r
-                                       $bindarr = &$this->_bind[$bindpos];\r
-                               } else {\r
-                               // one statement to bind them all\r
-                                       $bindarr = array();\r
-                                       foreach($inputarr as $k => $v) {\r
-                                               $bindarr[$k] = $v;\r
-                                               OCIBindByName($stmt,":$k",$bindarr[$k],4000);\r
-                                       }\r
-                                       $this->_bind[$bindpos] = &$bindarr;\r
-                               }\r
-                       }\r
-               } else {\r
-                       $stmt=OCIParse($this->_connectionID,$sql);\r
-               }\r
-                       \r
-               $this->_stmt = $stmt;\r
-               if (!$stmt) return false;\r
-       \r
-               if (defined('ADODB_PREFETCH_ROWS')) @OCISetPrefetch($stmt,ADODB_PREFETCH_ROWS);\r
-                       \r
-               if (is_array($inputarr)) {\r
-                       foreach($inputarr as $k => $v) {\r
-                               if (is_array($v)) {\r
-                                       if (sizeof($v) == 2) // suggested by g.giunta@libero.\r
-                                               OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);\r
-                                       else\r
-                                               OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);\r
-                                       \r
-                                       if ($this->debug==99) echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>';\r
-                               } else {\r
-                                       $len = -1;\r
-                                       if ($v === ' ') $len = 1;\r
-                                       if (isset($bindarr)) {  // is prepared sql, so no need to ocibindbyname again\r
-                                               $bindarr[$k] = $v;\r
-                                       } else {                                // dynamic sql, so rebind every time\r
-                                               OCIBindByName($stmt,":$k",$inputarr[$k],$len);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-               \r
-        $this->_errorMsg = false;\r
-               $this->_errorCode = false;\r
-               if (OCIExecute($stmt,$this->_commit)) {\r
-               \r
-            switch (@OCIStatementType($stmt)) {\r
-                case "SELECT":\r
-                                       return $stmt;\r
-                                       \r
-                case "BEGIN":\r
-                    if (is_array($sql) && !empty($sql[4])) {\r
-                                               $cursor = $sql[4];\r
-                                               if (is_resource($cursor)) {\r
-                                                       $ok = OCIExecute($cursor);      \r
-                               return $cursor;\r
-                                               }\r
-                                               return $stmt;\r
-                    } else {\r
-                                               if (is_resource($stmt)) {\r
-                                                       OCIFreeStatement($stmt);\r
-                                                       return true;\r
-                                               }\r
-                        return $stmt;\r
-                    }\r
-                    break;\r
-                default :\r
-                                       // ociclose -- no because it could be used in a LOB?\r
-                    return true;\r
-            }\r
-               }\r
-               return false;\r
-       }\r
-       \r
-       // returns true or false\r
-       function _close()\r
-       {\r
-               if (!$this->autoCommit) OCIRollback($this->_connectionID);\r
-               OCILogoff($this->_connectionID);\r
-               $this->_stmt = false;\r
-               $this->_connectionID = false;\r
-       }\r
-       \r
-       function MetaPrimaryKeys($table, $owner=false,$internalKey=false)\r
-       {\r
-               if ($internalKey) return array('ROWID');\r
-               \r
-       // tested with oracle 8.1.7\r
-               $table = strtoupper($table);\r
-               if ($owner) {\r
-                       $owner_clause = "AND ((a.OWNER = b.OWNER) AND (a.OWNER = UPPER('$owner')))";\r
-                       $ptab = 'ALL_';\r
-               } else {\r
-                       $owner_clause = '';\r
-                       $ptab = 'USER_';\r
-               }\r
-               $sql = "\r
-SELECT /*+ RULE */ distinct b.column_name\r
-   FROM {$ptab}CONSTRAINTS a\r
-         , {$ptab}CONS_COLUMNS b\r
-  WHERE ( UPPER(b.table_name) = ('$table'))\r
-       AND (UPPER(a.table_name) = ('$table') and a.constraint_type = 'P')\r
-       $owner_clause\r
-       AND (a.constraint_name = b.constraint_name)";\r
-\r
-               $rs = $this->Execute($sql);\r
-               if ($rs && !$rs->EOF) {\r
-                       $arr =& $rs->GetArray();\r
-                       $a = array();\r
-                       foreach($arr as $v) {\r
-                               $a[] = reset($v);\r
-                       }\r
-                       return $a;\r
-               }\r
-               else return false;\r
-       }\r
-       \r
-       // http://gis.mit.edu/classes/11.521/sqlnotes/referential_integrity.html\r
-       function MetaForeignKeys($table, $owner=false)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $table = $this->qstr(strtoupper($table));\r
-               if (!$owner) {\r
-                       $owner = $this->user;\r
-                       $tabp = 'user_';\r
-               } else\r
-                       $tabp = 'all_';\r
-                       \r
-               $owner = ' and owner='.$this->qstr(strtoupper($owner));\r
-               \r
-               $sql = \r
-"select constraint_name,r_owner,r_constraint_name \r
-       from {$tabp}constraints\r
-       where constraint_type = 'R' and table_name = $table $owner";\r
-               \r
-               $constraints =& $this->GetArray($sql);\r
-               $arr = false;\r
-               foreach($constraints as $constr) {\r
-                       $cons = $this->qstr($constr[0]);\r
-                       $rowner = $this->qstr($constr[1]);\r
-                       $rcons = $this->qstr($constr[2]);\r
-                       $cols = $this->GetArray("select column_name from {$tabp}cons_columns where constraint_name=$cons $owner order by position");\r
-                       $tabcol = $this->GetArray("select table_name,column_name from {$tabp}cons_columns where owner=$rowner and constraint_name=$rcons order by position");\r
-                       \r
-                       if ($cols && $tabcol) \r
-                               for ($i=0, $max=sizeof($cols); $i < $max; $i++) {\r
-                                       $arr[$tabcol[$i][0]] = $cols[$i][0].'='.$tabcol[$i][1];\r
-                               }\r
-               }\r
-               $ADODB_FETCH_MODE = $save;\r
-               \r
-               return $arr;\r
-       }\r
-\r
-       \r
-       function CharMax()\r
-       {\r
-               return 4000;\r
-       }\r
-       \r
-       function TextMax()\r
-       {\r
-               return 4000;\r
-       }\r
-       \r
-       /**\r
-        * Quotes a string.\r
-        * An example is  $db->qstr("Don't bother",magic_quotes_runtime());\r
-        * \r
-        * @param s                     the string to quote\r
-        * @param [magic_quotes]        if $s is GET/POST var, set to get_magic_quotes_gpc().\r
-        *                              This undoes the stupidity of magic quotes for GPC.\r
-        *\r
-        * @return  quoted string to be sent back to database\r
-        */\r
-       function qstr($s,$magic_quotes=false)\r
-       {       \r
-       $nofixquotes=false;\r
-       \r
-               if (is_array($s)) adodb_backtrace();\r
-               if ($this->noNullStrings && strlen($s)==0)$s = ' ';\r
-               if (!$magic_quotes) {   \r
-                       if ($this->replaceQuote[0] == '\\'){\r
-                               $s = str_replace('\\','\\\\',$s);\r
-                       }\r
-                       return  "'".str_replace("'",$this->replaceQuote,$s)."'";\r
-               }\r
-               \r
-               // undo magic quotes for "\r
-               $s = str_replace('\\"','"',$s);\r
-               \r
-               if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything\r
-                       return "'$s'";\r
-               else {// change \' to '' for sybase/mssql\r
-                       $s = str_replace('\\\\','\\',$s);\r
-                       return "'".str_replace("\\'",$this->replaceQuote,$s)."'";\r
-               }\r
-       }\r
-       \r
-}\r
-\r
-/*--------------------------------------------------------------------------------------\r
-                Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordset_oci8 extends ADORecordSet {\r
-\r
-       var $databaseType = 'oci8';\r
-       var $bind=false;\r
-       var $_fieldobjs;\r
-       //var $_arr = false;\r
-               \r
-       function ADORecordset_oci8($queryID,$mode=false)\r
-       {\r
-               if ($mode === false) { \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               switch ($mode)\r
-               {\r
-               default:\r
-               case ADODB_FETCH_NUM: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;\r
-               case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;\r
-               case ADODB_FETCH_DEFAULT:\r
-               case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;\r
-               }\r
-\r
-               $this->_queryID = $queryID;\r
-       }\r
-\r
-\r
-       function Init()\r
-       {\r
-               if ($this->_inited) return;\r
-               \r
-               $this->_inited = true;\r
-               if ($this->_queryID) {\r
-                       \r
-                       $this->_currentRow = 0;\r
-                       @$this->_initrs();\r
-                       $this->EOF = !$this->_fetch();\r
-                       \r
-                       /*\r
-                       // based on idea by Gaetano Giunta to detect unusual oracle errors\r
-                       // see http://phplens.com/lens/lensforum/msgs.php?id=6771\r
-                       $err = OCIError($this->_queryID);\r
-                       if ($err && $this->connection->debug) ADOConnection::outp($err);\r
-                       */\r
-                       \r
-                       if (!is_array($this->fields)) {\r
-                               $this->_numOfRows = 0;\r
-                               $this->fields = array();\r
-                       }\r
-               } else {\r
-                       $this->fields = array();\r
-                       $this->_numOfRows = 0;\r
-                       $this->_numOfFields = 0;\r
-                       $this->EOF = true;\r
-               }\r
-       }\r
-       \r
-       function _initrs()\r
-       {\r
-               $this->_numOfRows = -1;\r
-               $this->_numOfFields = OCInumcols($this->_queryID);\r
-               if ($this->_numOfFields>0) {\r
-                       $this->_fieldobjs = array();\r
-                       $max = $this->_numOfFields;\r
-                       for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i);\r
-               }\r
-       }\r
-\r
-         /*            Returns: an object containing field information.\r
-                         Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
-                         fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
-                         fetchField() is retrieved.            */\r
-\r
-       function &_FetchField($fieldOffset = -1)\r
-       {\r
-               $fld = new ADOFieldObject;\r
-               $fieldOffset += 1;\r
-               $fld->name =OCIcolumnname($this->_queryID, $fieldOffset);\r
-               $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);\r
-               $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);\r
-               if ($fld->type == 'NUMBER') {\r
-                       $p = OCIColumnPrecision($this->_queryID, $fieldOffset);\r
-                       $sc = OCIColumnScale($this->_queryID, $fieldOffset);\r
-                       if ($p != 0 && $sc == 0) $fld->type = 'INT';\r
-                       //echo " $this->name ($p.$sc) ";\r
-               }\r
-               return $fld;\r
-       }\r
-       \r
-       /* For some reason, OCIcolumnname fails when called after _initrs() so we cache it */\r
-       function &FetchField($fieldOffset = -1)\r
-       {\r
-               return $this->_fieldobjs[$fieldOffset];\r
-       }\r
-       \r
-       \r
-       // 10% speedup to move MoveNext to child class\r
-       function MoveNext() \r
-       {\r
-       //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return @adodb_movenext($this);\r
-               \r
-               if ($this->EOF) return false;\r
-               \r
-               $this->_currentRow++;\r
-               if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode))\r
-                       return true;\r
-               $this->EOF = true;\r
-               \r
-               return false;\r
-       }       \r
-       \r
-       /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */\r
-       function &GetArrayLimit($nrows,$offset=-1) \r
-       {\r
-               if ($offset <= 0) {\r
-                       $arr =& $this->GetArray($nrows);\r
-                       return $arr;\r
-               }\r
-               for ($i=1; $i < $offset; $i++) \r
-                       if (!@OCIFetch($this->_queryID)) return array();\r
-                       \r
-               if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();\r
-               $results = array();\r
-               $cnt = 0;\r
-               while (!$this->EOF && $nrows != $cnt) {\r
-                       $results[$cnt++] = $this->fields;\r
-                       $this->MoveNext();\r
-               }\r
-               \r
-               return $results;\r
-       }\r
-\r
-       \r
-       /* Use associative array to get fields array */\r
-       function Fields($colname)\r
-       {\r
-               if (!$this->bind) {\r
-                       $this->bind = array();\r
-                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                               $o = $this->FetchField($i);\r
-                               $this->bind[strtoupper($o->name)] = $i;\r
-                       }\r
-               }\r
-               \r
-                return $this->fields[$this->bind[strtoupper($colname)]];\r
-       }\r
-       \r
-\r
-\r
-       function _seek($row)\r
-       {\r
-               return false;\r
-       }\r
-\r
-       function _fetch() \r
-       {\r
-               return OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);\r
-       }\r
-\r
-       /*              close() only needs to be called if you are worried about using too much memory while your script\r
-                       is running. All associated result memory for the specified result identifier will automatically be freed.               */\r
-\r
-       function _close() \r
-       {\r
-               if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false;\r
-               OCIFreeStatement($this->_queryID);\r
-               $this->_queryID = false;\r
-               \r
-       }\r
-\r
-       function MetaType($t,$len=-1)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               switch (strtoupper($t)) {\r
-               case 'VARCHAR':\r
-               case 'VARCHAR2':\r
-               case 'CHAR':\r
-               case 'VARBINARY':\r
-               case 'BINARY':\r
-               case 'NCHAR':\r
-               case 'NVARCHAR':\r
-               case 'NVARCHAR2':\r
-                                if (isset($this) && $len <= $this->blobSize) return 'C';\r
-               \r
-               case 'NCLOB':\r
-               case 'LONG':\r
-               case 'LONG VARCHAR':\r
-               case 'CLOB':\r
-               return 'X';\r
-               \r
-               case 'LONG RAW':\r
-               case 'LONG VARBINARY':\r
-               case 'BLOB':\r
-                       return 'B';\r
-               \r
-               case 'DATE': \r
-                       return  ($this->connection->datetime) ? 'T' : 'D';\r
-               \r
-               \r
-               case 'TIMESTAMP': return 'T';\r
-               \r
-               case 'INT': \r
-               case 'SMALLINT':\r
-               case 'INTEGER': \r
-                       return 'I';\r
-                       \r
-               default: return 'N';\r
-               }\r
-       }\r
-}\r
+<?php
+/*
+
+  version V4.20 22 Feb 2004 (c) 2000-2004 John Lim. All rights reserved.
+
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+
+  Latest version is available at http://php.weblogs.com/
+  
+  Code contributed by George Fourlanos <fou@infomap.gr>
+  
+  13 Nov 2000 jlim - removed all ora_* references.
+*/
+
+/*
+NLS_Date_Format
+Allows you to use a date format other than the Oracle Lite default. When a literal
+character string appears where a date value is expected, the Oracle Lite database
+tests the string to see if it matches the formats of Oracle, SQL-92, or the value
+specified for this parameter in the POLITE.INI file. Setting this parameter also
+defines the default format used in the TO_CHAR or TO_DATE functions when no
+other format string is supplied.
+
+For Oracle the default is dd-mon-yy or dd-mon-yyyy, and for SQL-92 the default is
+yy-mm-dd or yyyy-mm-dd.
+
+Using 'RR' in the format forces two-digit years less than or equal to 49 to be
+interpreted as years in the 21st century (2000\962049), and years over 50 as years in
+the 20th century (1950\961999). Setting the RR format as the default for all two-digit
+year entries allows you to become year-2000 compliant. For example:
+NLS_DATE_FORMAT='RR-MM-DD'
+
+You can also modify the date format using the ALTER SESSION command. 
+*/
+
+class ADODB_oci8 extends ADOConnection {
+       var $databaseType = 'oci8';
+       var $dataProvider = 'oci8';
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $concat_operator='||';
+       var $sysDate = "TRUNC(SYSDATE)";
+       var $sysTimeStamp = 'SYSDATE';
+       var $metaDatabasesSQL = "SELECT USERNAME FROM ALL_USERS WHERE USERNAME NOT IN ('SYS','SYSTEM','DBSNMP','OUTLN') ORDER BY 1";
+       var $_stmt;
+       var $_commit = OCI_COMMIT_ON_SUCCESS;
+       var $_initdate = true; // init date to YYYY-MM-DD
+       var $metaTablesSQL = "select table_name,table_type from cat where table_type in ('TABLE','VIEW')";
+       var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net
+       var $_bindInputArray = true;
+       var $hasGenID = true;
+       var $_genIDSQL = "SELECT (%s.nextval) FROM DUAL";
+       var $_genSeqSQL = "CREATE SEQUENCE %s START WITH %s";
+       var $_dropSeqSQL = "DROP SEQUENCE %s";
+       var $hasAffectedRows = true;
+       var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)";
+       var $noNullStrings = false;
+       var $connectSID = false;
+       var $_bind = false;
+       var $_hasOCIFetchStatement = false;
+       var $_getarray = false; // currently not working
+       var $leftOuter = '';  // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER
+       var $session_sharing_force_blob = false; // alter session on updateblob if set to true 
+       var $firstrows = true; // enable first rows optimization on SelectLimit()
+       var $selectOffsetAlg1 = 100; // when to use 1st algorithm of selectlimit.
+       var $NLS_DATE_FORMAT = 'YYYY-MM-DD';  // To include time, use 'RRRR-MM-DD HH24:MI:SS'
+       var $useDBDateFormatForTextInput=false;
+       var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true)
+       
+       // var $ansiOuter = true; // if oracle9
+    
+       function ADODB_oci8() 
+       {
+               $this->_hasOCIFetchStatement = ADODB_PHPVER >= 0x4200;
+       }
+       
+       /*  Function &MetaColumns($table) added by smondino@users.sourceforge.net*/
+       function &MetaColumns($table) 
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+               
+               $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
+               
+               if (isset($savem)) $this->SetFetchMode($savem);
+               $ADODB_FETCH_MODE = $save;
+               if (!$rs) return false;
+               $retarr = array();
+               while (!$rs->EOF) { //print_r($rs->fields);
+                       $fld = new ADOFieldObject();
+                       $fld->name = $rs->fields[0];
+                       $fld->type = $rs->fields[1];
+                       $fld->max_length = $rs->fields[2];
+                       $fld->scale = $rs->fields[3];
+                       if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) {
+                               $fld->type ='INT';
+                       $fld->max_length = $rs->fields[4];
+               }       
+                       $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);
+                       $fld->binary = (strpos($fld->type,'BLOB') !== false);
+                       $fld->default_value = $rs->fields[6];
+                       
+                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     
+                       else $retarr[strtoupper($fld->name)] = $fld;
+                       $rs->MoveNext();
+               }
+               $rs->Close();
+               return $retarr;
+       }
+/*
+
+  Multiple modes of connection are supported:
+  
+  a. Local Database
+    $conn->Connect(false,'scott','tiger');
+  
+  b. From tnsnames.ora
+    $conn->Connect(false,'scott','tiger',$tnsname); 
+    $conn->Connect($tnsname,'scott','tiger'); 
+  
+  c. Server + service name
+    $conn->Connect($serveraddress,'scott,'tiger',$service_name);
+  
+  d. Server + SID
+       $conn->connectSID = true;
+       $conn->Connect($serveraddress,'scott,'tiger',$SID);
+
+
+Example TNSName:
+---------------
+NATSOFT.DOMAIN =
+  (DESCRIPTION =
+       (ADDRESS_LIST =
+         (ADDRESS = (PROTOCOL = TCP)(HOST = kermit)(PORT = 1523))
+       )
+       (CONNECT_DATA =
+         (SERVICE_NAME = natsoft.domain)
+       )
+  )
+  
+  There are 3 connection modes, 0 = non-persistent, 1 = persistent, 2 = force new connection
+       
+*/
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$mode=0)
+       {
+               if (!function_exists('OCIPLogon')) return false;
+               
+               
+        $this->_errorMsg = false;
+               $this->_errorCode = false;
+               
+               if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>
+                       if (empty($argDatabasename)) $argDatabasename = $argHostname;
+                       else {
+                               if(strpos($argHostname,":")) {
+                                       $argHostinfo=explode(":",$argHostname);
+                                       $argHostname=$argHostinfo[0];
+                                       $argHostport=$argHostinfo[1];
+                               } else {
+                                       $argHostport="1521";
+                               }
+                               
+                               if ($this->connectSID) {
+                                       $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
+                                       .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
+                               } else
+                                       $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
+                                       .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";
+                       }
+               }
+                               
+               //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
+               if ($mode==1) {
+                       $this->_connectionID = OCIPLogon($argUsername,$argPassword, $argDatabasename);
+                       if ($this->_connectionID && $this->autoRollback)  OCIrollback($this->_connectionID);
+               } else if ($mode==2) {
+                       $this->_connectionID = OCINLogon($argUsername,$argPassword, $argDatabasename);
+               } else {
+                       $this->_connectionID = OCILogon($argUsername,$argPassword, $argDatabasename);
+               }
+               if ($this->_connectionID === false) return false;
+               if ($this->_initdate) {
+                       $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");
+               }
+               
+               // looks like: 
+               // Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production With the Partitioning option JServer Release 8.1.7.0.0 - Production
+               // $vers = OCIServerVersion($this->_connectionID);
+               // if (strpos($vers,'8i') !== false) $this->ansiOuter = true;
+               return true;
+       }
+       
+       function ServerInfo()
+       {
+               $arr['compat'] = $this->GetOne('select value from sys.database_compatible_level');
+               $arr['description'] = @OCIServerVersion($this->_connectionID);
+               $arr['version'] = ADOConnection::_findvers($arr['description']);
+               return $arr;
+       }
+               // returns true or false
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,1);
+       }
+       
+       
+       
+       // returns true or false
+       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,2);
+       }
+       
+       function _affectedrows()
+       {
+               if (is_resource($this->_stmt)) return @OCIRowCount($this->_stmt);
+               return 0;
+       }
+       
+       function IfNull( $field, $ifNull ) 
+       {
+               return " NVL($field, $ifNull) "; // if Oracle
+       }
+       
+       // format and return date string in database date format
+       function DBDate($d)
+       {
+               if (empty($d) && $d !== 0) return 'null';
+               
+               if (is_string($d)) $d = ADORecordSet::UnixDate($d);
+               return "TO_DATE(".adodb_date($this->fmtDate,$d).",'".$this->NLS_DATE_FORMAT."')";
+       }
+
+       
+       // format and return date string in database timestamp format
+       function DBTimeStamp($ts)
+       {
+               if (empty($ts) && $ts !== 0) return 'null';
+               if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts);
+               return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";
+       }
+       
+       function RowLock($tables,$where) 
+       {
+               if ($this->autoCommit) $this->BeginTrans();
+               return $this->GetOne("select 1 as ignore from $tables where $where for update");
+       }
+       
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+       {
+               if ($mask) {
+                       $save = $this->metaTablesSQL;
+                       $mask = $this->qstr(strtoupper($mask));
+                       $this->metaTablesSQL .= " AND table_name like $mask";
+               }
+               $ret =& ADOConnection::MetaTables($ttype,$showSchema);
+               
+               if ($mask) {
+                       $this->metaTablesSQL = $save;
+               }
+               return $ret;
+       }
+       
+       function BeginTrans()
+       {       
+               if ($this->transOff) return true;
+               $this->transCnt += 1;
+               $this->autoCommit = false;
+               $this->_commit = OCI_DEFAULT;
+               return true;
+       }
+       
+       function CommitTrans($ok=true) 
+       { 
+               if ($this->transOff) return true;
+               if (!$ok) return $this->RollbackTrans();
+               
+               if ($this->transCnt) $this->transCnt -= 1;
+               $ret = OCIcommit($this->_connectionID);
+               $this->_commit = OCI_COMMIT_ON_SUCCESS;
+               $this->autoCommit = true;
+               return $ret;
+       }
+       
+       function RollbackTrans()
+       {
+               if ($this->transOff) return true;
+               if ($this->transCnt) $this->transCnt -= 1;
+               $ret = OCIrollback($this->_connectionID);
+               $this->_commit = OCI_COMMIT_ON_SUCCESS;
+               $this->autoCommit = true;
+               return $ret;
+       }
+       
+       
+       function SelectDB($dbName) 
+       {
+               return false;
+       }
+
+       function ErrorMsg() 
+       {
+               if ($this->_errorMsg !== false) return $this->_errorMsg;
+
+               if (is_resource($this->_stmt)) $arr = @OCIerror($this->_stmt);
+               if (empty($arr)) {
+                       $arr = @OCIerror($this->_connectionID);
+                       if ($arr === false) $arr = @OCIError();
+                       if ($arr === false) return '';
+               }
+               $this->_errorMsg = $arr['message'];
+               $this->_errorCode = $arr['code'];
+               return $this->_errorMsg;
+       }
+
+       function ErrorNo() 
+       {
+               if ($this->_errorCode !== false) return $this->_errorCode;
+               
+               if (is_resource($this->_stmt)) $arr = @OCIError($this->_stmt);
+               if (empty($arr)) {
+                       $arr = @OCIError($this->_connectionID);
+                       if ($arr == false) $arr = @OCIError();
+                       if ($arr == false) return '';
+               }
+               
+               $this->_errorMsg = $arr['message'];
+               $this->_errorCode = $arr['code'];
+               
+               return $arr['code'];
+       }
+       
+       // Format date column in sql string given an input format that understands Y M D
+       function SQLDate($fmt, $col=false)
+       {       
+               if (!$col) $col = $this->sysTimeStamp;
+               $s = 'TO_CHAR('.$col.",'";
+               
+               $len = strlen($fmt);
+               for ($i=0; $i < $len; $i++) {
+                       $ch = $fmt[$i];
+                       switch($ch) {
+                       case 'Y':
+                       case 'y':
+                               $s .= 'YYYY';
+                               break;
+                       case 'Q':
+                       case 'q':
+                               $s .= 'Q';
+                               break;
+                               
+                       case 'M':
+                               $s .= 'Mon';
+                               break;
+                               
+                       case 'm':
+                               $s .= 'MM';
+                               break;
+                       case 'D':
+                       case 'd':
+                               $s .= 'DD';
+                               break;
+                       
+                       case 'H':
+                               $s.= 'HH24';
+                               break;
+                               
+                       case 'h':
+                               $s .= 'HH';
+                               break;
+                               
+                       case 'i':
+                               $s .= 'MI';
+                               break;
+                       
+                       case 's':
+                               $s .= 'SS';
+                               break;
+                       
+                       case 'a':
+                       case 'A':
+                               $s .= 'AM';
+                               break;
+                               
+                       default:
+                       // handle escape characters...
+                               if ($ch == '\\') {
+                                       $i++;
+                                       $ch = substr($fmt,$i,1);
+                               }
+                               if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
+                               else $s .= '"'.$ch.'"';
+                               
+                       }
+               }
+               return $s. "')";
+       }
+       
+       
+       /*
+       This algorithm makes use of
+       
+       a. FIRST_ROWS hint
+       The FIRST_ROWS hint explicitly chooses the approach to optimize response time, 
+       that is, minimum resource usage to return the first row. Results will be returned 
+       as soon as they are identified. 
+
+       b. Uses rownum tricks to obtain only the required rows from a given offset.
+        As this uses complicated sql statements, we only use this if the $offset >= 100. 
+        This idea by Tomas V V Cox.
+        
+        This implementation does not appear to work with oracle 8.0.5 or earlier. Comment
+        out this function then, and the slower SelectLimit() in the base class will be used.
+       */
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+       {
+               // seems that oracle only supports 1 hint comment in 8i
+               if ($this->firstrows) {
+                       if (strpos($sql,'/*+') !== false)
+                               $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);
+                       else
+                               $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
+               }
+               
+               if ($offset < $this->selectOffsetAlg1) {
+                       if ($nrows > 0) {       
+                               if ($offset > 0) $nrows += $offset;
+                               //$inputarr['adodb_rownum'] = $nrows;
+                               if ($this->databaseType == 'oci8po') {
+                                       $sql = "select * from ($sql) where rownum <= ?";
+                               } else {
+                                       $sql = "select * from ($sql) where rownum <= :adodb_offset";
+                               } 
+                               $inputarr['adodb_offset'] = $nrows;
+                               $nrows = -1;
+                       }
+                       // note that $nrows = 0 still has to work ==> no rows returned
+
+                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+                       return $rs;
+                       
+               } else {
+                        // Algorithm by Tomas V V Cox, from PEAR DB oci8.php
+                       
+                        // Let Oracle return the name of the columns
+                        $q_fields = "SELECT * FROM ($sql) WHERE NULL = NULL";
+                        if (!$stmt = OCIParse($this->_connectionID, $q_fields)) {
+                                return false;
+                        }
+                        
+                        if (is_array($inputarr)) {
+                               foreach($inputarr as $k => $v) {
+                                       if (is_array($v)) {
+                                               if (sizeof($v) == 2) // suggested by g.giunta@libero.
+                                                       OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);
+                                               else
+                                                       OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);
+                                       } else {
+                                               $len = -1;
+                                               if ($v === ' ') $len = 1;
+                                               if (isset($bindarr)) {  // is prepared sql, so no need to ocibindbyname again
+                                                       $bindarr[$k] = $v;
+                                               } else {                                // dynamic sql, so rebind every time
+                                                       OCIBindByName($stmt,":$k",$inputarr[$k],$len);
+                                               }
+                                       }
+                               }
+                       }
+                       
+                        if (!OCIExecute($stmt, OCI_DEFAULT)) {
+                                OCIFreeStatement($stmt); 
+                                return false;
+                        }
+                        
+                        $ncols = OCINumCols($stmt);
+                        for ( $i = 1; $i <= $ncols; $i++ ) {
+                                $cols[] = '"'.OCIColumnName($stmt, $i).'"';
+                        }
+                        $result = false;
+                       
+                        OCIFreeStatement($stmt); 
+                        $fields = implode(',', $cols);
+                        $nrows += $offset;
+                        $offset += 1; // in Oracle rownum starts at 1
+                       
+                       if ($this->databaseType == 'oci8po') {
+                                        $sql = "SELECT $fields FROM".
+                                         "(SELECT rownum as adodb_rownum, $fields FROM".
+                                         " ($sql) WHERE rownum <= ?".
+                                         ") WHERE adodb_rownum >= ?";
+                               } else {
+                                        $sql = "SELECT $fields FROM".
+                                         "(SELECT rownum as adodb_rownum, $fields FROM".
+                                         " ($sql) WHERE rownum <= :adodb_nrows".
+                                         ") WHERE adodb_rownum >= :adodb_offset";
+                               } 
+                               $inputarr['adodb_nrows'] = $nrows;
+                               $inputarr['adodb_offset'] = $offset;
+                               
+                       if ($secs2cache>0) $rs =& $this->CacheExecute($secs2cache, $sql,$inputarr);
+                       else $rs =& $this->Execute($sql,$inputarr);
+                       return $rs;
+               }
+       
+       }
+       
+       /**
+       * Usage:
+       * Store BLOBs and CLOBs
+       *
+       * Example: to store $var in a blob
+       *
+       *       $conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())');
+       *       $conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB');
+       *       
+       *       $blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'.
+       *
+       *  to get length of LOB:
+       *       select DBMS_LOB.GETLENGTH(ablob) from TABLE
+       *
+       * If you are using CURSOR_SHARING = force, it appears this will case a segfault
+       * under oracle 8.1.7.0. Run:
+       *        $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
+       * before UpdateBlob() then...
+       */
+
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+       {
+               
+               //if (strlen($val) < 4000) return $this->Execute("UPDATE $table SET $column=:blob WHERE $where",array('blob'=>$val)) != false;
+               
+               switch(strtoupper($blobtype)) {
+               default: ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
+               case 'BLOB': $type = OCI_B_BLOB; break;
+               case 'CLOB': $type = OCI_B_CLOB; break;
+               }
+               
+               if ($this->databaseType == 'oci8po') 
+                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
+               else 
+                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
+               
+               $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);
+               $arr['blob'] = array($desc,-1,$type);
+               if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
+               $commit = $this->autoCommit;
+               if ($commit) $this->BeginTrans();
+               $rs = ADODB_oci8::Execute($sql,$arr);
+               if ($rez = !empty($rs)) $desc->save($val);
+               $desc->free();
+               if ($commit) $this->CommitTrans();
+               if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE');
+               
+               if ($rez) $rs->Close();
+               return $rez;
+       }
+       
+       /**
+       * Usage:  store file pointed to by $var in a blob
+       */
+       function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB')
+       {
+               switch(strtoupper($blobtype)) {
+               default: ADOConnection::outp( "<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
+               case 'BLOB': $type = OCI_B_BLOB; break;
+               case 'CLOB': $type = OCI_B_CLOB; break;
+               }
+               
+               if ($this->databaseType == 'oci8po') 
+                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
+               else 
+                       $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
+               
+               $desc = OCINewDescriptor($this->_connectionID, OCI_D_LOB);
+               $arr['blob'] = array($desc,-1,$type);
+               
+               $this->BeginTrans();
+               $rs = ADODB_oci8::Execute($sql,$arr);
+               if ($rez = !empty($rs)) $desc->savefile($val);
+               $desc->free();
+               $this->CommitTrans();
+               
+               if ($rez) $rs->Close();
+               return $rez;
+       }
+       
+       /*
+               Example of usage:
+               
+               $stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
+       */
+       function Prepare($sql,$cursor=false)
+       {
+       static $BINDNUM = 0;
+       
+               $stmt = OCIParse($this->_connectionID,$sql);
+
+               if (!$stmt) return false;
+
+               $BINDNUM += 1;
+               
+               if (@OCIStatementType($stmt) == 'BEGIN') {
+                       return array($sql,$stmt,0,$BINDNUM, ($cursor) ? OCINewCursor($this->_connectionID) : false);
+               } 
+               
+               return array($sql,$stmt,0,$BINDNUM);
+       }
+       
+       /*
+               Call an oracle stored procedure and return a cursor variable. 
+               Convert the cursor variable into a recordset. 
+               Concept by Robert Tuttle robert@ud.com
+               
+               Example:
+                       Note: we return a cursor variable in :RS2
+                       $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS2); END;",'RS2');
+                       
+                       $rs = $db->ExecuteCursor(
+                               "BEGIN :RS2 = adodb.getdata(:VAR1); END;", 
+                               'RS2',
+                               array('VAR1' => 'Mr Bean'));
+                       
+       */
+       function &ExecuteCursor($sql,$cursorName='rs',$params=false)
+       {
+               $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate OCINewCursor
+                       
+               if (is_array($stmt) && sizeof($stmt) >= 5) {
+                       $this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR);
+                       if ($params) {
+                               foreach($params as $k => $v) {
+                                       $this->Parameter($stmt,$params[$k], $k);
+                               }
+                       }
+               }
+               return $this->Execute($stmt);
+       }
+       
+       /*
+               Bind a variable -- very, very fast for executing repeated statements in oracle. 
+               Better than using
+                       for ($i = 0; $i < $max; $i++) { 
+                               $p1 = ?; $p2 = ?; $p3 = ?;
+                               $this->Execute("insert into table (col0, col1, col2) values (:0, :1, :2)", 
+                                       array($p1,$p2,$p3));
+                       }
+               
+               Usage:
+                       $stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)");
+                       $DB->Bind($stmt, $p1);
+                       $DB->Bind($stmt, $p2);
+                       $DB->Bind($stmt, $p3);
+                       for ($i = 0; $i < $max; $i++) { 
+                               $p1 = ?; $p2 = ?; $p3 = ?;
+                               $DB->Execute($stmt);
+                       }
+                       
+               Some timings:           
+                       ** Test table has 3 cols, and 1 index. Test to insert 1000 records
+                       Time 0.6081s (1644.60 inserts/sec) with direct OCIParse/OCIExecute
+                       Time 0.6341s (1577.16 inserts/sec) with ADOdb Prepare/Bind/Execute
+                       Time 1.5533s ( 643.77 inserts/sec) with pure SQL using Execute
+                       
+               Now if PHP only had batch/bulk updating like Java or PL/SQL...
+       
+               Note that the order of parameters differs from OCIBindByName,
+               because we default the names to :0, :1, :2
+       */
+       function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false)
+       {
+               if (!is_array($stmt)) return false;
+        
+        if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) { 
+            return OCIBindByName($stmt[1],":".$name,$stmt[4],$size,$type);
+        }
+        
+               if ($name == false) {
+                       if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type);
+                       else $rez = OCIBindByName($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator
+                       $stmt[2] += 1;
+               } else {
+                       if ($type !== false) $rez = OCIBindByName($stmt[1],":".$name,$var,$size,$type);
+                       else $rez = OCIBindByName($stmt[1],":".$name,$var,$size); // +1 byte for null terminator
+               }
+               
+               return $rez;
+       }
+       
+       function Param($name)
+       {
+               return ':'.$name;
+       }
+       
+       /* 
+       Usage:
+               $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
+               $db->Parameter($stmt,$id,'myid');
+               $db->Parameter($stmt,$group,'group');
+               $db->Execute($stmt);
+               
+               @param $stmt Statement returned by Prepare() or PrepareSP().
+               @param $var PHP variable to bind to
+               @param $name Name of stored procedure variable name to bind to.
+               @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
+               @param [$maxLen] Holds an maximum length of the variable.
+               @param [$type] The data type of $var. Legal values depend on driver.
+               
+               See OCIBindByName documentation at php.net.
+       */
+       function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
+       {
+                       if  ($this->debug) {
+                               $prefix = ($isOutput) ? 'Out' : 'In';
+                               $ztype = (empty($type)) ? 'false' : $type;
+                               ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");
+                       }
+                       return $this->Bind($stmt,$var,$maxLen,$type,$name);
+       }
+       
+       /*
+       returns query ID if successful, otherwise false
+       this version supports:
+       
+          1. $db->execute('select * from table');
+          
+          2. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
+                 $db->execute($prepared_statement, array(1,2,3));
+                 
+          3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3));
+          
+          4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
+                 $db->$bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3); 
+                 $db->execute($stmt);
+       */ 
+       function _query($sql,$inputarr)
+       {
+               
+               if (is_array($sql)) { // is prepared sql
+                       $stmt = $sql[1];
+                       
+                       // we try to bind to permanent array, so that OCIBindByName is persistent
+                       // and carried out once only - note that max array element size is 4000 chars
+                       if (is_array($inputarr)) {
+                               $bindpos = $sql[3];
+                               if (isset($this->_bind[$bindpos])) {
+                               // all tied up already
+                                       $bindarr = &$this->_bind[$bindpos];
+                               } else {
+                               // one statement to bind them all
+                                       $bindarr = array();
+                                       foreach($inputarr as $k => $v) {
+                                               $bindarr[$k] = $v;
+                                               OCIBindByName($stmt,":$k",$bindarr[$k],4000);
+                                       }
+                                       $this->_bind[$bindpos] = &$bindarr;
+                               }
+                       }
+               } else {
+                       $stmt=OCIParse($this->_connectionID,$sql);
+               }
+                       
+               $this->_stmt = $stmt;
+               if (!$stmt) return false;
+       
+               if (defined('ADODB_PREFETCH_ROWS')) @OCISetPrefetch($stmt,ADODB_PREFETCH_ROWS);
+                       
+               if (is_array($inputarr)) {
+                       foreach($inputarr as $k => $v) {
+                               if (is_array($v)) {
+                                       if (sizeof($v) == 2) // suggested by g.giunta@libero.
+                                               OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);
+                                       else
+                                               OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);
+                                       
+                                       if ($this->debug==99) echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>';
+                               } else {
+                                       $len = -1;
+                                       if ($v === ' ') $len = 1;
+                                       if (isset($bindarr)) {  // is prepared sql, so no need to ocibindbyname again
+                                               $bindarr[$k] = $v;
+                                       } else {                                // dynamic sql, so rebind every time
+                                               OCIBindByName($stmt,":$k",$inputarr[$k],$len);
+                                       }
+                               }
+                       }
+               }
+               
+        $this->_errorMsg = false;
+               $this->_errorCode = false;
+               if (OCIExecute($stmt,$this->_commit)) {
+               
+            switch (@OCIStatementType($stmt)) {
+                case "SELECT":
+                                       return $stmt;
+                                       
+                case "BEGIN":
+                    if (is_array($sql) && !empty($sql[4])) {
+                                               $cursor = $sql[4];
+                                               if (is_resource($cursor)) {
+                                                       $ok = OCIExecute($cursor);      
+                               return $cursor;
+                                               }
+                                               return $stmt;
+                    } else {
+                                               if (is_resource($stmt)) {
+                                                       OCIFreeStatement($stmt);
+                                                       return true;
+                                               }
+                        return $stmt;
+                    }
+                    break;
+                default :
+                                       // ociclose -- no because it could be used in a LOB?
+                    return true;
+            }
+               }
+               return false;
+       }
+       
+       // returns true or false
+       function _close()
+       {
+               if (!$this->autoCommit) OCIRollback($this->_connectionID);
+               OCILogoff($this->_connectionID);
+               $this->_stmt = false;
+               $this->_connectionID = false;
+       }
+       
+       function MetaPrimaryKeys($table, $owner=false,$internalKey=false)
+       {
+               if ($internalKey) return array('ROWID');
+               
+       // tested with oracle 8.1.7
+               $table = strtoupper($table);
+               if ($owner) {
+                       $owner_clause = "AND ((a.OWNER = b.OWNER) AND (a.OWNER = UPPER('$owner')))";
+                       $ptab = 'ALL_';
+               } else {
+                       $owner_clause = '';
+                       $ptab = 'USER_';
+               }
+               $sql = "
+SELECT /*+ RULE */ distinct b.column_name
+   FROM {$ptab}CONSTRAINTS a
+         , {$ptab}CONS_COLUMNS b
+  WHERE ( UPPER(b.table_name) = ('$table'))
+       AND (UPPER(a.table_name) = ('$table') and a.constraint_type = 'P')
+       $owner_clause
+       AND (a.constraint_name = b.constraint_name)";
+
+               $rs = $this->Execute($sql);
+               if ($rs && !$rs->EOF) {
+                       $arr =& $rs->GetArray();
+                       $a = array();
+                       foreach($arr as $v) {
+                               $a[] = reset($v);
+                       }
+                       return $a;
+               }
+               else return false;
+       }
+       
+       // http://gis.mit.edu/classes/11.521/sqlnotes/referential_integrity.html
+       function MetaForeignKeys($table, $owner=false)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $table = $this->qstr(strtoupper($table));
+               if (!$owner) {
+                       $owner = $this->user;
+                       $tabp = 'user_';
+               } else
+                       $tabp = 'all_';
+                       
+               $owner = ' and owner='.$this->qstr(strtoupper($owner));
+               
+               $sql = 
+"select constraint_name,r_owner,r_constraint_name 
+       from {$tabp}constraints
+       where constraint_type = 'R' and table_name = $table $owner";
+               
+               $constraints =& $this->GetArray($sql);
+               $arr = false;
+               foreach($constraints as $constr) {
+                       $cons = $this->qstr($constr[0]);
+                       $rowner = $this->qstr($constr[1]);
+                       $rcons = $this->qstr($constr[2]);
+                       $cols = $this->GetArray("select column_name from {$tabp}cons_columns where constraint_name=$cons $owner order by position");
+                       $tabcol = $this->GetArray("select table_name,column_name from {$tabp}cons_columns where owner=$rowner and constraint_name=$rcons order by position");
+                       
+                       if ($cols && $tabcol) 
+                               for ($i=0, $max=sizeof($cols); $i < $max; $i++) {
+                                       $arr[$tabcol[$i][0]] = $cols[$i][0].'='.$tabcol[$i][1];
+                               }
+               }
+               $ADODB_FETCH_MODE = $save;
+               
+               return $arr;
+       }
+
+       
+       function CharMax()
+       {
+               return 4000;
+       }
+       
+       function TextMax()
+       {
+               return 4000;
+       }
+       
+       /**
+        * Quotes a string.
+        * An example is  $db->qstr("Don't bother",magic_quotes_runtime());
+        * 
+        * @param s                     the string to quote
+        * @param [magic_quotes]        if $s is GET/POST var, set to get_magic_quotes_gpc().
+        *                              This undoes the stupidity of magic quotes for GPC.
+        *
+        * @return  quoted string to be sent back to database
+        */
+       function qstr($s,$magic_quotes=false)
+       {       
+       $nofixquotes=false;
+       
+               if (is_array($s)) adodb_backtrace();
+               if ($this->noNullStrings && strlen($s)==0)$s = ' ';
+               if (!$magic_quotes) {   
+                       if ($this->replaceQuote[0] == '\\'){
+                               $s = str_replace('\\','\\\\',$s);
+                       }
+                       return  "'".str_replace("'",$this->replaceQuote,$s)."'";
+               }
+               
+               // undo magic quotes for "
+               $s = str_replace('\\"','"',$s);
+               
+               if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything
+                       return "'$s'";
+               else {// change \' to '' for sybase/mssql
+                       $s = str_replace('\\\\','\\',$s);
+                       return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
+               }
+       }
+       
+}
+
+/*--------------------------------------------------------------------------------------
+                Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_oci8 extends ADORecordSet {
+
+       var $databaseType = 'oci8';
+       var $bind=false;
+       var $_fieldobjs;
+       //var $_arr = false;
+               
+       function ADORecordset_oci8($queryID,$mode=false)
+       {
+               if ($mode === false) { 
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               switch ($mode)
+               {
+               default:
+               case ADODB_FETCH_NUM: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
+               case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
+               case ADODB_FETCH_DEFAULT:
+               case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break;
+               }
+
+               $this->_queryID = $queryID;
+       }
+
+
+       function Init()
+       {
+               if ($this->_inited) return;
+               
+               $this->_inited = true;
+               if ($this->_queryID) {
+                       
+                       $this->_currentRow = 0;
+                       @$this->_initrs();
+                       $this->EOF = !$this->_fetch();
+                       
+                       /*
+                       // based on idea by Gaetano Giunta to detect unusual oracle errors
+                       // see http://phplens.com/lens/lensforum/msgs.php?id=6771
+                       $err = OCIError($this->_queryID);
+                       if ($err && $this->connection->debug) ADOConnection::outp($err);
+                       */
+                       
+                       if (!is_array($this->fields)) {
+                               $this->_numOfRows = 0;
+                               $this->fields = array();
+                       }
+               } else {
+                       $this->fields = array();
+                       $this->_numOfRows = 0;
+                       $this->_numOfFields = 0;
+                       $this->EOF = true;
+               }
+       }
+       
+       function _initrs()
+       {
+               $this->_numOfRows = -1;
+               $this->_numOfFields = OCInumcols($this->_queryID);
+               if ($this->_numOfFields>0) {
+                       $this->_fieldobjs = array();
+                       $max = $this->_numOfFields;
+                       for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i);
+               }
+       }
+
+         /*            Returns: an object containing field information.
+                         Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+                         fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+                         fetchField() is retrieved.            */
+
+       function &_FetchField($fieldOffset = -1)
+       {
+               $fld = new ADOFieldObject;
+               $fieldOffset += 1;
+               $fld->name =OCIcolumnname($this->_queryID, $fieldOffset);
+               $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
+               $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
+               if ($fld->type == 'NUMBER') {
+                       $p = OCIColumnPrecision($this->_queryID, $fieldOffset);
+                       $sc = OCIColumnScale($this->_queryID, $fieldOffset);
+                       if ($p != 0 && $sc == 0) $fld->type = 'INT';
+                       //echo " $this->name ($p.$sc) ";
+               }
+               return $fld;
+       }
+       
+       /* For some reason, OCIcolumnname fails when called after _initrs() so we cache it */
+       function &FetchField($fieldOffset = -1)
+       {
+               return $this->_fieldobjs[$fieldOffset];
+       }
+       
+       
+       // 10% speedup to move MoveNext to child class
+       function MoveNext() 
+       {
+       //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return @adodb_movenext($this);
+               
+               if ($this->EOF) return false;
+               
+               $this->_currentRow++;
+               if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode))
+                       return true;
+               $this->EOF = true;
+               
+               return false;
+       }       
+       
+       /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
+       function &GetArrayLimit($nrows,$offset=-1) 
+       {
+               if ($offset <= 0) {
+                       $arr =& $this->GetArray($nrows);
+                       return $arr;
+               }
+               for ($i=1; $i < $offset; $i++) 
+                       if (!@OCIFetch($this->_queryID)) return array();
+                       
+               if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();
+               $results = array();
+               $cnt = 0;
+               while (!$this->EOF && $nrows != $cnt) {
+                       $results[$cnt++] = $this->fields;
+                       $this->MoveNext();
+               }
+               
+               return $results;
+       }
+
+       
+       /* Use associative array to get fields array */
+       function Fields($colname)
+       {
+               if (!$this->bind) {
+                       $this->bind = array();
+                       for ($i=0; $i < $this->_numOfFields; $i++) {
+                               $o = $this->FetchField($i);
+                               $this->bind[strtoupper($o->name)] = $i;
+                       }
+               }
+               
+                return $this->fields[$this->bind[strtoupper($colname)]];
+       }
+       
+
+
+       function _seek($row)
+       {
+               return false;
+       }
+
+       function _fetch() 
+       {
+               return @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);
+       }
+
+       /*              close() only needs to be called if you are worried about using too much memory while your script
+                       is running. All associated result memory for the specified result identifier will automatically be freed.               */
+
+       function _close() 
+       {
+               if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false;
+               OCIFreeStatement($this->_queryID);
+               $this->_queryID = false;
+               
+       }
+
+       function MetaType($t,$len=-1)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               switch (strtoupper($t)) {
+               case 'VARCHAR':
+               case 'VARCHAR2':
+               case 'CHAR':
+               case 'VARBINARY':
+               case 'BINARY':
+               case 'NCHAR':
+               case 'NVARCHAR':
+               case 'NVARCHAR2':
+                                if (isset($this) && $len <= $this->blobSize) return 'C';
+               
+               case 'NCLOB':
+               case 'LONG':
+               case 'LONG VARCHAR':
+               case 'CLOB':
+               return 'X';
+               
+               case 'LONG RAW':
+               case 'LONG VARBINARY':
+               case 'BLOB':
+                       return 'B';
+               
+               case 'DATE': 
+                       return  ($this->connection->datetime) ? 'T' : 'D';
+               
+               
+               case 'TIMESTAMP': return 'T';
+               
+               case 'INT': 
+               case 'SMALLINT':
+               case 'INTEGER': 
+                       return 'I';
+                       
+               default: return 'N';
+               }
+       }
+}
 ?>
\ No newline at end of file
index 4dde2b363b8f07d1c1ff23a69cc49c42202d91fc..51f61d44ccabbb924dbef3d08e9acc23302b3701 100644 (file)
@@ -1,56 +1,56 @@
-<?php\r
-/** \r
- * @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license. \r
- * Whenever there is any discrepancy between the two licenses, \r
- * the BSD license will take precedence. \r
- *\r
- * Set tabs to 4 for best viewing.\r
- * \r
- * Latest version is available at http://php.weblogs.com\r
- *\r
- * Oracle 8.0.5 driver\r
-*/\r
-\r
-include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');\r
-\r
-class ADODB_oci805 extends ADODB_oci8 {\r
-       var $databaseType = "oci805";   \r
-       var $connectSID = true;\r
-       \r
-       function ADODB_oci805() \r
-       {\r
-               $this->ADODB_oci8();\r
-       }\r
-       \r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
-       {\r
-               // seems that oracle only supports 1 hint comment in 8i\r
-               if (strpos($sql,'/*+') !== false)\r
-                       $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);\r
-               else\r
-                       $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);\r
-               \r
-               /* \r
-                       The following is only available from 8.1.5 because order by in inline views not \r
-                       available before then...\r
-                       http://www.jlcomp.demon.co.uk/faq/top_sql.html\r
-               if ($nrows > 0) {       \r
-                       if ($offset > 0) $nrows += $offset;\r
-                       $sql = "select * from ($sql) where rownum <= $nrows";\r
-                       $nrows = -1;\r
-               }\r
-               */\r
-\r
-               return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
-       }\r
-}\r
-\r
-class ADORecordset_oci805 extends ADORecordset_oci8 {  \r
-       var $databaseType = "oci805";\r
-       function ADORecordset_oci805($id,$mode=false)\r
-       {\r
-               $this->ADORecordset_oci8($id,$mode);\r
-       }\r
-}\r
+<?php
+/** 
+ * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com
+ *
+ * Oracle 8.0.5 driver
+*/
+
+include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');
+
+class ADODB_oci805 extends ADODB_oci8 {
+       var $databaseType = "oci805";   
+       var $connectSID = true;
+       
+       function ADODB_oci805() 
+       {
+               $this->ADODB_oci8();
+       }
+       
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+       {
+               // seems that oracle only supports 1 hint comment in 8i
+               if (strpos($sql,'/*+') !== false)
+                       $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);
+               else
+                       $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
+               
+               /* 
+                       The following is only available from 8.1.5 because order by in inline views not 
+                       available before then...
+                       http://www.jlcomp.demon.co.uk/faq/top_sql.html
+               if ($nrows > 0) {       
+                       if ($offset > 0) $nrows += $offset;
+                       $sql = "select * from ($sql) where rownum <= $nrows";
+                       $nrows = -1;
+               }
+               */
+
+               return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+       }
+}
+
+class ADORecordset_oci805 extends ADORecordset_oci8 {  
+       var $databaseType = "oci805";
+       function ADORecordset_oci805($id,$mode=false)
+       {
+               $this->ADORecordset_oci8($id,$mode);
+       }
+}
 ?>
\ No newline at end of file
index 2d91f8a722fe2df6f48ea84512587649a97edd83..1cccd8efe392627d28ef66d35cd820f690a7d4d7 100644 (file)
-<?php\r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim. All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-\r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Portable version of oci8 driver, to make it more similar to other database drivers.\r
-  The main differences are\r
-\r
-   1. that the OCI_ASSOC names are in lowercase instead of uppercase.\r
-   2. bind variables are mapped using ? instead of :<bindvar>\r
-\r
-   Should some emulation of RecordCount() be implemented?\r
-  \r
-*/\r
-\r
-include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');\r
-\r
-class ADODB_oci8po extends ADODB_oci8 {\r
-       var $databaseType = 'oci8po';\r
-       var $dataProvider = 'oci8';\r
-       var $metaColumnsSQL = "select lower(cname),coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net\r
-       var $metaTablesSQL = "select lower(table_name),table_type from cat where table_type in ('TABLE','VIEW')";\r
-       \r
-       function ADODB_oci8po()\r
-       {\r
-               $this->ADODB_oci8();\r
-       }\r
-       \r
-       function Param($name)\r
-       {\r
-               return '?';\r
-       }\r
-       \r
-       function Prepare($sql)\r
-       {\r
-               $sqlarr = explode('?',$sql);\r
-               $sql = $sqlarr[0];\r
-               for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {\r
-                       $sql .=  ':'.($i-1) . $sqlarr[$i];\r
-               } \r
-               return ADODB_oci8::Prepare($sql);\r
-       }\r
-       \r
-       // emulate handling of parameters ? ?, replacing with :bind0 :bind1\r
-       function _query($sql,$inputarr)\r
-       {\r
-               if (is_array($inputarr)) {\r
-                       $i = 0;\r
-                       if (is_array($sql)) {\r
-                               foreach($inputarr as $v) {\r
-                                       $arr['bind'.$i++] = $v;\r
-                               } \r
-                       } else {\r
-                               $sqlarr = explode('?',$sql);\r
-                               $sql = $sqlarr[0];\r
-                               foreach($inputarr as $k => $v) {\r
-                                       $sql .=  ":$k" . $sqlarr[++$i];\r
-                               }\r
-                       }\r
-               }\r
-               return ADODB_oci8::_query($sql,$inputarr);\r
-       }\r
-}\r
-\r
-/*--------------------------------------------------------------------------------------\r
-                Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordset_oci8po extends ADORecordset_oci8 {\r
-\r
-       var $databaseType = 'oci8po';\r
-       \r
-               function ADORecordset_oci8po($queryID,$mode=false)\r
-               {\r
-                       $this->ADORecordset_oci8($queryID,$mode);\r
-               }\r
-\r
-               function Fields($colname)\r
-               {\r
-                       if ($this->fetchMode & OCI_ASSOC) return $this->fields[$colname];\r
-                       \r
-                       if (!$this->bind) {\r
-                               $this->bind = array();\r
-                               for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                                       $o = $this->FetchField($i);\r
-                                       $this->bind[strtoupper($o->name)] = $i;\r
-                               }\r
-                       }\r
-                        return $this->fields[$this->bind[strtoupper($colname)]];\r
-               }\r
-               \r
-               // lowercase field names...\r
-               function &_FetchField($fieldOffset = -1)\r
-               {\r
-                                $fld = new ADOFieldObject;\r
-                                $fieldOffset += 1;\r
-                                $fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset));\r
-                                $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);\r
-                                $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);\r
-                                if ($fld->type == 'NUMBER') {\r
-                                       //$p = OCIColumnPrecision($this->_queryID, $fieldOffset);\r
-                                       $sc = OCIColumnScale($this->_queryID, $fieldOffset);\r
-                                       if ($sc == 0) $fld->type = 'INT';\r
-                                }\r
-                                return $fld;\r
-               }\r
-\r
-       // 10% speedup to move MoveNext to child class\r
-       function MoveNext() \r
-       {\r
-       \r
-               if (!$this->EOF) {              \r
-                       $this->_currentRow++;\r
-                       if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {\r
-                       global $ADODB_ANSI_PADDING_OFF;\r
-       \r
-                               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();\r
-                               if (!empty($ADODB_ANSI_PADDING_OFF)) {\r
-                                       foreach($this->fields as $k => $v) {\r
-                                               if (is_string($v)) $this->fields[$k] = rtrim($v);\r
-                                       }\r
-                               }\r
-                               return true;\r
-                       }\r
-                       $this->EOF = true;\r
-               }\r
-               return false;\r
-       }       \r
-       \r
-       /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */\r
-       function &GetArrayLimit($nrows,$offset=-1) \r
-       {\r
-               if ($offset <= 0) return $this->GetArray($nrows);\r
-               for ($i=1; $i < $offset; $i++) \r
-                       if (!@OCIFetch($this->_queryID)) return array();\r
-                       \r
-               if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();\r
-               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();\r
-               $results = array();\r
-               $cnt = 0;\r
-               while (!$this->EOF && $nrows != $cnt) {\r
-                       $results[$cnt++] = $this->fields;\r
-                       $this->MoveNext();\r
-               }\r
-               \r
-               return $results;\r
-       }\r
-\r
-       // Create associative array\r
-       function _updatefields()\r
-       {\r
-               if (ADODB_ASSOC_CASE == 2) return; // native\r
-       \r
-               $arr = array();\r
-               $lowercase = (ADODB_ASSOC_CASE == 0);\r
-               \r
-               foreach($this->fields as $k => $v) {\r
-                       if (is_integer($k)) $arr[$k] = $v;\r
-                       else {\r
-                               if ($lowercase)\r
-                                       $arr[strtolower($k)] = $v;\r
-                               else\r
-                                       $arr[strtoupper($k)] = $v;\r
-                       }\r
-               }\r
-               $this->fields = $arr;\r
-       }\r
-       \r
-       function _fetch() \r
-       {\r
-               $ret = @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);\r
-               if ($ret) {\r
-               global $ADODB_ANSI_PADDING_OFF;\r
-       \r
-                               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();\r
-                               if (!empty($ADODB_ANSI_PADDING_OFF)) {\r
-                                       foreach($this->fields as $k => $v) {\r
-                                               if (is_string($v)) $this->fields[$k] = rtrim($v);\r
-                                       }\r
-                               }\r
-               }\r
-               return $ret;\r
-       }\r
-       \r
-}\r
+<?php
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim. All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+
+  Latest version is available at http://php.weblogs.com/
+  
+  Portable version of oci8 driver, to make it more similar to other database drivers.
+  The main differences are
+
+   1. that the OCI_ASSOC names are in lowercase instead of uppercase.
+   2. bind variables are mapped using ? instead of :<bindvar>
+
+   Should some emulation of RecordCount() be implemented?
+  
+*/
+
+include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');
+
+class ADODB_oci8po extends ADODB_oci8 {
+       var $databaseType = 'oci8po';
+       var $dataProvider = 'oci8';
+       var $metaColumnsSQL = "select lower(cname),coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net
+       var $metaTablesSQL = "select lower(table_name),table_type from cat where table_type in ('TABLE','VIEW')";
+       
+       function ADODB_oci8po()
+       {
+               $this->ADODB_oci8();
+       }
+       
+       function Param($name)
+       {
+               return '?';
+       }
+       
+       function Prepare($sql,$cursor=false)
+       {
+               $sqlarr = explode('?',$sql);
+               $sql = $sqlarr[0];
+               for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {
+                       $sql .=  ':'.($i-1) . $sqlarr[$i];
+               } 
+               return ADODB_oci8::Prepare($sql,$cursor);
+       }
+       
+       // emulate handling of parameters ? ?, replacing with :bind0 :bind1
+       function _query($sql,$inputarr)
+       {
+               if (is_array($inputarr)) {
+                       $i = 0;
+                       if (is_array($sql)) {
+                               foreach($inputarr as $v) {
+                                       $arr['bind'.$i++] = $v;
+                               } 
+                       } else {
+                               $sqlarr = explode('?',$sql);
+                               $sql = $sqlarr[0];
+                               foreach($inputarr as $k => $v) {
+                                       $sql .=  ":$k" . $sqlarr[++$i];
+                               }
+                       }
+               }
+               return ADODB_oci8::_query($sql,$inputarr);
+       }
+}
+
+/*--------------------------------------------------------------------------------------
+                Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_oci8po extends ADORecordset_oci8 {
+
+       var $databaseType = 'oci8po';
+       
+               function ADORecordset_oci8po($queryID,$mode=false)
+               {
+                       $this->ADORecordset_oci8($queryID,$mode);
+               }
+
+               function Fields($colname)
+               {
+                       if ($this->fetchMode & OCI_ASSOC) return $this->fields[$colname];
+                       
+                       if (!$this->bind) {
+                               $this->bind = array();
+                               for ($i=0; $i < $this->_numOfFields; $i++) {
+                                       $o = $this->FetchField($i);
+                                       $this->bind[strtoupper($o->name)] = $i;
+                               }
+                       }
+                        return $this->fields[$this->bind[strtoupper($colname)]];
+               }
+               
+               // lowercase field names...
+               function &_FetchField($fieldOffset = -1)
+               {
+                                $fld = new ADOFieldObject;
+                                $fieldOffset += 1;
+                                $fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset));
+                                $fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
+                                $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
+                                if ($fld->type == 'NUMBER') {
+                                       //$p = OCIColumnPrecision($this->_queryID, $fieldOffset);
+                                       $sc = OCIColumnScale($this->_queryID, $fieldOffset);
+                                       if ($sc == 0) $fld->type = 'INT';
+                                }
+                                return $fld;
+               }
+
+       // 10% speedup to move MoveNext to child class
+       function MoveNext() 
+       {
+       
+               if (!$this->EOF) {              
+                       $this->_currentRow++;
+                       if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
+                       global $ADODB_ANSI_PADDING_OFF;
+       
+                               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
+                               if (!empty($ADODB_ANSI_PADDING_OFF)) {
+                                       foreach($this->fields as $k => $v) {
+                                               if (is_string($v)) $this->fields[$k] = rtrim($v);
+                                       }
+                               }
+                               return true;
+                       }
+                       $this->EOF = true;
+               }
+               return false;
+       }       
+       
+       /* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
+       function &GetArrayLimit($nrows,$offset=-1) 
+       {
+               if ($offset <= 0) return $this->GetArray($nrows);
+               for ($i=1; $i < $offset; $i++) 
+                       if (!@OCIFetch($this->_queryID)) return array();
+                       
+               if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();
+               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
+               $results = array();
+               $cnt = 0;
+               while (!$this->EOF && $nrows != $cnt) {
+                       $results[$cnt++] = $this->fields;
+                       $this->MoveNext();
+               }
+               
+               return $results;
+       }
+
+       // Create associative array
+       function _updatefields()
+       {
+               if (ADODB_ASSOC_CASE == 2) return; // native
+       
+               $arr = array();
+               $lowercase = (ADODB_ASSOC_CASE == 0);
+               
+               foreach($this->fields as $k => $v) {
+                       if (is_integer($k)) $arr[$k] = $v;
+                       else {
+                               if ($lowercase)
+                                       $arr[strtolower($k)] = $v;
+                               else
+                                       $arr[strtoupper($k)] = $v;
+                       }
+               }
+               $this->fields = $arr;
+       }
+       
+       function _fetch() 
+       {
+               $ret = @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);
+               if ($ret) {
+               global $ADODB_ANSI_PADDING_OFF;
+       
+                               if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
+                               if (!empty($ADODB_ANSI_PADDING_OFF)) {
+                                       foreach($this->fields as $k => $v) {
+                                               if (is_string($v)) $this->fields[$k] = rtrim($v);
+                                       }
+                               }
+               }
+               return $ret;
+       }
+       
+}
 ?>
\ No newline at end of file
index aff3efa390f4cf15d86cc66d4f4c125e37411bf0..79aadef54b44f6fcf2698a82d7c26c56d8baf886 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Requires ODBC. Works on Windows and Unix.\r
-*/\r
-  define("_ADODB_ODBC_LAYER", 2 );\r
-        \r
-/*--------------------------------------------------------------------------------------\r
---------------------------------------------------------------------------------------*/\r
-\r
-\r
-class ADODB_odbc extends ADOConnection {\r
-       var $databaseType = "odbc";     \r
-       var $fmtDate = "'Y-m-d'";\r
-       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $dataProvider = "odbc";\r
-       var $hasAffectedRows = true;\r
-       var $binmode = ODBC_BINMODE_RETURN;\r
-       var $useFetchArray = false; // setting this to true will make array elements in FETCH_ASSOC mode case-sensitive\r
-                                                               // breaking backward-compat\r
-       //var $longreadlen = 8000; // default number of chars to return for a Blob/Long field\r
-       var $_bindInputArray = false;   \r
-       var $curmode = SQL_CUR_USE_DRIVER; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L\r
-       var $_genSeqSQL = "create table %s (id integer)";\r
-       var $_autocommit = true;\r
-       var $_haserrorfunctions = true;\r
-       var $_has_stupid_odbc_fetch_api_change = true;\r
-       var $_lastAffectedRows = 0;\r
-       \r
-       function ADODB_odbc() \r
-       {       \r
-               $this->_haserrorfunctions = ADODB_PHPVER >= 0x4050;\r
-               $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;\r
-       }\r
-       \r
-       function ServerInfo()\r
-       {\r
-       \r
-               if (!empty($this->host) && ADODB_PHPVER >= 0x4300) {\r
-                       $dsn = strtoupper($this->host);\r
-                       $first = true;\r
-                       $found = false;\r
-                       \r
-                       if (!function_exists('odbc_data_source')) return false;\r
-                       \r
-                       while(true) {\r
-                               \r
-                               $rez = odbc_data_source($this->_connectionID,\r
-                                       $first ? SQL_FETCH_FIRST : SQL_FETCH_NEXT);\r
-                               $first = false;\r
-                               if (!is_array($rez)) break;\r
-                               if (strtoupper($rez['server']) == $dsn) {\r
-                                       $found = true;\r
-                                       break;\r
-                               }\r
-                       } \r
-                       if (!$found) return ADOConnection::ServerInfo();\r
-                       if (!isset($rez['version'])) $rez['version'] = '';\r
-                       return $rez;\r
-               } else {\r
-                       return ADOConnection::ServerInfo();\r
-               }\r
-       }\r
-\r
-       \r
-       function CreateSequence($seqname='adodbseq',$start=1)\r
-       {\r
-               if (empty($this->_genSeqSQL)) return false;\r
-               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
-               if (!$ok) return false;\r
-               $start -= 1;\r
-               return $this->Execute("insert into $seqname values($start)");\r
-       }\r
-       \r
-       var $_dropSeqSQL = 'drop table %s';\r
-       function DropSequence($seqname)\r
-       {\r
-               if (empty($this->_dropSeqSQL)) return false;\r
-               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));\r
-       }\r
-       \r
-       /*\r
-               This algorithm is not very efficient, but works even if table locking\r
-               is not available.\r
-               \r
-               Will return false if unable to generate an ID after $MAXLOOPS attempts.\r
-       */\r
-       function GenID($seq='adodbseq',$start=1)\r
-       {       \r
-               // if you have to modify the parameter below, your database is overloaded,\r
-               // or you need to implement generation of id's yourself!\r
-               $MAXLOOPS = 100;\r
-               //$this->debug=1;\r
-               while (--$MAXLOOPS>=0) {\r
-                       $num = $this->GetOne("select id from $seq");\r
-                       if ($num === false) {\r
-                               $this->Execute(sprintf($this->_genSeqSQL ,$seq));       \r
-                               $start -= 1;\r
-                               $num = '0';\r
-                               $ok = $this->Execute("insert into $seq values($start)");\r
-                               if (!$ok) return false;\r
-                       } \r
-                       $this->Execute("update $seq set id=id+1 where id=$num");\r
-                       \r
-                       if ($this->affected_rows() > 0) {\r
-                               $num += 1;\r
-                               $this->genID = $num;\r
-                               return $num;\r
-                       }\r
-               }\r
-               if ($fn = $this->raiseErrorFn) {\r
-                       $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);\r
-               }\r
-               return false;\r
-       }\r
-\r
-\r
-       function ErrorMsg()\r
-       {\r
-               if ($this->_haserrorfunctions) {\r
-                       if ($this->_errorMsg !== false) return $this->_errorMsg;\r
-                       if (empty($this->_connectionID)) return @odbc_errormsg();\r
-                       return @odbc_errormsg($this->_connectionID);\r
-               } else return ADOConnection::ErrorMsg();\r
-       }\r
-       \r
-       function ErrorNo()\r
-       {\r
-               \r
-               if ($this->_haserrorfunctions) {\r
-                       if ($this->_errorCode !== false) {\r
-                               // bug in 4.0.6, error number can be corrupted string (should be 6 digits)\r
-                               return (strlen($this->_errorCode)<=2) ? 0 : $this->_errorCode;\r
-                       }\r
-\r
-                       if (empty($this->_connectionID)) $e = @odbc_error(); \r
-                       else $e = @odbc_error($this->_connectionID);\r
-                       \r
-                        // bug in 4.0.6, error number can be corrupted string (should be 6 digits)\r
-                        // so we check and patch\r
-                       if (strlen($e)<=2) return 0;\r
-                       return $e;\r
-               } else return ADOConnection::ErrorNo();\r
-       }\r
-       \r
-       \r
-       // returns true or false\r
-       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-       global $php_errormsg;\r
-               \r
-               if (!function_exists('odbc_connect')) return false;\r
-               \r
-               if ($this->debug && $argDatabasename) {\r
-                       ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter.");\r
-               }\r
-               $php_errormsg = '';\r
-               if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);\r
-               else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode);\r
-               $this->_errorMsg = $php_errormsg;\r
-               if (isset($this->connectStmt)) $this->Execute($this->connectStmt);\r
-               \r
-               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
-               return $this->_connectionID != false;\r
-       }\r
-       \r
-       // returns true or false\r
-       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-       global $php_errormsg;\r
-       \r
-               if (!function_exists('odbc_connect')) return false;\r
-               \r
-               $php_errormsg = '';\r
-               if ($this->debug && $argDatabasename) {\r
-                       ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");\r
-               }\r
-       //      print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();\r
-               if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);\r
-               else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);\r
-               \r
-               $this->_errorMsg = $php_errormsg;\r
-               if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID);\r
-               if (isset($this->connectStmt)) $this->Execute($this->connectStmt);\r
-               \r
-               return $this->_connectionID != false;\r
-       }\r
-\r
-       function BeginTrans()\r
-       {       \r
-               if (!$this->hasTransactions) return false;\r
-               if ($this->transOff) return true; \r
-               $this->transCnt += 1;\r
-               $this->_autocommit = false;\r
-               return odbc_autocommit($this->_connectionID,false);\r
-       }\r
-       \r
-       function CommitTrans($ok=true) \r
-       { \r
-               if ($this->transOff) return true; \r
-               if (!$ok) return $this->RollbackTrans();\r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $this->_autocommit = true;\r
-               $ret = odbc_commit($this->_connectionID);\r
-               odbc_autocommit($this->_connectionID,true);\r
-               return $ret;\r
-       }\r
-       \r
-       function RollbackTrans()\r
-       {\r
-               if ($this->transOff) return true; \r
-               if ($this->transCnt) $this->transCnt -= 1;\r
-               $this->_autocommit = true;\r
-               $ret = odbc_rollback($this->_connectionID);\r
-               odbc_autocommit($this->_connectionID,true);\r
-               return $ret;\r
-       }\r
-       \r
-       function MetaPrimaryKeys($table)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $savem = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $qid = @odbc_primarykeys($this->_connectionID,'','',$table);\r
-               \r
-               if (!$qid) {\r
-                       $ADODB_FETCH_MODE = $savem;\r
-                       return false;\r
-               }\r
-               $rs = new ADORecordSet_odbc($qid);\r
-               $ADODB_FETCH_MODE = $savem;\r
-               \r
-               if (!$rs) return false;\r
-               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
-               \r
-               $arr =& $rs->GetArray();\r
-               $rs->Close();\r
-               //print_r($arr);\r
-               $arr2 = array();\r
-               for ($i=0; $i < sizeof($arr); $i++) {\r
-                       if ($arr[$i][3]) $arr2[] = $arr[$i][3];\r
-               }\r
-               return $arr2;\r
-       }\r
-       \r
-       \r
-       \r
-       function &MetaTables($ttype=false)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $savem = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $qid = odbc_tables($this->_connectionID);\r
-               \r
-               $rs = new ADORecordSet_odbc($qid);\r
-               \r
-               $ADODB_FETCH_MODE = $savem;\r
-               if (!$rs) return false;\r
-               \r
-               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
-               \r
-               $arr =& $rs->GetArray();\r
-               //print_r($arr);\r
-               \r
-               $rs->Close();\r
-               $arr2 = array();\r
-               \r
-               if ($ttype) {\r
-                       $isview = strncmp($ttype,'V',1) === 0;\r
-               }\r
-               for ($i=0; $i < sizeof($arr); $i++) {\r
-                       if (!$arr[$i][2]) continue;\r
-                       $type = $arr[$i][3];\r
-                       if ($ttype) { \r
-                               if ($isview) {\r
-                                       if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];\r
-                               } else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];\r
-                       } else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];\r
-               }\r
-               return $arr2;\r
-       }\r
-       \r
-/*\r
-/ SQL data type codes /\r
-#define        SQL_UNKNOWN_TYPE        0\r
-#define SQL_CHAR                       1\r
-#define SQL_NUMERIC             2\r
-#define SQL_DECIMAL             3\r
-#define SQL_INTEGER             4\r
-#define SQL_SMALLINT           5\r
-#define SQL_FLOAT                 6\r
-#define SQL_REAL                       7\r
-#define SQL_DOUBLE               8\r
-#if (ODBCVER >= 0x0300)\r
-#define SQL_DATETIME           9\r
-#endif\r
-#define SQL_VARCHAR            12\r
-\r
-/ One-parameter shortcuts for date/time data types /\r
-#if (ODBCVER >= 0x0300)\r
-#define SQL_TYPE_DATE    91\r
-#define SQL_TYPE_TIME    92\r
-#define SQL_TYPE_TIMESTAMP 93\r
-\r
-#define SQL_UNICODE                             (-95)\r
-#define SQL_UNICODE_VARCHAR                     (-96)\r
-#define SQL_UNICODE_LONGVARCHAR                 (-97)\r
-*/\r
-       function ODBCTypes($t)\r
-       {\r
-               switch ((integer)$t) {\r
-               case 1: \r
-               case 12:\r
-               case 0:\r
-               case -95:\r
-               case -96:\r
-                       return 'C';\r
-               case -97:\r
-               case -1: //text\r
-                       return 'X';\r
-               case -4: //image\r
-                       return 'B';\r
-                               \r
-               case 91:\r
-               case 11:\r
-                       return 'D';\r
-                       \r
-               case 92:\r
-               case 93:\r
-               case 9: return 'T';\r
-               case 4:\r
-               case 5:\r
-               case -6:\r
-                       return 'I';\r
-                       \r
-               case -11: // uniqidentifier\r
-                       return 'R';\r
-               case -7: //bit\r
-                       return 'L';\r
-               \r
-               default:\r
-                       return 'N';\r
-               }\r
-       }\r
-       \r
-       function &MetaColumns($table)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $table = strtoupper($table);\r
-               $schema = false;\r
-               $this->_findschema($table,$schema);\r
-               \r
-               $savem = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-       \r
-               if (false) { // after testing, confirmed that the following does not work becoz of a bug\r
-                       $qid2 = odbc_tables($this->_connectionID);\r
-                       $rs = new ADORecordSet_odbc($qid2);             \r
-                       $ADODB_FETCH_MODE = $savem;\r
-                       if (!$rs) return false;\r
-                       $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
-                       $rs->_fetch();\r
-                       \r
-                       while (!$rs->EOF) {\r
-                               if ($table == strtoupper($rs->fields[2])) {\r
-                                       $q = $rs->fields[0];\r
-                                       $o = $rs->fields[1];\r
-                                       break;\r
-                               }\r
-                               $rs->MoveNext();\r
-                       }\r
-                       $rs->Close();\r
-                       \r
-                       $qid = odbc_columns($this->_connectionID,$q,$o,strtoupper($table),'%');\r
-               } else switch ($this->databaseType) {\r
-               case 'access':\r
-               case 'vfp':\r
-               case 'db2':\r
-                       $qid = odbc_columns($this->_connectionID);\r
-                       break;\r
-                       \r
-               default:\r
-                       $qid = @odbc_columns($this->_connectionID,'%','%',strtoupper($table),'%');\r
-                       if (empty($qid)) $qid = odbc_columns($this->_connectionID);\r
-                       break;\r
-               }\r
-               if (empty($qid)) return false;\r
-               \r
-               $rs = new ADORecordSet_odbc($qid);\r
-               $ADODB_FETCH_MODE = $savem;\r
-               \r
-               if (!$rs) return false;\r
-               \r
-               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;\r
-               $rs->_fetch();\r
-               $retarr = array();\r
-               \r
-               /*\r
-               $rs->fields indices\r
-               0 TABLE_QUALIFIER\r
-               1 TABLE_SCHEM\r
-               2 TABLE_NAME\r
-               3 COLUMN_NAME\r
-               4 DATA_TYPE\r
-               5 TYPE_NAME\r
-               6 PRECISION\r
-               7 LENGTH\r
-               8 SCALE\r
-               9 RADIX\r
-               10 NULLABLE\r
-               11 REMARKS\r
-               */\r
-               while (!$rs->EOF) {\r
-                       //adodb_pr($rs->fields);\r
-                       if (strtoupper($rs->fields[2]) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {\r
-                               $fld = new ADOFieldObject();\r
-                               $fld->name = $rs->fields[3];\r
-                               $fld->type = $this->ODBCTypes($rs->fields[4]);\r
-                               \r
-                               // ref: http://msdn.microsoft.com/library/default.asp?url=/archive/en-us/dnaraccgen/html/msdn_odk.asp\r
-                               // access uses precision to store length for char/varchar\r
-                               if ($fld->type == 'C' or $fld->type == 'X') {\r
-                                       if ($this->databaseType == 'access') \r
-                                               $fld->max_length = $rs->fields[6];\r
-                                       else if ($rs->fields[4] <= -95) // UNICODE\r
-                                               $fld->max_length = $rs->fields[7]/2;\r
-                                       else\r
-                                               $fld->max_length = $rs->fields[7];\r
-                               } else \r
-                                       $fld->max_length = $rs->fields[7];\r
-                               $fld->not_null = !empty($rs->fields[10]);\r
-                               $fld->scale = $rs->fields[8];\r
-                               $retarr[strtoupper($fld->name)] = $fld; \r
-                       } else if (sizeof($retarr)>0)\r
-                               break;\r
-                       $rs->MoveNext();\r
-               }\r
-               $rs->Close(); //-- crashes 4.03pl1 -- why?\r
-               \r
-               return $retarr;\r
-       }\r
-       \r
-       function Prepare($sql)\r
-       {\r
-               if (! $this->_bindInputArray) return $sql; // no binding\r
-               $stmt = odbc_prepare($this->_connectionID,$sql);\r
-               if (!$stmt) {\r
-               //      print "Prepare Error for ($sql) ".$this->ErrorMsg()."<br>";\r
-                       return $sql;\r
-               }\r
-               return array($sql,$stmt,false);\r
-       }\r
-\r
-       /* returns queryID or false */\r
-       function _query($sql,$inputarr=false) \r
-       {\r
-       GLOBAL $php_errormsg;\r
-               $php_errormsg = '';\r
-               $this->_error = '';\r
-               \r
-               if ($inputarr) {\r
-                       if (is_array($sql)) {\r
-                               $stmtid = $sql[1];\r
-                       } else {\r
-                               $stmtid = odbc_prepare($this->_connectionID,$sql);\r
-       \r
-                               if ($stmtid == false) {\r
-                                       $this->_errorMsg = $php_errormsg;\r
-                                       return false;\r
-                               }\r
-                       }\r
-                       \r
-                       if (! odbc_execute($stmtid,$inputarr)) {\r
-                               //@odbc_free_result($stmtid);\r
-                               if ($this->_haserrorfunctions) {\r
-                                       $this->_errorMsg = odbc_errormsg();\r
-                                       $this->_errorCode = odbc_error();\r
-                               }\r
-                               return false;\r
-                       }\r
-               \r
-               } else if (is_array($sql)) {\r
-                       $stmtid = $sql[1];\r
-                       if (!odbc_execute($stmtid)) {\r
-                               //@odbc_free_result($stmtid);\r
-                               if ($this->_haserrorfunctions) {\r
-                                       $this->_errorMsg = odbc_errormsg();\r
-                                       $this->_errorCode = odbc_error();\r
-                               }\r
-                               return false;\r
-                       }\r
-               } else\r
-                       $stmtid = odbc_exec($this->_connectionID,$sql);\r
-               \r
-               $this->_lastAffectedRows = 0;\r
-               if ($stmtid) {\r
-                       if (@odbc_num_fields($stmtid) == 0) {\r
-                               $this->_lastAffectedRows = odbc_num_rows($stmtid);\r
-                               $stmtid = true;\r
-                       } else {\r
-                               $this->_lastAffectedRows = 0;\r
-                               odbc_binmode($stmtid,$this->binmode);\r
-                               odbc_longreadlen($stmtid,$this->maxblobsize);\r
-                       }\r
-                       \r
-                       if ($this->_haserrorfunctions) {\r
-                               $this->_errorMsg = '';\r
-                               $this->_errorCode = 0;\r
-                       } else\r
-                               $this->_errorMsg = $php_errormsg;\r
-               } else {\r
-                       if ($this->_haserrorfunctions) {\r
-                               $this->_errorMsg = odbc_errormsg();\r
-                               $this->_errorCode = odbc_error();\r
-                       } else\r
-                               $this->_errorMsg = $php_errormsg;\r
-               }\r
-               \r
-               \r
-               return $stmtid;\r
-       }\r
-\r
-       /*\r
-               Insert a null into the blob field of the table first.\r
-               Then use UpdateBlob to store the blob.\r
-               \r
-               Usage:\r
-                \r
-               $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
-               $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
-       */\r
-       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
-       {\r
-               return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;\r
-       }\r
-       \r
-       // returns true or false\r
-       function _close()\r
-       {\r
-               $ret = @odbc_close($this->_connectionID);\r
-               $this->_connectionID = false;\r
-               return $ret;\r
-       }\r
-\r
-       function _affectedrows()\r
-       {\r
-               return $this->_lastAffectedRows;\r
-       }\r
-       \r
-}\r
-       \r
-/*--------------------------------------------------------------------------------------\r
-        Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordSet_odbc extends ADORecordSet { \r
-       \r
-       var $bind = false;\r
-       var $databaseType = "odbc";             \r
-       var $dataProvider = "odbc";\r
-       var $useFetchArray;\r
-       var $_has_stupid_odbc_fetch_api_change;\r
-       \r
-       function ADORecordSet_odbc($id,$mode=false)\r
-       {\r
-               if ($mode === false) {  \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               $this->fetchMode = $mode;\r
-               \r
-               $this->_queryID = $id;\r
-               \r
-               // the following is required for mysql odbc driver in 4.3.1 -- why?\r
-               $this->EOF = false;\r
-               $this->_currentRow = -1;\r
-               //$this->ADORecordSet($id);\r
-       }\r
-\r
-\r
-       // returns the field object\r
-       function &FetchField($fieldOffset = -1) \r
-       {\r
-               \r
-               $off=$fieldOffset+1; // offsets begin at 1\r
-               \r
-               $o= new ADOFieldObject();\r
-               $o->name = @odbc_field_name($this->_queryID,$off);\r
-               $o->type = @odbc_field_type($this->_queryID,$off);\r
-               $o->max_length = @odbc_field_len($this->_queryID,$off);\r
-               if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);\r
-               else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);\r
-               return $o;\r
-       }\r
-       \r
-       /* Use associative array to get fields array */\r
-       function Fields($colname)\r
-       {\r
-               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];\r
-               if (!$this->bind) {\r
-                       $this->bind = array();\r
-                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                               $o = $this->FetchField($i);\r
-                               $this->bind[strtoupper($o->name)] = $i;\r
-                       }\r
-               }\r
-\r
-                return $this->fields[$this->bind[strtoupper($colname)]];\r
-       }\r
-       \r
-               \r
-       function _initrs()\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-               $this->_numOfRows = ($ADODB_COUNTRECS) ? @odbc_num_rows($this->_queryID) : -1;\r
-               $this->_numOfFields = @odbc_num_fields($this->_queryID);\r
-               // some silly drivers such as db2 as/400 and intersystems cache return _numOfRows = 0\r
-               if ($this->_numOfRows == 0) $this->_numOfRows = -1;\r
-               //$this->useFetchArray = $this->connection->useFetchArray;\r
-               $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;\r
-       }       \r
-       \r
-       function _seek($row)\r
-       {\r
-               return false;\r
-       }\r
-       \r
-       // speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated\r
-       function &GetArrayLimit($nrows,$offset=-1) \r
-       {\r
-               if ($offset <= 0) {\r
-                       $rs =& $this->GetArray($nrows);\r
-                       return $rs;\r
-               }\r
-               $savem = $this->fetchMode;\r
-               $this->fetchMode = ADODB_FETCH_NUM;\r
-               $this->Move($offset);\r
-               $this->fetchMode = $savem;\r
-               \r
-               if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
-                       $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);\r
-               }\r
-               \r
-               $results = array();\r
-               $cnt = 0;\r
-               while (!$this->EOF && $nrows != $cnt) {\r
-                       $results[$cnt++] = $this->fields;\r
-                       $this->MoveNext();\r
-               }\r
-               \r
-               return $results;\r
-       }\r
-       \r
-       \r
-       function MoveNext() \r
-       {\r
-               if ($this->_numOfRows != 0 && !$this->EOF) {            \r
-                       $this->_currentRow++;\r
-                       $row = 0;\r
-                       if ($this->_has_stupid_odbc_fetch_api_change)\r
-                               $rez = @odbc_fetch_into($this->_queryID,$this->fields);\r
-                       else \r
-                               $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);\r
-                       if ($rez) {\r
-                               if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
-                                       $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);\r
-                               }\r
-                               return true;\r
-                       }\r
-               }\r
-               $this->fields = false;\r
-               $this->EOF = true;\r
-               return false;\r
-       }       \r
-       \r
-       function _fetch()\r
-       {\r
-               $row = 0;\r
-               if ($this->_has_stupid_odbc_fetch_api_change)\r
-                       $rez = @odbc_fetch_into($this->_queryID,$this->fields,$row);\r
-               else \r
-                       $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);\r
-               \r
-               if ($rez) {\r
-                       if ($this->fetchMode & ADODB_FETCH_ASSOC) {\r
-                               $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);\r
-                       }\r
-                       return true;\r
-               }\r
-               $this->fields = false;\r
-               return false;\r
-       }\r
-       \r
-       function _close() \r
-       {\r
-               return @odbc_free_result($this->_queryID);              \r
-       }\r
-\r
-}\r
-\r
-?>\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Requires ODBC. Works on Windows and Unix.
+*/
+  define("_ADODB_ODBC_LAYER", 2 );
+        
+/*--------------------------------------------------------------------------------------
+--------------------------------------------------------------------------------------*/
+
+
+class ADODB_odbc extends ADOConnection {
+       var $databaseType = "odbc";     
+       var $fmtDate = "'Y-m-d'";
+       var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $dataProvider = "odbc";
+       var $hasAffectedRows = true;
+       var $binmode = ODBC_BINMODE_RETURN;
+       var $useFetchArray = false; // setting this to true will make array elements in FETCH_ASSOC mode case-sensitive
+                                                               // breaking backward-compat
+       //var $longreadlen = 8000; // default number of chars to return for a Blob/Long field
+       var $_bindInputArray = false;   
+       var $curmode = SQL_CUR_USE_DRIVER; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
+       var $_genSeqSQL = "create table %s (id integer)";
+       var $_autocommit = true;
+       var $_haserrorfunctions = true;
+       var $_has_stupid_odbc_fetch_api_change = true;
+       var $_lastAffectedRows = 0;
+       
+       function ADODB_odbc() 
+       {       
+               $this->_haserrorfunctions = ADODB_PHPVER >= 0x4050;
+               $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;
+       }
+       
+       function ServerInfo()
+       {
+       
+               if (!empty($this->host) && ADODB_PHPVER >= 0x4300) {
+                       $dsn = strtoupper($this->host);
+                       $first = true;
+                       $found = false;
+                       
+                       if (!function_exists('odbc_data_source')) return false;
+                       
+                       while(true) {
+                               
+                               $rez = odbc_data_source($this->_connectionID,
+                                       $first ? SQL_FETCH_FIRST : SQL_FETCH_NEXT);
+                               $first = false;
+                               if (!is_array($rez)) break;
+                               if (strtoupper($rez['server']) == $dsn) {
+                                       $found = true;
+                                       break;
+                               }
+                       } 
+                       if (!$found) return ADOConnection::ServerInfo();
+                       if (!isset($rez['version'])) $rez['version'] = '';
+                       return $rez;
+               } else {
+                       return ADOConnection::ServerInfo();
+               }
+       }
+
+       
+       function CreateSequence($seqname='adodbseq',$start=1)
+       {
+               if (empty($this->_genSeqSQL)) return false;
+               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+               if (!$ok) return false;
+               $start -= 1;
+               return $this->Execute("insert into $seqname values($start)");
+       }
+       
+       var $_dropSeqSQL = 'drop table %s';
+       function DropSequence($seqname)
+       {
+               if (empty($this->_dropSeqSQL)) return false;
+               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
+       }
+       
+       /*
+               This algorithm is not very efficient, but works even if table locking
+               is not available.
+               
+               Will return false if unable to generate an ID after $MAXLOOPS attempts.
+       */
+       function GenID($seq='adodbseq',$start=1)
+       {       
+               // if you have to modify the parameter below, your database is overloaded,
+               // or you need to implement generation of id's yourself!
+               $MAXLOOPS = 100;
+               //$this->debug=1;
+               while (--$MAXLOOPS>=0) {
+                       $num = $this->GetOne("select id from $seq");
+                       if ($num === false) {
+                               $this->Execute(sprintf($this->_genSeqSQL ,$seq));       
+                               $start -= 1;
+                               $num = '0';
+                               $ok = $this->Execute("insert into $seq values($start)");
+                               if (!$ok) return false;
+                       } 
+                       $this->Execute("update $seq set id=id+1 where id=$num");
+                       
+                       if ($this->affected_rows() > 0) {
+                               $num += 1;
+                               $this->genID = $num;
+                               return $num;
+                       }
+               }
+               if ($fn = $this->raiseErrorFn) {
+                       $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
+               }
+               return false;
+       }
+
+
+       function ErrorMsg()
+       {
+               if ($this->_haserrorfunctions) {
+                       if ($this->_errorMsg !== false) return $this->_errorMsg;
+                       if (empty($this->_connectionID)) return @odbc_errormsg();
+                       return @odbc_errormsg($this->_connectionID);
+               } else return ADOConnection::ErrorMsg();
+       }
+       
+       function ErrorNo()
+       {
+               
+               if ($this->_haserrorfunctions) {
+                       if ($this->_errorCode !== false) {
+                               // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
+                               return (strlen($this->_errorCode)<=2) ? 0 : $this->_errorCode;
+                       }
+
+                       if (empty($this->_connectionID)) $e = @odbc_error(); 
+                       else $e = @odbc_error($this->_connectionID);
+                       
+                        // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
+                        // so we check and patch
+                       if (strlen($e)<=2) return 0;
+                       return $e;
+               } else return ADOConnection::ErrorNo();
+       }
+       
+       
+       // returns true or false
+       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
+       {
+       global $php_errormsg;
+               
+               if (!function_exists('odbc_connect')) return false;
+               
+               if ($this->debug && $argDatabasename) {
+                       ADOConnection::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter.");
+               }
+               $php_errormsg = '';
+               if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
+               else $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode);
+               $this->_errorMsg = $php_errormsg;
+               if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
+               
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
+               return $this->_connectionID != false;
+       }
+       
+       // returns true or false
+       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
+       {
+       global $php_errormsg;
+       
+               if (!function_exists('odbc_connect')) return false;
+               
+               $php_errormsg = '';
+               if ($this->debug && $argDatabasename) {
+                       ADOConnection::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");
+               }
+       //      print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();
+               if ($this->curmode === false) $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword);
+               else $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode);
+               
+               $this->_errorMsg = $php_errormsg;
+               if ($this->_connectionID && $this->autoRollback) @odbc_rollback($this->_connectionID);
+               if (isset($this->connectStmt)) $this->Execute($this->connectStmt);
+               
+               return $this->_connectionID != false;
+       }
+
+       function BeginTrans()
+       {       
+               if (!$this->hasTransactions) return false;
+               if ($this->transOff) return true; 
+               $this->transCnt += 1;
+               $this->_autocommit = false;
+               return odbc_autocommit($this->_connectionID,false);
+       }
+       
+       function CommitTrans($ok=true) 
+       { 
+               if ($this->transOff) return true; 
+               if (!$ok) return $this->RollbackTrans();
+               if ($this->transCnt) $this->transCnt -= 1;
+               $this->_autocommit = true;
+               $ret = odbc_commit($this->_connectionID);
+               odbc_autocommit($this->_connectionID,true);
+               return $ret;
+       }
+       
+       function RollbackTrans()
+       {
+               if ($this->transOff) return true; 
+               if ($this->transCnt) $this->transCnt -= 1;
+               $this->_autocommit = true;
+               $ret = odbc_rollback($this->_connectionID);
+               odbc_autocommit($this->_connectionID,true);
+               return $ret;
+       }
+       
+       function MetaPrimaryKeys($table)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $savem = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $qid = @odbc_primarykeys($this->_connectionID,'','',$table);
+               
+               if (!$qid) {
+                       $ADODB_FETCH_MODE = $savem;
+                       return false;
+               }
+               $rs = new ADORecordSet_odbc($qid);
+               $ADODB_FETCH_MODE = $savem;
+               
+               if (!$rs) return false;
+               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+               
+               $arr =& $rs->GetArray();
+               $rs->Close();
+               //print_r($arr);
+               $arr2 = array();
+               for ($i=0; $i < sizeof($arr); $i++) {
+                       if ($arr[$i][3]) $arr2[] = $arr[$i][3];
+               }
+               return $arr2;
+       }
+       
+       
+       
+       function &MetaTables($ttype=false)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $savem = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $qid = odbc_tables($this->_connectionID);
+               
+               $rs = new ADORecordSet_odbc($qid);
+               
+               $ADODB_FETCH_MODE = $savem;
+               if (!$rs) return false;
+               
+               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+               
+               $arr =& $rs->GetArray();
+               //print_r($arr);
+               
+               $rs->Close();
+               $arr2 = array();
+               
+               if ($ttype) {
+                       $isview = strncmp($ttype,'V',1) === 0;
+               }
+               for ($i=0; $i < sizeof($arr); $i++) {
+                       if (!$arr[$i][2]) continue;
+                       $type = $arr[$i][3];
+                       if ($ttype) { 
+                               if ($isview) {
+                                       if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];
+                               } else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];
+                       } else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];
+               }
+               return $arr2;
+       }
+       
+/*
+/ SQL data type codes /
+#define        SQL_UNKNOWN_TYPE        0
+#define SQL_CHAR                       1
+#define SQL_NUMERIC             2
+#define SQL_DECIMAL             3
+#define SQL_INTEGER             4
+#define SQL_SMALLINT           5
+#define SQL_FLOAT                 6
+#define SQL_REAL                       7
+#define SQL_DOUBLE               8
+#if (ODBCVER >= 0x0300)
+#define SQL_DATETIME           9
+#endif
+#define SQL_VARCHAR            12
+
+/ One-parameter shortcuts for date/time data types /
+#if (ODBCVER >= 0x0300)
+#define SQL_TYPE_DATE    91
+#define SQL_TYPE_TIME    92
+#define SQL_TYPE_TIMESTAMP 93
+
+#define SQL_UNICODE                             (-95)
+#define SQL_UNICODE_VARCHAR                     (-96)
+#define SQL_UNICODE_LONGVARCHAR                 (-97)
+*/
+       function ODBCTypes($t)
+       {
+               switch ((integer)$t) {
+               case 1: 
+               case 12:
+               case 0:
+               case -95:
+               case -96:
+                       return 'C';
+               case -97:
+               case -1: //text
+                       return 'X';
+               case -4: //image
+                       return 'B';
+                               
+               case 91:
+               case 11:
+                       return 'D';
+                       
+               case 92:
+               case 93:
+               case 9: return 'T';
+               case 4:
+               case 5:
+               case -6:
+                       return 'I';
+                       
+               case -11: // uniqidentifier
+                       return 'R';
+               case -7: //bit
+                       return 'L';
+               
+               default:
+                       return 'N';
+               }
+       }
+       
+       function &MetaColumns($table)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $table = strtoupper($table);
+               $schema = false;
+               $this->_findschema($table,$schema);
+               
+               $savem = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+       
+               if (false) { // after testing, confirmed that the following does not work becoz of a bug
+                       $qid2 = odbc_tables($this->_connectionID);
+                       $rs = new ADORecordSet_odbc($qid2);             
+                       $ADODB_FETCH_MODE = $savem;
+                       if (!$rs) return false;
+                       $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+                       $rs->_fetch();
+                       
+                       while (!$rs->EOF) {
+                               if ($table == strtoupper($rs->fields[2])) {
+                                       $q = $rs->fields[0];
+                                       $o = $rs->fields[1];
+                                       break;
+                               }
+                               $rs->MoveNext();
+                       }
+                       $rs->Close();
+                       
+                       $qid = odbc_columns($this->_connectionID,$q,$o,strtoupper($table),'%');
+               } else switch ($this->databaseType) {
+               case 'access':
+               case 'vfp':
+               case 'db2':
+                       $qid = odbc_columns($this->_connectionID);
+                       break;
+                       
+               default:
+                       $qid = @odbc_columns($this->_connectionID,'%','%',strtoupper($table),'%');
+                       if (empty($qid)) $qid = odbc_columns($this->_connectionID);
+                       break;
+               }
+               if (empty($qid)) return false;
+               
+               $rs = new ADORecordSet_odbc($qid);
+               $ADODB_FETCH_MODE = $savem;
+               
+               if (!$rs) return false;
+               
+               $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
+               $rs->_fetch();
+               $retarr = array();
+               
+               /*
+               $rs->fields indices
+               0 TABLE_QUALIFIER
+               1 TABLE_SCHEM
+               2 TABLE_NAME
+               3 COLUMN_NAME
+               4 DATA_TYPE
+               5 TYPE_NAME
+               6 PRECISION
+               7 LENGTH
+               8 SCALE
+               9 RADIX
+               10 NULLABLE
+               11 REMARKS
+               */
+               while (!$rs->EOF) {
+                       //adodb_pr($rs->fields);
+                       if (strtoupper($rs->fields[2]) == $table && (!$schema || strtoupper($rs->fields[1]) == $schema)) {
+                               $fld = new ADOFieldObject();
+                               $fld->name = $rs->fields[3];
+                               $fld->type = $this->ODBCTypes($rs->fields[4]);
+                               
+                               // ref: http://msdn.microsoft.com/library/default.asp?url=/archive/en-us/dnaraccgen/html/msdn_odk.asp
+                               // access uses precision to store length for char/varchar
+                               if ($fld->type == 'C' or $fld->type == 'X') {
+                                       if ($this->databaseType == 'access') 
+                                               $fld->max_length = $rs->fields[6];
+                                       else if ($rs->fields[4] <= -95) // UNICODE
+                                               $fld->max_length = $rs->fields[7]/2;
+                                       else
+                                               $fld->max_length = $rs->fields[7];
+                               } else 
+                                       $fld->max_length = $rs->fields[7];
+                               $fld->not_null = !empty($rs->fields[10]);
+                               $fld->scale = $rs->fields[8];
+                               $retarr[strtoupper($fld->name)] = $fld; 
+                       } else if (sizeof($retarr)>0)
+                               break;
+                       $rs->MoveNext();
+               }
+               $rs->Close(); //-- crashes 4.03pl1 -- why?
+               
+               return $retarr;
+       }
+       
+       function Prepare($sql)
+       {
+               if (! $this->_bindInputArray) return $sql; // no binding
+               $stmt = odbc_prepare($this->_connectionID,$sql);
+               if (!$stmt) {
+                       // we don't know whether odbc driver is parsing prepared stmts, so just return sql
+                       return $sql;
+               }
+               return array($sql,$stmt,false);
+       }
+
+       /* returns queryID or false */
+       function _query($sql,$inputarr=false) 
+       {
+       GLOBAL $php_errormsg;
+               $php_errormsg = '';
+               $this->_error = '';
+               
+               if ($inputarr) {
+                       if (is_array($sql)) {
+                               $stmtid = $sql[1];
+                       } else {
+                               $stmtid = odbc_prepare($this->_connectionID,$sql);
+       
+                               if ($stmtid == false) {
+                                       $this->_errorMsg = $php_errormsg;
+                                       return false;
+                               }
+                       }
+                       
+                       if (! odbc_execute($stmtid,$inputarr)) {
+                               //@odbc_free_result($stmtid);
+                               if ($this->_haserrorfunctions) {
+                                       $this->_errorMsg = odbc_errormsg();
+                                       $this->_errorCode = odbc_error();
+                               }
+                               return false;
+                       }
+               
+               } else if (is_array($sql)) {
+                       $stmtid = $sql[1];
+                       if (!odbc_execute($stmtid)) {
+                               //@odbc_free_result($stmtid);
+                               if ($this->_haserrorfunctions) {
+                                       $this->_errorMsg = odbc_errormsg();
+                                       $this->_errorCode = odbc_error();
+                               }
+                               return false;
+                       }
+               } else
+                       $stmtid = odbc_exec($this->_connectionID,$sql);
+               
+               $this->_lastAffectedRows = 0;
+               if ($stmtid) {
+                       if (@odbc_num_fields($stmtid) == 0) {
+                               $this->_lastAffectedRows = odbc_num_rows($stmtid);
+                               $stmtid = true;
+                       } else {
+                               $this->_lastAffectedRows = 0;
+                               odbc_binmode($stmtid,$this->binmode);
+                               odbc_longreadlen($stmtid,$this->maxblobsize);
+                       }
+                       
+                       if ($this->_haserrorfunctions) {
+                               $this->_errorMsg = '';
+                               $this->_errorCode = 0;
+                       } else
+                               $this->_errorMsg = $php_errormsg;
+               } else {
+                       if ($this->_haserrorfunctions) {
+                               $this->_errorMsg = odbc_errormsg();
+                               $this->_errorCode = odbc_error();
+                       } else
+                               $this->_errorMsg = $php_errormsg;
+               }
+               return $stmtid;
+       }
+
+       /*
+               Insert a null into the blob field of the table first.
+               Then use UpdateBlob to store the blob.
+               
+               Usage:
+                
+               $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+               $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+       */
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+       {
+               return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
+       }
+       
+       // returns true or false
+       function _close()
+       {
+               $ret = @odbc_close($this->_connectionID);
+               $this->_connectionID = false;
+               return $ret;
+       }
+
+       function _affectedrows()
+       {
+               return $this->_lastAffectedRows;
+       }
+       
+}
+       
+/*--------------------------------------------------------------------------------------
+        Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_odbc extends ADORecordSet { 
+       
+       var $bind = false;
+       var $databaseType = "odbc";             
+       var $dataProvider = "odbc";
+       var $useFetchArray;
+       var $_has_stupid_odbc_fetch_api_change;
+       
+       function ADORecordSet_odbc($id,$mode=false)
+       {
+               if ($mode === false) {  
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               $this->fetchMode = $mode;
+               
+               $this->_queryID = $id;
+               
+               // the following is required for mysql odbc driver in 4.3.1 -- why?
+               $this->EOF = false;
+               $this->_currentRow = -1;
+               //$this->ADORecordSet($id);
+       }
+
+
+       // returns the field object
+       function &FetchField($fieldOffset = -1) 
+       {
+               
+               $off=$fieldOffset+1; // offsets begin at 1
+               
+               $o= new ADOFieldObject();
+               $o->name = @odbc_field_name($this->_queryID,$off);
+               $o->type = @odbc_field_type($this->_queryID,$off);
+               $o->max_length = @odbc_field_len($this->_queryID,$off);
+               if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
+               else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
+               return $o;
+       }
+       
+       /* Use associative array to get fields array */
+       function Fields($colname)
+       {
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
+               if (!$this->bind) {
+                       $this->bind = array();
+                       for ($i=0; $i < $this->_numOfFields; $i++) {
+                               $o = $this->FetchField($i);
+                               $this->bind[strtoupper($o->name)] = $i;
+                       }
+               }
+
+                return $this->fields[$this->bind[strtoupper($colname)]];
+       }
+       
+               
+       function _initrs()
+       {
+       global $ADODB_COUNTRECS;
+               $this->_numOfRows = ($ADODB_COUNTRECS) ? @odbc_num_rows($this->_queryID) : -1;
+               $this->_numOfFields = @odbc_num_fields($this->_queryID);
+               // some silly drivers such as db2 as/400 and intersystems cache return _numOfRows = 0
+               if ($this->_numOfRows == 0) $this->_numOfRows = -1;
+               //$this->useFetchArray = $this->connection->useFetchArray;
+               $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200;
+       }       
+       
+       function _seek($row)
+       {
+               return false;
+       }
+       
+       // speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated
+       function &GetArrayLimit($nrows,$offset=-1) 
+       {
+               if ($offset <= 0) {
+                       $rs =& $this->GetArray($nrows);
+                       return $rs;
+               }
+               $savem = $this->fetchMode;
+               $this->fetchMode = ADODB_FETCH_NUM;
+               $this->Move($offset);
+               $this->fetchMode = $savem;
+               
+               if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+                       $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+               }
+               
+               $results = array();
+               $cnt = 0;
+               while (!$this->EOF && $nrows != $cnt) {
+                       $results[$cnt++] = $this->fields;
+                       $this->MoveNext();
+               }
+               
+               return $results;
+       }
+       
+       
+       function MoveNext() 
+       {
+               if ($this->_numOfRows != 0 && !$this->EOF) {            
+                       $this->_currentRow++;
+                       $row = 0;
+                       if ($this->_has_stupid_odbc_fetch_api_change)
+                               $rez = @odbc_fetch_into($this->_queryID,$this->fields);
+                       else 
+                               $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);
+                       if ($rez) {
+                               if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+                                       $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+                               }
+                               return true;
+                       }
+               }
+               $this->fields = false;
+               $this->EOF = true;
+               return false;
+       }       
+       
+       function _fetch()
+       {
+               $row = 0;
+               if ($this->_has_stupid_odbc_fetch_api_change)
+                       $rez = @odbc_fetch_into($this->_queryID,$this->fields,$row);
+               else 
+                       $rez = @odbc_fetch_into($this->_queryID,$row,$this->fields);
+               
+               if ($rez) {
+                       if ($this->fetchMode & ADODB_FETCH_ASSOC) {
+                               $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE);
+                       }
+                       return true;
+               }
+               $this->fields = false;
+               return false;
+       }
+       
+       function _close() 
+       {
+               return @odbc_free_result($this->_queryID);              
+       }
+
+}
+
+?>
index 435bd73465fb61b2105b57c4a6fd521a6fe793ad..4b3161245b9670eb3f6a4680fc46e5c983588973 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  MSSQL support via ODBC. Requires ODBC. Works on Windows and Unix. \r
-  For Unix configuration, see http://phpbuilder.com/columns/alberto20000919.php3\r
-*/\r
-\r
-if (!defined('_ADODB_ODBC_LAYER')) {\r
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
-}\r
-\r
\r
-class  ADODB_odbc_mssql extends ADODB_odbc {   \r
-       var $databaseType = 'odbc_mssql';\r
-       var $fmtDate = "'Y-m-d'";\r
-       var $fmtTimeStamp = "'Y-m-d h:i:sA'";\r
-       var $_bindInputArray = true;\r
-       var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE'))";\r
-       var $metaColumnsSQL = "select c.name,t.name,c.length from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";\r
-       var $hasTop = 'top';            // support mssql/interbase SELECT TOP 10 * FROM TABLE\r
-       var $sysDate = 'GetDate()';\r
-       var $sysTimeStamp = 'GetDate()';\r
-       var $leftOuter = '*=';\r
-       var $rightOuter = '=*';\r
-       var $upperCase = 'upper';\r
-       var $substr = 'substring';\r
-       var $length = 'len';\r
-       var $ansiOuter = true; // for mssql7 or later\r
-       var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000\r
-       var $hasInsertID = true;\r
-       var $connectStmt = 'SET CONCAT_NULL_YIELDS_NULL OFF'; # When SET CONCAT_NULL_YIELDS_NULL is ON, \r
-                                                                                                                 # concatenating a null value with a string yields a NULL result\r
-       \r
-       function ADODB_odbc_mssql()\r
-       {\r
-               $this->ADODB_odbc();\r
-               $this->curmode = SQL_CUR_USE_ODBC;      \r
-       }\r
-\r
-       // crashes php...\r
-       function ServerInfo()\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $row = $this->GetRow("execute sp_server_info 2");\r
-               $ADODB_FETCH_MODE = $save;\r
-               if (!is_array($row)) return false;\r
-               $arr['description'] = $row[2];\r
-               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
-               return $arr;\r
-       }\r
-\r
-       function IfNull( $field, $ifNull ) \r
-       {\r
-               return " ISNULL($field, $ifNull) "; // if MS SQL Server\r
-       }\r
-       \r
-       function _insertid()\r
-       {\r
-       // SCOPE_IDENTITY()\r
-       // Returns the last IDENTITY value inserted into an IDENTITY column in \r
-       // the same scope. A scope is a module -- a stored procedure, trigger, \r
-       // function, or batch. Thus, two statements are in the same scope if \r
-       // they are in the same stored procedure, function, or batch.\r
-                       return $this->GetOne($this->identitySQL);\r
-       }\r
-       \r
-       \r
-       function MetaForeignKeys($table, $owner=false, $upper=false)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $table = $this->qstr(strtoupper($table));\r
-               \r
-               $sql = \r
-"select object_name(constid) as constraint_name,\r
-       col_name(fkeyid, fkey) as column_name,\r
-       object_name(rkeyid) as referenced_table_name,\r
-       col_name(rkeyid, rkey) as referenced_column_name\r
-from sysforeignkeys\r
-where upper(object_name(fkeyid)) = $table\r
-order by constraint_name, referenced_table_name, keyno";\r
-               \r
-               $constraints =& $this->GetArray($sql);\r
-               \r
-               $ADODB_FETCH_MODE = $save;\r
-               \r
-               $arr = false;\r
-               foreach($constraints as $constr) {\r
-                       //print_r($constr);\r
-                       $arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; \r
-               }\r
-               if (!$arr) return false;\r
-               \r
-               $arr2 = false;\r
-               \r
-               foreach($arr as $k => $v) {\r
-                       foreach($v as $a => $b) {\r
-                               if ($upper) $a = strtoupper($a);\r
-                               $arr2[$a] = $b;\r
-                       }\r
-               }\r
-               return $arr2;\r
-       }\r
-       \r
-       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
-       {\r
-               if ($mask) {$this->debug=1;\r
-                       $save = $this->metaTablesSQL;\r
-                       $mask = $this->qstr($mask);\r
-                       $this->metaTablesSQL .= " AND name like $mask";\r
-               }\r
-               $ret =& ADOConnection::MetaTables($ttype,$showSchema);\r
-               \r
-               if ($mask) {\r
-                       $this->metaTablesSQL = $save;\r
-               }\r
-               return $ret;\r
-       }\r
-       \r
-       function &MetaColumns($table)\r
-       {\r
-               return ADOConnection::MetaColumns($table);\r
-       }\r
-       \r
-       function _query($sql,$inputarr)\r
-       {\r
-               if (is_string($sql)) $sql = str_replace('||','+',$sql);\r
-               return ADODB_odbc::_query($sql,$inputarr);\r
-       }\r
-       \r
-       // "Stein-Aksel Basma" <basma@accelero.no>\r
-       // tested with MSSQL 2000\r
-       function &MetaPrimaryKeys($table)\r
-       {\r
-               $sql = "select k.column_name from information_schema.key_column_usage k,\r
-               information_schema.table_constraints tc \r
-               where tc.constraint_name = k.constraint_name and tc.constraint_type =\r
-               'PRIMARY KEY' and k.table_name = '$table'";\r
-               \r
-               $a = $this->GetCol($sql);\r
-               if ($a && sizeof($a)>0) return $a;\r
-               return false;     \r
-       }\r
-       \r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
-       {\r
-               if ($nrows > 0 && $offset <= 0) {\r
-                       $sql = preg_replace(\r
-                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);\r
-                       $rs =& $this->Execute($sql,$inputarr);\r
-               } else\r
-                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
-                       \r
-               return $rs;\r
-       }\r
-       \r
-       // Format date column in sql string given an input format that understands Y M D\r
-       function SQLDate($fmt, $col=false)\r
-       {       \r
-               if (!$col) $col = $this->sysTimeStamp;\r
-               $s = '';\r
-               \r
-               $len = strlen($fmt);\r
-               for ($i=0; $i < $len; $i++) {\r
-                       if ($s) $s .= '+';\r
-                       $ch = $fmt[$i];\r
-                       switch($ch) {\r
-                       case 'Y':\r
-                       case 'y':\r
-                               $s .= "datename(yyyy,$col)";\r
-                               break;\r
-                       case 'M':\r
-                               $s .= "convert(char(3),$col,0)";\r
-                               break;\r
-                       case 'm':\r
-                               $s .= "replace(str(month($col),2),' ','0')";\r
-                               break;\r
-                       case 'Q':\r
-                       case 'q':\r
-                               $s .= "datename(quarter,$col)";\r
-                               break;\r
-                       case 'D':\r
-                       case 'd':\r
-                               $s .= "replace(str(day($col),2),' ','0')";\r
-                               break;\r
-                       case 'h':\r
-                               $s .= "substring(convert(char(14),$col,0),13,2)";\r
-                               break;\r
-                       \r
-                       case 'H':\r
-                               $s .= "replace(str(datepart(hh,$col),2),' ','0')";\r
-                               break;\r
-                               \r
-                       case 'i':\r
-                               $s .= "replace(str(datepart(mi,$col),2),' ','0')";\r
-                               break;\r
-                       case 's':\r
-                               $s .= "replace(str(datepart(ss,$col),2),' ','0')";\r
-                               break;\r
-                       case 'a':\r
-                       case 'A':\r
-                               $s .= "substring(convert(char(19),$col,0),18,2)";\r
-                               break;\r
-                               \r
-                       default:\r
-                               if ($ch == '\\') {\r
-                                       $i++;\r
-                                       $ch = substr($fmt,$i,1);\r
-                               }\r
-                               $s .= $this->qstr($ch);\r
-                               break;\r
-                       }\r
-               }\r
-               return $s;\r
-       }\r
-\r
-} \r
\r
-class  ADORecordSet_odbc_mssql extends ADORecordSet_odbc {     \r
-       \r
-       var $databaseType = 'odbc_mssql';\r
-       \r
-       function ADORecordSet_odbc_mssql($id,$mode=false)\r
-       {\r
-               return $this->ADORecordSet_odbc($id,$mode);\r
-       }       \r
-}\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  MSSQL support via ODBC. Requires ODBC. Works on Windows and Unix. 
+  For Unix configuration, see http://phpbuilder.com/columns/alberto20000919.php3
+*/
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+
+class  ADODB_odbc_mssql extends ADODB_odbc {   
+       var $databaseType = 'odbc_mssql';
+       var $fmtDate = "'Y-m-d'";
+       var $fmtTimeStamp = "'Y-m-d h:i:sA'";
+       var $_bindInputArray = true;
+       var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end from sysobjects where (type='U' or type='V') and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE'))";
+       var $metaColumnsSQL = "select c.name,t.name,c.length from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";
+       var $hasTop = 'top';            // support mssql/interbase SELECT TOP 10 * FROM TABLE
+       var $sysDate = 'GetDate()';
+       var $sysTimeStamp = 'GetDate()';
+       var $leftOuter = '*=';
+       var $rightOuter = '=*';
+       var $upperCase = 'upper';
+       var $substr = 'substring';
+       var $length = 'len';
+       var $ansiOuter = true; // for mssql7 or later
+       var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000
+       var $hasInsertID = true;
+       var $connectStmt = 'SET CONCAT_NULL_YIELDS_NULL OFF'; # When SET CONCAT_NULL_YIELDS_NULL is ON, 
+                                                                                                                 # concatenating a null value with a string yields a NULL result
+       
+       function ADODB_odbc_mssql()
+       {
+               $this->ADODB_odbc();
+               $this->curmode = SQL_CUR_USE_ODBC;      
+       }
+
+       // crashes php...
+       function ServerInfo()
+       {
+       global $ADODB_FETCH_MODE;
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $row = $this->GetRow("execute sp_server_info 2");
+               $ADODB_FETCH_MODE = $save;
+               if (!is_array($row)) return false;
+               $arr['description'] = $row[2];
+               $arr['version'] = ADOConnection::_findvers($arr['description']);
+               return $arr;
+       }
+
+       function IfNull( $field, $ifNull ) 
+       {
+               return " ISNULL($field, $ifNull) "; // if MS SQL Server
+       }
+       
+       function _insertid()
+       {
+       // SCOPE_IDENTITY()
+       // Returns the last IDENTITY value inserted into an IDENTITY column in 
+       // the same scope. A scope is a module -- a stored procedure, trigger, 
+       // function, or batch. Thus, two statements are in the same scope if 
+       // they are in the same stored procedure, function, or batch.
+                       return $this->GetOne($this->identitySQL);
+       }
+       
+       
+       function MetaForeignKeys($table, $owner=false, $upper=false)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $table = $this->qstr(strtoupper($table));
+               
+               $sql = 
+"select object_name(constid) as constraint_name,
+       col_name(fkeyid, fkey) as column_name,
+       object_name(rkeyid) as referenced_table_name,
+       col_name(rkeyid, rkey) as referenced_column_name
+from sysforeignkeys
+where upper(object_name(fkeyid)) = $table
+order by constraint_name, referenced_table_name, keyno";
+               
+               $constraints =& $this->GetArray($sql);
+               
+               $ADODB_FETCH_MODE = $save;
+               
+               $arr = false;
+               foreach($constraints as $constr) {
+                       //print_r($constr);
+                       $arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3]; 
+               }
+               if (!$arr) return false;
+               
+               $arr2 = false;
+               
+               foreach($arr as $k => $v) {
+                       foreach($v as $a => $b) {
+                               if ($upper) $a = strtoupper($a);
+                               $arr2[$a] = $b;
+                       }
+               }
+               return $arr2;
+       }
+       
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+       {
+               if ($mask) {$this->debug=1;
+                       $save = $this->metaTablesSQL;
+                       $mask = $this->qstr($mask);
+                       $this->metaTablesSQL .= " AND name like $mask";
+               }
+               $ret =& ADOConnection::MetaTables($ttype,$showSchema);
+               
+               if ($mask) {
+                       $this->metaTablesSQL = $save;
+               }
+               return $ret;
+       }
+       
+       function &MetaColumns($table)
+       {
+               return ADOConnection::MetaColumns($table);
+       }
+       
+       function _query($sql,$inputarr)
+       {
+               if (is_string($sql)) $sql = str_replace('||','+',$sql);
+               return ADODB_odbc::_query($sql,$inputarr);
+       }
+       
+       // "Stein-Aksel Basma" <basma@accelero.no>
+       // tested with MSSQL 2000
+       function &MetaPrimaryKeys($table)
+       {
+               $sql = "select k.column_name from information_schema.key_column_usage k,
+               information_schema.table_constraints tc 
+               where tc.constraint_name = k.constraint_name and tc.constraint_type =
+               'PRIMARY KEY' and k.table_name = '$table'";
+               
+               $a = $this->GetCol($sql);
+               if ($a && sizeof($a)>0) return $a;
+               return false;     
+       }
+       
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+       {
+               if ($nrows > 0 && $offset <= 0) {
+                       $sql = preg_replace(
+                               '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);
+                       $rs =& $this->Execute($sql,$inputarr);
+               } else
+                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+                       
+               return $rs;
+       }
+       
+       // Format date column in sql string given an input format that understands Y M D
+       function SQLDate($fmt, $col=false)
+       {       
+               if (!$col) $col = $this->sysTimeStamp;
+               $s = '';
+               
+               $len = strlen($fmt);
+               for ($i=0; $i < $len; $i++) {
+                       if ($s) $s .= '+';
+                       $ch = $fmt[$i];
+                       switch($ch) {
+                       case 'Y':
+                       case 'y':
+                               $s .= "datename(yyyy,$col)";
+                               break;
+                       case 'M':
+                               $s .= "convert(char(3),$col,0)";
+                               break;
+                       case 'm':
+                               $s .= "replace(str(month($col),2),' ','0')";
+                               break;
+                       case 'Q':
+                       case 'q':
+                               $s .= "datename(quarter,$col)";
+                               break;
+                       case 'D':
+                       case 'd':
+                               $s .= "replace(str(day($col),2),' ','0')";
+                               break;
+                       case 'h':
+                               $s .= "substring(convert(char(14),$col,0),13,2)";
+                               break;
+                       
+                       case 'H':
+                               $s .= "replace(str(datepart(hh,$col),2),' ','0')";
+                               break;
+                               
+                       case 'i':
+                               $s .= "replace(str(datepart(mi,$col),2),' ','0')";
+                               break;
+                       case 's':
+                               $s .= "replace(str(datepart(ss,$col),2),' ','0')";
+                               break;
+                       case 'a':
+                       case 'A':
+                               $s .= "substring(convert(char(19),$col,0),18,2)";
+                               break;
+                               
+                       default:
+                               if ($ch == '\\') {
+                                       $i++;
+                                       $ch = substr($fmt,$i,1);
+                               }
+                               $s .= $this->qstr($ch);
+                               break;
+                       }
+               }
+               return $s;
+       }
+
+} 
+class  ADORecordSet_odbc_mssql extends ADORecordSet_odbc {     
+       
+       var $databaseType = 'odbc_mssql';
+       
+       function ADORecordSet_odbc_mssql($id,$mode=false)
+       {
+               return $this->ADORecordSet_odbc($id,$mode);
+       }       
+}
 ?>
\ No newline at end of file
index 293af7653f08cb0a341a9b59441bce647b47f951..80c6ae8cba6a66fe668a26b92bbb0cbbe5f2fd94 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Oracle support via ODBC. Requires ODBC. Works on Windows. \r
-*/\r
-\r
-if (!defined('_ADODB_ODBC_LAYER')) {\r
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
-}\r
-\r
\r
-class  ADODB_odbc_oracle extends ADODB_odbc {  \r
-       var $databaseType = 'odbc_oracle';\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $concat_operator='||';\r
-       var $fmtDate = "'Y-m-d 00:00:00'"; \r
-       var $fmtTimeStamp = "'Y-m-d h:i:sA'";\r
-       var $metaTablesSQL = 'select table_name from cat';\r
-       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";\r
-       var $sysDate = "TRUNC(SYSDATE)";\r
-       var $sysTimeStamp = 'SYSDATE';\r
-       \r
-       //var $_bindInputArray = false;\r
-       \r
-       function ADODB_odbc_oracle()\r
-       {\r
-               $this->ADODB_odbc();\r
-       }\r
-               \r
-       function &MetaTables() \r
-       {\r
-               if ($this->metaTablesSQL) {\r
-                       $rs = $this->Execute($this->metaTablesSQL);\r
-                       if ($rs === false) return false;\r
-                       $arr = $rs->GetArray();\r
-                       $arr2 = array();\r
-                       for ($i=0; $i < sizeof($arr); $i++) {\r
-                               $arr2[] = $arr[$i][0];\r
-                       }\r
-                       $rs->Close();\r
-                       return $arr2;\r
-               }\r
-               return false;\r
-       }\r
-       \r
-       function &MetaColumns($table) \r
-       {\r
-               if (!empty($this->metaColumnsSQL)) {\r
-               \r
-                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));\r
-                       if ($rs === false) return false;\r
-\r
-                       $retarr = array();\r
-                       while (!$rs->EOF) { //print_r($rs->fields);\r
-                               $fld = new ADOFieldObject();\r
-                               $fld->name = $rs->fields[0];\r
-                               $fld->type = $rs->fields[1];\r
-                               $fld->max_length = $rs->fields[2];\r
-                               \r
-                               \r
-                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
-                               else $retarr[strtoupper($fld->name)] = $fld;\r
-                               \r
-                               $rs->MoveNext();\r
-                       }\r
-                       $rs->Close();\r
-                       return $retarr; \r
-               }\r
-               return false;\r
-       }\r
-\r
-       // returns true or false\r
-       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-       global $php_errormsg;\r
-       \r
-               $php_errormsg = '';\r
-               $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );\r
-               $this->_errorMsg = $php_errormsg;\r
-               \r
-               $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");\r
-               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
-               return $this->_connectionID != false;\r
-       }\r
-       // returns true or false\r
-       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-       global $php_errormsg;\r
-               $php_errormsg = '';\r
-               $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );\r
-               $this->_errorMsg = $php_errormsg;\r
-               \r
-               $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");\r
-               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);\r
-               return $this->_connectionID != false;\r
-       }\r
-} \r
\r
-class  ADORecordSet_odbc_oracle extends ADORecordSet_odbc {    \r
-       \r
-       var $databaseType = 'odbc_oracle';\r
-       \r
-       function ADORecordSet_odbc_oracle($id,$mode=false)\r
-       {\r
-               return $this->ADORecordSet_odbc($id,$mode);\r
-       }\r
-}\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Oracle support via ODBC. Requires ODBC. Works on Windows. 
+*/
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+
+class  ADODB_odbc_oracle extends ADODB_odbc {  
+       var $databaseType = 'odbc_oracle';
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $concat_operator='||';
+       var $fmtDate = "'Y-m-d 00:00:00'"; 
+       var $fmtTimeStamp = "'Y-m-d h:i:sA'";
+       var $metaTablesSQL = 'select table_name from cat';
+       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";
+       var $sysDate = "TRUNC(SYSDATE)";
+       var $sysTimeStamp = 'SYSDATE';
+       
+       //var $_bindInputArray = false;
+       
+       function ADODB_odbc_oracle()
+       {
+               $this->ADODB_odbc();
+       }
+               
+       function &MetaTables() 
+       {
+               if ($this->metaTablesSQL) {
+                       $rs = $this->Execute($this->metaTablesSQL);
+                       if ($rs === false) return false;
+                       $arr = $rs->GetArray();
+                       $arr2 = array();
+                       for ($i=0; $i < sizeof($arr); $i++) {
+                               $arr2[] = $arr[$i][0];
+                       }
+                       $rs->Close();
+                       return $arr2;
+               }
+               return false;
+       }
+       
+       function &MetaColumns($table) 
+       {
+               if (!empty($this->metaColumnsSQL)) {
+               
+                       $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
+                       if ($rs === false) return false;
+
+                       $retarr = array();
+                       while (!$rs->EOF) { //print_r($rs->fields);
+                               $fld = new ADOFieldObject();
+                               $fld->name = $rs->fields[0];
+                               $fld->type = $rs->fields[1];
+                               $fld->max_length = $rs->fields[2];
+                               
+                               
+                               if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     
+                               else $retarr[strtoupper($fld->name)] = $fld;
+                               
+                               $rs->MoveNext();
+                       }
+                       $rs->Close();
+                       return $retarr; 
+               }
+               return false;
+       }
+
+       // returns true or false
+       function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
+       {
+       global $php_errormsg;
+       
+               $php_errormsg = '';
+               $this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );
+               $this->_errorMsg = $php_errormsg;
+               
+               $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
+               return $this->_connectionID != false;
+       }
+       // returns true or false
+       function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
+       {
+       global $php_errormsg;
+               $php_errormsg = '';
+               $this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );
+               $this->_errorMsg = $php_errormsg;
+               
+               $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
+               //if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
+               return $this->_connectionID != false;
+       }
+} 
+class  ADORecordSet_odbc_oracle extends ADORecordSet_odbc {    
+       
+       var $databaseType = 'odbc_oracle';
+       
+       function ADORecordSet_odbc_oracle($id,$mode=false)
+       {
+               return $this->ADORecordSet_odbc($id,$mode);
+       }
+}
 ?>
\ No newline at end of file
index ec7b81165b08357f95c5a65a48d9cc7983b74dda..bcc49118d7e3bc7114b53947c1e5a1b36dad592e 100644 (file)
-<?php\r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-\r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Oracle data driver. Requires Oracle client. Works on Windows and Unix and Oracle 7 and 8.\r
-  \r
-  If you are using Oracle 8, use the oci8 driver which is much better and more reliable.\r
-  \r
-*/\r
-\r
-class ADODB_oracle extends ADOConnection {\r
-       var $databaseType = "oracle";\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $concat_operator='||';\r
-       var $_curs;\r
-       var $_initdate = true; // init date to YYYY-MM-DD\r
-       var $metaTablesSQL = 'select table_name from cat';      \r
-       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";\r
-       var $sysDate = "TO_DATE(TO_CHAR(SYSDATE,'YYYY-MM-DD'),'YYYY-MM-DD')";\r
-       var $sysTimeStamp = 'SYSDATE';\r
-       var $connectSID = true;\r
-       \r
-       function ADODB_oracle() \r
-       {\r
-       }\r
-\r
-       // format and return date string in database date format\r
-       function DBDate($d)\r
-       {\r
-               if (is_string($d)) $d = ADORecordSet::UnixDate($d);\r
-               return 'TO_DATE('.adodb_date($this->fmtDate,$d).",'YYYY-MM-DD')";\r
-       }\r
-       \r
-       // format and return date string in database timestamp format\r
-       function DBTimeStamp($ts)\r
-       {\r
-\r
-               if (is_string($ts)) $d = ADORecordSet::UnixTimeStamp($ts);\r
-               return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";\r
-       }\r
-\r
-       \r
-       function BeginTrans()\r
-       {         \r
-                $this->autoCommit = false;\r
-                ora_commitoff($this->_connectionID);\r
-                return true;\r
-       }\r
-\r
-       \r
-       function CommitTrans($ok=true) \r
-       { \r
-                  if (!$ok) return $this->RollbackTrans();\r
-                  $ret = ora_commit($this->_connectionID);\r
-                  ora_commiton($this->_connectionID);\r
-                  return $ret;\r
-       }\r
-\r
-       \r
-       function RollbackTrans()\r
-       {\r
-               $ret = ora_rollback($this->_connectionID);\r
-               ora_commiton($this->_connectionID);\r
-               return $ret;\r
-       }\r
-\r
-\r
-       /* there seems to be a bug in the oracle extension -- always returns ORA-00000 - no error */\r
-       function ErrorMsg() \r
-       {\r
-               $this->_errorMsg = @ora_error($this->_curs);\r
-               if (!$this->_errorMsg) $this->_errorMsg = @ora_error($this->_connectionID);\r
-               return $this->_errorMsg;\r
-       }\r
-\r
\r
-       function ErrorNo() \r
-       {\r
-               $err = @ora_errorcode($this->_curs);\r
-               if (!$err) return @ora_errorcode($this->_connectionID);\r
-       }\r
-\r
-       \r
-\r
-               // returns true or false\r
-               function _connect($argHostname, $argUsername, $argPassword, $argDatabasename, $mode=0)\r
-               {\r
-            // G. Giunta 2003/08/13 - This looks danegrously suspicious: why should we want to set\r
-            // the oracle home to the host name of remote DB?\r
-//                     if ($argHostname) putenv("ORACLE_HOME=$argHostname");\r
-\r
-                       if($argHostname) { // code copied from version submitted for oci8 by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>\r
-                               if (empty($argDatabasename)) $argDatabasename = $argHostname;\r
-                               else {\r
-                                       if(strpos($argHostname,":")) {\r
-                                               $argHostinfo=explode(":",$argHostname);\r
-                                               $argHostname=$argHostinfo[0];\r
-                                               $argHostport=$argHostinfo[1];\r
-                                       } else {\r
-                                               $argHostport="1521";\r
-                                       }\r
-\r
-\r
-                                       if ($this->connectSID) {\r
-                                               $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname\r
-                                               .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";\r
-                                       } else\r
-                                               $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname\r
-                                               .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";\r
-                               }\r
-\r
-                       }\r
-\r
-                       if ($argDatabasename) $argUsername .= "@$argDatabasename";\r
-\r
-               //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";\r
-                       if ($mode = 1)\r
-                               $this->_connectionID = ora_plogon($argUsername,$argPassword);\r
-                       else\r
-                               $this->_connectionID = ora_logon($argUsername,$argPassword);\r
-                       if ($this->_connectionID === false) return false;\r
-                       if ($this->autoCommit) ora_commiton($this->_connectionID);\r
-                       if ($this->_initdate) {\r
-                               $rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");\r
-                               if ($rs) ora_close($rs);\r
-                       }\r
-\r
-                       return true;\r
-               }\r
-\r
-\r
-               // returns true or false\r
-               function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-               {\r
-                       return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, 1);\r
-               }\r
-\r
-\r
-               // returns query ID if successful, otherwise false\r
-               function _query($sql,$inputarr=false)\r
-               {\r
-                       $curs = ora_open($this->_connectionID);\r
-                \r
-                       if ($curs === false) return false;\r
-                       $this->_curs = $curs;\r
-                       if (!ora_parse($curs,$sql)) return false;\r
-                       if (ora_exec($curs)) return $curs;\r
-               \r
-                       @ora_close($curs);\r
-                       return false;\r
-               }\r
-\r
-\r
-               // returns true or false\r
-               function _close()\r
-               {\r
-                       return @ora_logoff($this->_connectionID);\r
-               }\r
-\r
-\r
-\r
-}\r
-\r
-\r
-/*--------------------------------------------------------------------------------------\r
-                Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordset_oracle extends ADORecordSet {\r
-\r
-       var $databaseType = "oracle";\r
-       var $bind = false;\r
-\r
-       function ADORecordset_oracle($queryID,$mode=false)\r
-       {\r
-               \r
-               if ($mode === false) { \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               $this->fetchMode = $mode;\r
-               \r
-               $this->_queryID = $queryID;\r
-       \r
-               $this->_inited = true;\r
-               $this->fields = array();\r
-               if ($queryID) {\r
-                       $this->_currentRow = 0;\r
-                       $this->EOF = !$this->_fetch();\r
-                       @$this->_initrs();\r
-               } else {\r
-                       $this->_numOfRows = 0;\r
-                       $this->_numOfFields = 0;\r
-                       $this->EOF = true;\r
-               }\r
-               \r
-               return $this->_queryID;\r
-       }\r
-\r
-\r
-\r
-          /*           Returns: an object containing field information.\r
-                          Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
-                          fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
-                          fetchField() is retrieved.           */\r
-\r
-          function FetchField($fieldOffset = -1)\r
-          {\r
-                       $fld = new ADOFieldObject;\r
-                       $fld->name = ora_columnname($this->_queryID, $fieldOffset);\r
-                       $fld->type = ora_columntype($this->_queryID, $fieldOffset);\r
-                       $fld->max_length = ora_columnsize($this->_queryID, $fieldOffset);\r
-                       return $fld;\r
-          }\r
-\r
-       /* Use associative array to get fields array */\r
-       function Fields($colname)\r
-       {\r
-               if (!$this->bind) {\r
-                       $this->bind = array();\r
-                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                               $o = $this->FetchField($i);\r
-                               $this->bind[strtoupper($o->name)] = $i;\r
-                       }\r
-               }\r
-               \r
-                return $this->fields[$this->bind[strtoupper($colname)]];\r
-       }\r
-       \r
-   function _initrs()\r
-   {\r
-                  $this->_numOfRows = -1;\r
-                  $this->_numOfFields = @ora_numcols($this->_queryID);\r
-   }\r
-\r
-\r
-   function _seek($row)\r
-   {\r
-                  return false;\r
-   }\r
-\r
-   function _fetch($ignore_fields=false) {\r
-// should remove call by reference, but ora_fetch_into requires it in 4.0.3pl1\r
-               if ($this->fetchMode & ADODB_FETCH_ASSOC)\r
-                       return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);\r
-               else \r
-                       return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS);\r
-   }\r
-\r
-   /*          close() only needs to be called if you are worried about using too much memory while your script\r
-                  is running. All associated result memory for the specified result identifier will automatically be freed.            */\r
-\r
-   function _close() \r
-{\r
-                  return @ora_close($this->_queryID);\r
-   }\r
-\r
-       function MetaType($t,$len=-1)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               \r
-               switch (strtoupper($t)) {\r
-               case 'VARCHAR':\r
-               case 'VARCHAR2':\r
-               case 'CHAR':\r
-               case 'VARBINARY':\r
-               case 'BINARY':\r
-                               if ($len <= $this->blobSize) return 'C';\r
-               case 'LONG':\r
-               case 'LONG VARCHAR':\r
-               case 'CLOB':\r
-               return 'X';\r
-               case 'LONG RAW':\r
-               case 'LONG VARBINARY':\r
-               case 'BLOB':\r
-                               return 'B';\r
-               \r
-               case 'DATE': return 'D';\r
-               \r
-               //case 'T': return 'T';\r
-               \r
-               case 'BIT': return 'L';\r
-               case 'INT': \r
-               case 'SMALLINT':\r
-               case 'INTEGER': return 'I';\r
-               default: return 'N';\r
-               }\r
-       }\r
-}\r
+<?php
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+
+  Latest version is available at http://php.weblogs.com/
+  
+  Oracle data driver. Requires Oracle client. Works on Windows and Unix and Oracle 7 and 8.
+  
+  If you are using Oracle 8, use the oci8 driver which is much better and more reliable.
+  
+*/
+
+class ADODB_oracle extends ADOConnection {
+       var $databaseType = "oracle";
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $concat_operator='||';
+       var $_curs;
+       var $_initdate = true; // init date to YYYY-MM-DD
+       var $metaTablesSQL = 'select table_name from cat';      
+       var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";
+       var $sysDate = "TO_DATE(TO_CHAR(SYSDATE,'YYYY-MM-DD'),'YYYY-MM-DD')";
+       var $sysTimeStamp = 'SYSDATE';
+       var $connectSID = true;
+       
+       function ADODB_oracle() 
+       {
+       }
+
+       // format and return date string in database date format
+       function DBDate($d)
+       {
+               if (is_string($d)) $d = ADORecordSet::UnixDate($d);
+               return 'TO_DATE('.adodb_date($this->fmtDate,$d).",'YYYY-MM-DD')";
+       }
+       
+       // format and return date string in database timestamp format
+       function DBTimeStamp($ts)
+       {
+
+               if (is_string($ts)) $d = ADORecordSet::UnixTimeStamp($ts);
+               return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";
+       }
+
+       
+       function BeginTrans()
+       {         
+                $this->autoCommit = false;
+                ora_commitoff($this->_connectionID);
+                return true;
+       }
+
+       
+       function CommitTrans($ok=true) 
+       { 
+                  if (!$ok) return $this->RollbackTrans();
+                  $ret = ora_commit($this->_connectionID);
+                  ora_commiton($this->_connectionID);
+                  return $ret;
+       }
+
+       
+       function RollbackTrans()
+       {
+               $ret = ora_rollback($this->_connectionID);
+               ora_commiton($this->_connectionID);
+               return $ret;
+       }
+
+
+       /* there seems to be a bug in the oracle extension -- always returns ORA-00000 - no error */
+       function ErrorMsg() 
+       {
+               $this->_errorMsg = @ora_error($this->_curs);
+               if (!$this->_errorMsg) $this->_errorMsg = @ora_error($this->_connectionID);
+               return $this->_errorMsg;
+       }
+
+       function ErrorNo() 
+       {
+               $err = @ora_errorcode($this->_curs);
+               if (!$err) return @ora_errorcode($this->_connectionID);
+       }
+
+       
+
+               // returns true or false
+               function _connect($argHostname, $argUsername, $argPassword, $argDatabasename, $mode=0)
+               {
+            // G. Giunta 2003/08/13 - This looks danegrously suspicious: why should we want to set
+            // the oracle home to the host name of remote DB?
+//                     if ($argHostname) putenv("ORACLE_HOME=$argHostname");
+
+                       if($argHostname) { // code copied from version submitted for oci8 by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>
+                               if (empty($argDatabasename)) $argDatabasename = $argHostname;
+                               else {
+                                       if(strpos($argHostname,":")) {
+                                               $argHostinfo=explode(":",$argHostname);
+                                               $argHostname=$argHostinfo[0];
+                                               $argHostport=$argHostinfo[1];
+                                       } else {
+                                               $argHostport="1521";
+                                       }
+
+
+                                       if ($this->connectSID) {
+                                               $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
+                                               .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
+                                       } else
+                                               $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
+                                               .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";
+                               }
+
+                       }
+
+                       if ($argDatabasename) $argUsername .= "@$argDatabasename";
+
+               //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
+                       if ($mode = 1)
+                               $this->_connectionID = ora_plogon($argUsername,$argPassword);
+                       else
+                               $this->_connectionID = ora_logon($argUsername,$argPassword);
+                       if ($this->_connectionID === false) return false;
+                       if ($this->autoCommit) ora_commiton($this->_connectionID);
+                       if ($this->_initdate) {
+                               $rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");
+                               if ($rs) ora_close($rs);
+                       }
+
+                       return true;
+               }
+
+
+               // returns true or false
+               function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+               {
+                       return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, 1);
+               }
+
+
+               // returns query ID if successful, otherwise false
+               function _query($sql,$inputarr=false)
+               {
+                       $curs = ora_open($this->_connectionID);
+                
+                       if ($curs === false) return false;
+                       $this->_curs = $curs;
+                       if (!ora_parse($curs,$sql)) return false;
+                       if (ora_exec($curs)) return $curs;
+               
+                       @ora_close($curs);
+                       return false;
+               }
+
+
+               // returns true or false
+               function _close()
+               {
+                       return @ora_logoff($this->_connectionID);
+               }
+
+
+
+}
+
+
+/*--------------------------------------------------------------------------------------
+                Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_oracle extends ADORecordSet {
+
+       var $databaseType = "oracle";
+       var $bind = false;
+
+       function ADORecordset_oracle($queryID,$mode=false)
+       {
+               
+               if ($mode === false) { 
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               $this->fetchMode = $mode;
+               
+               $this->_queryID = $queryID;
+       
+               $this->_inited = true;
+               $this->fields = array();
+               if ($queryID) {
+                       $this->_currentRow = 0;
+                       $this->EOF = !$this->_fetch();
+                       @$this->_initrs();
+               } else {
+                       $this->_numOfRows = 0;
+                       $this->_numOfFields = 0;
+                       $this->EOF = true;
+               }
+               
+               return $this->_queryID;
+       }
+
+
+
+          /*           Returns: an object containing field information.
+                          Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+                          fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+                          fetchField() is retrieved.           */
+
+          function FetchField($fieldOffset = -1)
+          {
+                       $fld = new ADOFieldObject;
+                       $fld->name = ora_columnname($this->_queryID, $fieldOffset);
+                       $fld->type = ora_columntype($this->_queryID, $fieldOffset);
+                       $fld->max_length = ora_columnsize($this->_queryID, $fieldOffset);
+                       return $fld;
+          }
+
+       /* Use associative array to get fields array */
+       function Fields($colname)
+       {
+               if (!$this->bind) {
+                       $this->bind = array();
+                       for ($i=0; $i < $this->_numOfFields; $i++) {
+                               $o = $this->FetchField($i);
+                               $this->bind[strtoupper($o->name)] = $i;
+                       }
+               }
+               
+                return $this->fields[$this->bind[strtoupper($colname)]];
+       }
+       
+   function _initrs()
+   {
+                  $this->_numOfRows = -1;
+                  $this->_numOfFields = @ora_numcols($this->_queryID);
+   }
+
+
+   function _seek($row)
+   {
+                  return false;
+   }
+
+   function _fetch($ignore_fields=false) {
+// should remove call by reference, but ora_fetch_into requires it in 4.0.3pl1
+               if ($this->fetchMode & ADODB_FETCH_ASSOC)
+                       return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
+               else 
+                       return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS);
+   }
+
+   /*          close() only needs to be called if you are worried about using too much memory while your script
+                  is running. All associated result memory for the specified result identifier will automatically be freed.            */
+
+   function _close() 
+{
+                  return @ora_close($this->_queryID);
+   }
+
+       function MetaType($t,$len=-1)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               
+               switch (strtoupper($t)) {
+               case 'VARCHAR':
+               case 'VARCHAR2':
+               case 'CHAR':
+               case 'VARBINARY':
+               case 'BINARY':
+                               if ($len <= $this->blobSize) return 'C';
+               case 'LONG':
+               case 'LONG VARCHAR':
+               case 'CLOB':
+               return 'X';
+               case 'LONG RAW':
+               case 'LONG VARBINARY':
+               case 'BLOB':
+                               return 'B';
+               
+               case 'DATE': return 'D';
+               
+               //case 'T': return 'T';
+               
+               case 'BIT': return 'L';
+               case 'INT': 
+               case 'SMALLINT':
+               case 'INTEGER': return 'I';
+               default: return 'N';
+               }
+       }
+}
 ?>
\ No newline at end of file
index 81ad7a0d4e6b806588ec0a53b9614f86e229d59c..f269b9a9105beb7dd0e089263fe46ab422b0607d 100644 (file)
@@ -1,14 +1,14 @@
-<?php\r
-/*\r
- V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 4.\r
-  \r
-  NOTE: Since 3.31, this file is no longer used, and the "postgres" driver is\r
-  remapped to "postgres7". Maintaining multiple postgres drivers is no easy\r
-  job, so hopefully this will ensure greater consistency and fewer bugs.\r
-*/\r
-\r
+<?php
+/*
+ V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 4.
+  
+  NOTE: Since 3.31, this file is no longer used, and the "postgres" driver is
+  remapped to "postgres7". Maintaining multiple postgres drivers is no easy
+  job, so hopefully this will ensure greater consistency and fewer bugs.
+*/
+
 ?>
\ No newline at end of file
index a259257d6974b07a17f0184e96d39fb6a81d8c72..257947f98bb1380deadb8563f49a09a235be2dc6 100644 (file)
-<?php\r
-/*\r
- V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 8.\r
-  \r
-  Original version derived from Alberto Cerezal (acerezalp@dbnet.es) - DBNet Informatica & Comunicaciones. \r
-  08 Nov 2000 jlim - Minor corrections, removing mysql stuff\r
-  09 Nov 2000 jlim - added insertid support suggested by "Christopher Kings-Lynne" <chriskl@familyhealth.com.au>\r
-                                       jlim - changed concat operator to || and data types to MetaType to match documented pgsql types \r
-                       see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm  \r
-  22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <raser@mail.zen.com.tw>\r
-  27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <leen@wirehub.nl>\r
-  15 Dec 2000 jlim - added changes suggested by Additional code changes by "Eric G. Werk" egw@netguide.dk. \r
-  31 Jan 2002 jlim - finally installed postgresql. testing\r
-  01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type\r
-  \r
-  See http://www.varlena.com/varlena/GeneralBits/47.php\r
-  \r
-       -- What indexes are on my table?\r
-       select * from pg_indexes where tablename = 'tablename';\r
-       \r
-       -- What triggers are on my table?\r
-       select c.relname as "Table", t.tgname as "Trigger Name", \r
-          t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled",\r
-          t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table",\r
-          p.proname as "Function Name"\r
-       from pg_trigger t, pg_class c, pg_class cc, pg_proc p\r
-       where t.tgfoid = p.oid and t.tgrelid = c.oid\r
-          and t.tgconstrrelid = cc.oid\r
-          and c.relname = 'tablename';\r
-       \r
-       -- What constraints are on my table?\r
-       select r.relname as "Table", c.conname as "Constraint Name",\r
-          contype as "Constraint Type", conkey as "Key Columns",\r
-          confkey as "Foreign Columns", consrc as "Source"\r
-       from pg_class r, pg_constraint c\r
-       where r.oid = c.conrelid\r
-          and relname = 'tablename';\r
-\r
-*/\r
-\r
-function adodb_addslashes($s)\r
-{\r
-       $len = strlen($s);\r
-       if ($len == 0) return "''";\r
-       if (strncmp($s,"'",1) === 0 && substr(s,$len-1) == "'") return $s; // already quoted\r
-       \r
-       return "'".addslashes($s)."'";\r
-}\r
-\r
-class ADODB_postgres64 extends ADOConnection{\r
-       var $databaseType = 'postgres64';\r
-       var $dataProvider = 'postgres';\r
-       var $hasInsertID = true;\r
-       var $_resultid = false;\r
-       var $concat_operator='||';\r
-       var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";\r
-    var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' union \r
-        select viewname,'V' from pg_views where viewname not like 'pg\_%'";\r
-       //"select tablename from pg_tables where tablename not like 'pg_%' order by 1";\r
-       var $isoDates = true; // accepts dates in ISO format\r
-       var $sysDate = "CURRENT_DATE";\r
-       var $sysTimeStamp = "CURRENT_TIMESTAMP";\r
-       var $blobEncodeType = 'C';\r
-       var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum \r
-               FROM pg_class c, pg_attribute a,pg_type t \r
-               WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'\r
-AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";\r
-\r
-       var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum \r
-FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n \r
-WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s'))\r
- and c.relnamespace=n.oid and n.nspname='%s' \r
-       and a.attname not like '....%%' AND a.attnum > 0 \r
-       AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";\r
-       \r
-       // get primary key etc -- from Freek Dijkstra\r
-       var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key \r
-       FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";\r
-       \r
-       var $hasAffectedRows = true;\r
-       var $hasLimit = false;  // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10\r
-       // below suggested by Freek Dijkstra \r
-       var $true = 't';                // string that represents TRUE for a database\r
-       var $false = 'f';               // string that represents FALSE for a database\r
-       var $fmtDate = "'Y-m-d'";       // used by DBDate() as the default date format used by the database\r
-       var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.\r
-       var $hasMoveFirst = true;\r
-       var $hasGenID = true;\r
-       var $_genIDSQL = "SELECT NEXTVAL('%s')";\r
-       var $_genSeqSQL = "CREATE SEQUENCE %s START %s";\r
-       var $_dropSeqSQL = "DROP SEQUENCE %s";\r
-       var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";\r
-       var $random = 'random()';               /// random function\r
-       var $autoRollback = true; // apparently pgsql does not autorollback properly before 4.3.4\r
-                                                       // http://bugs.php.net/bug.php?id=25404\r
-       \r
-       // The last (fmtTimeStamp is not entirely correct: \r
-       // PostgreSQL also has support for time zones, \r
-       // and writes these time in this format: "2001-03-01 18:59:26+02". \r
-       // There is no code for the "+02" time zone information, so I just left that out. \r
-       // I'm not familiar enough with both ADODB as well as Postgres \r
-       // to know what the concequences are. The other values are correct (wheren't in 0.94)\r
-       // -- Freek Dijkstra \r
-\r
-       function ADODB_postgres64() \r
-       {\r
-       // changes the metaColumnsSQL, adds columns: attnum[6]\r
-       }\r
-       \r
-       function ServerInfo()\r
-       {\r
-               if (isset($this->version)) return $this->version;\r
-               \r
-               $arr['description'] = $this->GetOne("select version()");\r
-               $arr['version'] = ADOConnection::_findvers($arr['description']);\r
-               $this->version = $arr;\r
-               return $arr;\r
-       }\r
-/*\r
-       function IfNull( $field, $ifNull ) \r
-       {\r
-               return " NULLIF($field, $ifNull) "; // if PGSQL\r
-       }\r
-*/\r
-       // get the last id - never tested\r
-       function pg_insert_id($tablename,$fieldname)\r
-       {\r
-               $result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq");\r
-               if ($result) {\r
-                       $arr = @pg_fetch_row($result,0);\r
-                       pg_freeresult($result);\r
-                       if (isset($arr[0])) return $arr[0];\r
-               }\r
-               return false;\r
-       }\r
-       \r
-/* Warning from http://www.php.net/manual/function.pg-getlastoid.php:\r
-Using a OID as a unique identifier is not generally wise. \r
-Unless you are very careful, you might end up with a tuple having \r
-a different OID if a database must be reloaded. */\r
-       function _insertid()\r
-       {\r
-               if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;\r
-               return pg_getlastoid($this->_resultid);\r
-       }\r
-\r
-// I get this error with PHP before 4.0.6 - jlim\r
-// Warning: This compilation does not support pg_cmdtuples() in d:/inetpub/wwwroot/php/adodb/adodb-postgres.inc.php on line 44\r
-   function _affectedrows()\r
-   {\r
-               if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;\r
-               return pg_cmdtuples($this->_resultid);\r
-   }\r
-   \r
-       \r
-               // returns true/false\r
-       function BeginTrans()\r
-       {\r
-               if ($this->transOff) return true;\r
-               $this->transCnt += 1;\r
-               return @pg_Exec($this->_connectionID, "begin");\r
-       }\r
-       \r
-       function RowLock($tables,$where) \r
-       {\r
-               if (!$this->transCnt) $this->BeginTrans();\r
-               return $this->GetOne("select 1 as ignore from $tables where $where for update");\r
-       }\r
-\r
-       // returns true/false. \r
-       function CommitTrans($ok=true) \r
-       { \r
-               if ($this->transOff) return true;\r
-               if (!$ok) return $this->RollbackTrans();\r
-               \r
-               $this->transCnt -= 1;\r
-               return @pg_Exec($this->_connectionID, "commit");\r
-       }\r
-       \r
-       // returns true/false\r
-       function RollbackTrans()\r
-       {\r
-               if ($this->transOff) return true;\r
-               $this->transCnt -= 1;\r
-               return @pg_Exec($this->_connectionID, "rollback");\r
-       }\r
-       \r
-       function &MetaTables($ttype=false,$showSchema=false,$mask=false) \r
-       {       \r
-               if ($mask) {\r
-                       $save = $this->metaTablesSQL;\r
-                       $mask = $this->qstr(strtolower($mask));\r
-                       $this->metaTablesSQL = "\r
-select tablename,'T' from pg_tables where tablename like $mask union \r
-select viewname,'V' from pg_views where viewname like $mask";\r
-               }\r
-               $ret =& ADOConnection::MetaTables($ttype,$showSchema);\r
-               \r
-               if ($mask) {\r
-                       $this->metaTablesSQL = $save;\r
-               }\r
-               return $ret;\r
-       }\r
-       \r
-       /*\r
-       // if magic quotes disabled, use pg_escape_string()\r
-       function qstr($s,$magic_quotes=false)\r
-       {\r
-               if (!$magic_quotes) {\r
-                       if (ADODB_PHPVER >= 0x4200) {\r
-                               return  "'".pg_escape_string($s)."'";\r
-                       }\r
-                       if ($this->replaceQuote[0] == '\\'){\r
-                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);\r
-                       }\r
-                       return  "'".str_replace("'",$this->replaceQuote,$s)."'"; \r
-               }\r
-               \r
-               // undo magic quotes for "\r
-               $s = str_replace('\\"','"',$s);\r
-               return "'$s'";\r
-       }\r
-       */\r
-       \r
-       \r
-       // Format date column in sql string given an input format that understands Y M D\r
-       function SQLDate($fmt, $col=false)\r
-       {       \r
-               if (!$col) $col = $this->sysTimeStamp;\r
-               $s = 'TO_CHAR('.$col.",'";\r
-               \r
-               $len = strlen($fmt);\r
-               for ($i=0; $i < $len; $i++) {\r
-                       $ch = $fmt[$i];\r
-                       switch($ch) {\r
-                       case 'Y':\r
-                       case 'y':\r
-                               $s .= 'YYYY';\r
-                               break;\r
-                       case 'Q':\r
-                       case 'q':\r
-                               $s .= 'Q';\r
-                               break;\r
-                               \r
-                       case 'M':\r
-                               $s .= 'Mon';\r
-                               break;\r
-                               \r
-                       case 'm':\r
-                               $s .= 'MM';\r
-                               break;\r
-                       case 'D':\r
-                       case 'd':\r
-                               $s .= 'DD';\r
-                               break;\r
-                       \r
-                       case 'H':\r
-                               $s.= 'HH24';\r
-                               break;\r
-                               \r
-                       case 'h':\r
-                               $s .= 'HH';\r
-                               break;\r
-                               \r
-                       case 'i':\r
-                               $s .= 'MI';\r
-                               break;\r
-                       \r
-                       case 's':\r
-                               $s .= 'SS';\r
-                               break;\r
-                       \r
-                       case 'a':\r
-                       case 'A':\r
-                               $s .= 'AM';\r
-                               break;\r
-                               \r
-                       default:\r
-                       // handle escape characters...\r
-                               if ($ch == '\\') {\r
-                                       $i++;\r
-                                       $ch = substr($fmt,$i,1);\r
-                               }\r
-                               if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;\r
-                               else $s .= '"'.$ch.'"';\r
-                               \r
-                       }\r
-               }\r
-               return $s. "')";\r
-       }\r
-       \r
-       \r
-       \r
-       /* \r
-       * Load a Large Object from a file \r
-       * - the procedure stores the object id in the table and imports the object using \r
-       * postgres proprietary blob handling routines \r
-       *\r
-       * contributed by Mattia Rossi mattia@technologist.com\r
-       * modified for safe mode by juraj chlebec\r
-       */ \r
-       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') \r
-       { \r
-               pg_exec ($this->_connectionID, "begin"); \r
-               \r
-               $fd = fopen($path,'r');\r
-               $contents = fread($fd,filesize($path));\r
-               fclose($fd);\r
-               \r
-               $oid = pg_lo_create($this->_connectionID);\r
-               $handle = pg_lo_open($this->_connectionID, $oid, 'w');\r
-               pg_lo_write($handle, $contents);\r
-               pg_lo_close($handle);\r
-               \r
-               // $oid = pg_lo_import ($path); \r
-               pg_exec($this->_connectionID, "commit"); \r
-               $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype); \r
-               $rez = !empty($rs); \r
-               return $rez; \r
-       } \r
-       \r
-       /* \r
-       * If an OID is detected, then we use pg_lo_* to open the oid file and read the\r
-       * real blob from the db using the oid supplied as a parameter. If you are storing\r
-       * blobs using bytea, we autodetect and process it so this function is not needed.\r
-       *\r
-       * contributed by Mattia Rossi mattia@technologist.com\r
-       *\r
-       * see http://www.postgresql.org/idocs/index.php?largeobjects.html\r
-       */ \r
-       function BlobDecode( $blob) \r
-       { \r
-               if (strlen($blob) > 24) return $blob;\r
-               \r
-               @pg_exec($this->_connectionID,"begin"); \r
-               $fd = @pg_lo_open($this->_connectionID,$blob,"r");\r
-               if ($fd === false) {\r
-                       @pg_exec($this->_connectionID,"commit");\r
-                       return $blob;\r
-               }\r
-               $realblob = @pg_loreadall($fd); \r
-               @pg_loclose($fd); \r
-               @pg_exec($this->_connectionID,"commit"); \r
-               return $realblob;\r
-       } \r
-       \r
-       /* \r
-               See http://www.postgresql.org/idocs/index.php?datatype-binary.html\r
-               \r
-               NOTE: SQL string literals (input strings) must be preceded with two backslashes \r
-               due to the fact that they must pass through two parsers in the PostgreSQL \r
-               backend.\r
-       */\r
-       function BlobEncode($blob)\r
-       {\r
-               if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob);\r
-               \r
-               /*92=backslash, 0=null, 39=single-quote*/\r
-               $badch = array(chr(92),chr(0),chr(39)); # \  null  '\r
-               $fixch = array('\\\\134','\\\\000','\\\\047');\r
-               return adodb_str_replace($badch,$fixch,$blob);\r
-               \r
-               // note that there is a pg_escape_bytea function only for php 4.2.0 or later\r
-       }\r
-       \r
-       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')\r
-       {\r
-               // do not use bind params which uses qstr(), as blobencode() already quotes data\r
-               return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where");\r
-       }\r
-       \r
-       function OffsetDate($dayFraction,$date=false)\r
-       {               \r
-               if (!$date) $date = $this->sysDate;\r
-               return "($date+interval'$dayFraction days')";\r
-       }\r
-       \r
-\r
-       // for schema support, pass in the $table param "$schema.$tabname".\r
-       // converts field names to lowercase, $upper is ignored\r
-       function &MetaColumns($table,$upper=true) \r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $schema = false;\r
-               $this->_findschema($table,$schema);\r
-               \r
-               $table = strtolower($table);\r
-\r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);\r
-               \r
-               if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));\r
-               else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));\r
-               if (isset($savem)) $this->SetFetchMode($savem);\r
-               $ADODB_FETCH_MODE = $save;\r
-               \r
-               if ($rs === false) return false;\r
-               \r
-               if (!empty($this->metaKeySQL)) {\r
-                       // If we want the primary keys, we have to issue a separate query\r
-                       // Of course, a modified version of the metaColumnsSQL query using a \r
-                       // LEFT JOIN would have been much more elegant, but postgres does \r
-                       // not support OUTER JOINS. So here is the clumsy way.\r
-                       \r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-                       \r
-                       $rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));\r
-                       // fetch all result in once for performance.\r
-                       $keys =& $rskey->GetArray();\r
-                       if (isset($savem)) $this->SetFetchMode($savem);\r
-                       $ADODB_FETCH_MODE = $save;\r
-                       \r
-                       $rskey->Close();\r
-                       unset($rskey);\r
-               }\r
-\r
-               $rsdefa = array();\r
-               if (!empty($this->metaDefaultsSQL)) {\r
-                       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-                       $sql = sprintf($this->metaDefaultsSQL, ($table));\r
-                       $rsdef = $this->Execute($sql);\r
-                       if (isset($savem)) $this->SetFetchMode($savem);\r
-                       $ADODB_FETCH_MODE = $save;\r
-                       \r
-                       if ($rsdef) {\r
-                               while (!$rsdef->EOF) {\r
-                                       $num = $rsdef->fields['num'];\r
-                                       $s = $rsdef->fields['def'];\r
-                                       if (substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */\r
-                                               $s = substr($s, 1);\r
-                                               $s = substr($s, 0, strlen($s) - 1);\r
-                                       }\r
-\r
-                                       $rsdefa[$num] = $s;\r
-                                       $rsdef->MoveNext();\r
-                               }\r
-                       } else {\r
-                               ADOConnection::outp( "==> SQL => " . $sql);\r
-                       }\r
-                       unset($rsdef);\r
-               }\r
-       \r
-               $retarr = array();\r
-               while (!$rs->EOF) {     \r
-                       $fld = new ADOFieldObject();\r
-                       $fld->name = $rs->fields[0];\r
-                       $fld->type = $rs->fields[1];\r
-                       $fld->max_length = $rs->fields[2];\r
-                       if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;\r
-                       if ($fld->max_length <= 0) $fld->max_length = -1;\r
-                       \r
-                       // dannym\r
-                       // 5 hasdefault; 6 num-of-column\r
-                       $fld->has_default = ($rs->fields[5] == 't');\r
-                       if ($fld->has_default) {\r
-                               $fld->default_value = $rsdefa[$rs->fields[6]];\r
-                       }\r
-\r
-                       //Freek\r
-                       if ($rs->fields[4] == $this->true) {\r
-                               $fld->not_null = true;\r
-                       }\r
-                       \r
-                       // Freek\r
-                       if (is_array($keys)) {\r
-                               foreach($keys as $key) {\r
-                                       if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) \r
-                                               $fld->primary_key = true;\r
-                                       if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) \r
-                                               $fld->unique = true; // What name is more compatible?\r
-                               }\r
-                       }\r
-                       \r
-                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     \r
-                       else $retarr[($upper) ? strtoupper($fld->name) : $fld->name] = $fld;\r
-                       \r
-                       $rs->MoveNext();\r
-               }\r
-               $rs->Close();\r
-               return $retarr; \r
-               \r
-       }\r
-\r
-         function &MetaIndexes ($table, $primary = FALSE)\r
-      {\r
-         global $ADODB_FETCH_MODE;\r
-                \r
-                               $schema = false;\r
-                               $this->_findschema($table,$schema);\r
-                               \r
-                               if ($schema) { // requires pgsql 7.3+ - pg_namespace used.\r
-                                       $sql = '\r
-SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns" \r
-FROM pg_catalog.pg_class c \r
-JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid \r
-JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid\r
-       ,pg_namespace n \r
-WHERE c2.relname=\'%s\' and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\' AND i.indisprimary=false';\r
-                               } else {\r
-                       $sql = '\r
-SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"\r
-FROM pg_catalog.pg_class c\r
-JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid\r
-JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid\r
-WHERE c2.relname=\'%s\'';\r
-                       }\r
-                                           \r
-                if ($primary == FALSE) {\r
-                        $sql .= ' AND i.indisprimary=false;';\r
-                }\r
-                \r
-                $save = $ADODB_FETCH_MODE;\r
-                $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-                if ($this->fetchMode !== FALSE) {\r
-                        $savem = $this->SetFetchMode(FALSE);\r
-                }\r
-                \r
-                $rs = $this->Execute(sprintf($sql,$table,$schema));\r
-                \r
-                if (isset($savem)) {\r
-                        $this->SetFetchMode($savem);\r
-                }\r
-                $ADODB_FETCH_MODE = $save;\r
-                \r
-                if (!is_object($rs)) {\r
-                        return FALSE;\r
-                }\r
-                \r
-                $col_names = $this->MetaColumnNames($table);\r
-                $indexes = array();\r
-                \r
-                while ($row = $rs->FetchRow()) {\r
-                        $columns = array();\r
-                        \r
-                        foreach (explode(' ', $row[2]) as $col) {\r
-                                $columns[] = $col_names[$col - 1];\r
-                        }\r
-                        \r
-                        $indexes[$row[0]] = array(\r
-                                'unique' => ($row[1] == 't'),\r
-                                'columns' => $columns\r
-                        );\r
-                }\r
-                \r
-                return $indexes;\r
-        }\r
-\r
-       // returns true or false\r
-       //\r
-       // examples:\r
-       //      $db->Connect("host=host1 user=user1 password=secret port=4341");\r
-       //      $db->Connect('host1','user1','secret');\r
-       function _connect($str,$user='',$pwd='',$db='',$ctype=0)\r
-       {\r
-               \r
-               if (!function_exists('pg_pconnect')) return false;\r
-               \r
-               $this->_errorMsg = false;\r
-               \r
-               if ($user || $pwd || $db) {\r
-                       $user = adodb_addslashes($user);\r
-                       $pwd = adodb_addslashes($pwd);\r
-                       if (strlen($db) == 0) $db = 'template1';\r
-                       $db = adodb_addslashes($db);\r
-                       if ($str)  {\r
-                               $host = split(":", $str);\r
-                               if ($host[0]) $str = "host=".adodb_addslashes($host[0]);\r
-                               else $str = 'host=localhost';\r
-                               if (isset($host[1])) $str .= " port=$host[1]";\r
-                       }\r
-                               if ($user) $str .= " user=".$user;\r
-                               if ($pwd)  $str .= " password=".$pwd;\r
-                               if ($db)   $str .= " dbname=".$db;\r
-               }\r
-\r
-               //if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432";\r
-               \r
-               if ($ctype === 1) { // persistent\r
-                       $this->_connectionID = pg_pconnect($str);\r
-               } else {\r
-                       if ($ctype === -1) { // nconnect, we trick pgsql ext by changing the connection str\r
-                       static $ncnt;\r
-                       \r
-                               if (empty($ncnt)) $ncnt = 1;\r
-                               else $ncnt += 1;\r
-                               \r
-                               $str .= str_repeat(' ',$ncnt);\r
-                       }\r
-                       $this->_connectionID = pg_connect($str);\r
-               }\r
-               if ($this->_connectionID === false) return false;\r
-               $this->Execute("set datestyle='ISO'");\r
-               return true;\r
-       }\r
-       \r
-       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)\r
-       {\r
-               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1);\r
-       }\r
-        \r
-       // returns true or false\r
-       //\r
-       // examples:\r
-       //      $db->PConnect("host=host1 user=user1 password=secret port=4341");\r
-       //      $db->PConnect('host1','user1','secret');\r
-       function _pconnect($str,$user='',$pwd='',$db='')\r
-       {\r
-               return $this->_connect($str,$user,$pwd,$db,1);\r
-       }\r
-\r
-       // returns queryID or false\r
-       function _query($sql,$inputarr)\r
-       {\r
-               /*\r
-               if (is_array($sql)) {\r
-                       if (!$sql[1]) {\r
-                       \r
-                               $sqltxt = $sql[0];\r
-                               $plan = $sql[1] = 'P'.md5($sqltxt);\r
-                               $params = '';\r
-                               foreach($inputarr as $v) {\r
-                                       if ($params) $params .= ',';\r
-                                       if (is_string($v)) {\r
-                                               $params .= 'VARCHAR';\r
-                                       } else if (is_integer($v)) {\r
-                                               $params .= 'INTEGER';\r
-                                       } else {\r
-                                               $params .= "REAL";\r
-                                       }\r
-                               }\r
-                               $sqlarr = explode('?',$sqltxt);\r
-                               $sqltxt = '';\r
-                               $i = 1;\r
-                               foreach($sqlarr as $v) {\r
-                                       $sqltxt .= $v.'$'.$i;\r
-                                       $i++;\r
-                               }\r
-                               $s = "PREPARE $plan ($params) AS ".substr($sqltxt,0,strlen($sqltxt)-2);         \r
-                               adodb_pr($s);\r
-                               pg_exec($this->_connectionID,$s);\r
-                               echo $this->ErrorMsg();\r
-                       } else {\r
-                               $plan = $sql[1];\r
-                       }\r
-                       $params = '';\r
-                       foreach($inputarr as $v) {\r
-                               if ($params) $params .= ',';\r
-                               if (is_string($v)) {\r
-                                       if (strncmp($v,"'",1) !== 0) $params .= $this->qstr($v.'TEST');\r
-                               } else {\r
-                                       $params .= $v;\r
-                               }\r
-                       }\r
-                       \r
-                       if ($params) $sql = "EXECUTE $plan ($params)";\r
-                       else $sql = "EXECUTE $plan";\r
-                       \r
-                       adodb_pr(">>>>>".$sql);\r
-                       pg_exec($this->_connectionID,$s);\r
-               }*/\r
-               \r
-               $this->_errorMsg = false;\r
-               \r
-               $rez = pg_exec($this->_connectionID,$sql);\r
-               // check if no data returned, then no need to create real recordset\r
-               if ($rez && pg_numfields($rez) <= 0) {\r
-                       if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {\r
-                               pg_freeresult($this->_resultid);\r
-                       }\r
-                       $this->_resultid = $rez;\r
-                       return true;\r
-               }\r
-               \r
-               return $rez;\r
-       }\r
-       \r
-\r
-       /*      Returns: the last error message from previous database operation        */      \r
-       function ErrorMsg() \r
-       {\r
-               if ($this->_errorMsg !== false) return $this->_errorMsg;\r
-               if (ADODB_PHPVER >= 0x4300) {\r
-                       if (!empty($this->_resultid)) {\r
-                               $this->_errorMsg = @pg_result_error($this->_resultid);\r
-                               if ($this->_errorMsg) return $this->_errorMsg;\r
-                       }\r
-                       \r
-                       if (!empty($this->_connectionID)) {\r
-                               $this->_errorMsg = @pg_last_error($this->_connectionID);\r
-                       } else $this->_errorMsg = @pg_last_error();\r
-               } else {\r
-                       if (empty($this->_connectionID)) $this->_errorMsg = @pg_errormessage();\r
-                       else $this->_errorMsg = @pg_errormessage($this->_connectionID);\r
-               }\r
-               return $this->_errorMsg;\r
-       }\r
-       \r
-       function ErrorNo()\r
-       {\r
-               $e = $this->ErrorMsg();\r
-               return strlen($e) ? $e : 0;\r
-       }\r
-\r
-       // returns true or false\r
-       function _close()\r
-       {\r
-               if ($this->transCnt) $this->RollbackTrans();\r
-               if ($this->_resultid) {\r
-                       @pg_freeresult($this->_resultid);\r
-                       $this->_resultid = false;\r
-               }\r
-               @pg_close($this->_connectionID);\r
-               $this->_connectionID = false;\r
-               return true;\r
-       }\r
-       \r
-       \r
-       /*\r
-       * Maximum size of C field\r
-       */\r
-       function CharMax()\r
-       {\r
-               return 1000000000;  // should be 1 Gb?\r
-       }\r
-       \r
-       /*\r
-       * Maximum size of X field\r
-       */\r
-       function TextMax()\r
-       {\r
-               return 1000000000; // should be 1 Gb?\r
-       }\r
-       \r
-               \r
-}\r
-       \r
-/*--------------------------------------------------------------------------------------\r
-        Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordSet_postgres64 extends ADORecordSet{\r
-       var $_blobArr;\r
-       var $databaseType = "postgres64";\r
-       var $canSeek = true;\r
-       function ADORecordSet_postgres64($queryID,$mode=false) \r
-       {\r
-               if ($mode === false) { \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               switch ($mode)\r
-               {\r
-               case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;\r
-               case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;\r
-               default:\r
-               case ADODB_FETCH_DEFAULT:\r
-               case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break;\r
-               }\r
-               $this->ADORecordSet($queryID);\r
-       }\r
-       \r
-       function &GetRowAssoc($upper=true)\r
-       {\r
-               if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields;\r
-               $row =& ADORecordSet::GetRowAssoc($upper);\r
-               return $row;\r
-       }\r
-\r
-       function _initrs()\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-               $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($this->_queryID):-1;\r
-               $this->_numOfFields = @pg_numfields($this->_queryID);\r
-               \r
-               // cache types for blob decode check\r
-               for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { \r
-                       $f1 = $this->FetchField($i);\r
-                       //print_r($f1);\r
-                       if ($f1->type == 'bytea') $this->_blobArr[$i] = $f1->name;\r
-               }               \r
-       }\r
-\r
-               /* Use associative array to get fields array */\r
-       function Fields($colname)\r
-       {\r
-               if ($this->fetchMode != PGSQL_NUM) return @$this->fields[$colname];\r
-               \r
-               if (!$this->bind) {\r
-                       $this->bind = array();\r
-                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                               $o = $this->FetchField($i);\r
-                               $this->bind[strtoupper($o->name)] = $i;\r
-                       }\r
-               }\r
-                return $this->fields[$this->bind[strtoupper($colname)]];\r
-       }\r
-\r
-       function &FetchField($fieldOffset = 0) \r
-       {\r
-               $off=$fieldOffset; // offsets begin at 0\r
-               \r
-               $o= new ADOFieldObject();\r
-               $o->name = @pg_fieldname($this->_queryID,$off);\r
-               $o->type = @pg_fieldtype($this->_queryID,$off);\r
-               $o->max_length = @pg_fieldsize($this->_queryID,$off);\r
-               //print_r($o);          \r
-               //print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";\r
-               return $o;      \r
-       }\r
-\r
-       function _seek($row)\r
-       {\r
-               return @pg_fetch_row($this->_queryID,$row);\r
-       }\r
-       \r
-       function _decode($blob)\r
-       {\r
-               eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');\r
-               return $realblob;       \r
-       }\r
-       \r
-       function _fixblobs()\r
-       {\r
-               if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) {\r
-                       foreach($this->_blobArr as $k => $v) {\r
-                               $this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]);\r
-                       }\r
-               }\r
-               if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) {\r
-                       foreach($this->_blobArr as $k => $v) {\r
-                               $this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]);\r
-                       }\r
-               }\r
-       }\r
-       \r
-       // 10% speedup to move MoveNext to child class\r
-       function MoveNext() \r
-       {\r
-               if (!$this->EOF) {\r
-                       $this->_currentRow++;\r
-                       if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {\r
-                               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);\r
-                               if (is_array($this->fields) && $this->fields) {\r
-                                       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();\r
-                                       return true;\r
-                               }\r
-                       }\r
-                       $this->fields = false;\r
-                       $this->EOF = true;\r
-               }\r
-               return false;\r
-       }               \r
-       \r
-       function _fetch()\r
-       {\r
-                               \r
-               if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)\r
-               return false;\r
-\r
-               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);\r
-               \r
-       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();\r
-                       \r
-               return (is_array($this->fields));\r
-       }\r
-\r
-       function _close() \r
-       { \r
-               return @pg_freeresult($this->_queryID);\r
-       }\r
-\r
-       function MetaType($t,$len=-1,$fieldobj=false)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               switch (strtoupper($t)) {\r
-                               case 'MONEY': // stupid, postgres expects money to be a string\r
-                               case 'INTERVAL':\r
-                               case 'CHAR':\r
-                               case 'CHARACTER':\r
-                               case 'VARCHAR':\r
-                               case 'NAME':\r
-                               case 'BPCHAR':\r
-                               case '_VARCHAR':\r
-                                       if ($len <= $this->blobSize) return 'C';\r
-                               \r
-                               case 'TEXT':\r
-                                       return 'X';\r
-               \r
-                               case 'IMAGE': // user defined type\r
-                               case 'BLOB': // user defined type\r
-                               case 'BIT':     // This is a bit string, not a single bit, so don't return 'L'\r
-                               case 'VARBIT':\r
-                               case 'BYTEA':\r
-                                       return 'B';\r
-                               \r
-                               case 'BOOL':\r
-                               case 'BOOLEAN':\r
-                                       return 'L';\r
-                               \r
-                               case 'DATE':\r
-                                       return 'D';\r
-                               \r
-                               case 'TIME':\r
-                               case 'DATETIME':\r
-                               case 'TIMESTAMP':\r
-                               case 'TIMESTAMPTZ':\r
-                                       return 'T';\r
-                               \r
-                               case 'SMALLINT': \r
-                               case 'BIGINT': \r
-                               case 'INTEGER': \r
-                               case 'INT8': \r
-                               case 'INT4':\r
-                               case 'INT2':\r
-                                       if (isset($fieldobj) &&\r
-                               empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';\r
-                               \r
-                               case 'OID':\r
-                               case 'SERIAL':\r
-                                       return 'R';\r
-                               \r
-                                default:\r
-                                       return 'N';\r
-                       }\r
-       }\r
-\r
-}\r
-?>\r
+<?php
+/*
+ V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+  
+  Original version derived from Alberto Cerezal (acerezalp@dbnet.es) - DBNet Informatica & Comunicaciones. 
+  08 Nov 2000 jlim - Minor corrections, removing mysql stuff
+  09 Nov 2000 jlim - added insertid support suggested by "Christopher Kings-Lynne" <chriskl@familyhealth.com.au>
+                                       jlim - changed concat operator to || and data types to MetaType to match documented pgsql types 
+                       see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm  
+  22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <raser@mail.zen.com.tw>
+  27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <leen@wirehub.nl>
+  15 Dec 2000 jlim - added changes suggested by Additional code changes by "Eric G. Werk" egw@netguide.dk. 
+  31 Jan 2002 jlim - finally installed postgresql. testing
+  01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type
+  
+  See http://www.varlena.com/varlena/GeneralBits/47.php
+  
+       -- What indexes are on my table?
+       select * from pg_indexes where tablename = 'tablename';
+       
+       -- What triggers are on my table?
+       select c.relname as "Table", t.tgname as "Trigger Name", 
+          t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled",
+          t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table",
+          p.proname as "Function Name"
+       from pg_trigger t, pg_class c, pg_class cc, pg_proc p
+       where t.tgfoid = p.oid and t.tgrelid = c.oid
+          and t.tgconstrrelid = cc.oid
+          and c.relname = 'tablename';
+       
+       -- What constraints are on my table?
+       select r.relname as "Table", c.conname as "Constraint Name",
+          contype as "Constraint Type", conkey as "Key Columns",
+          confkey as "Foreign Columns", consrc as "Source"
+       from pg_class r, pg_constraint c
+       where r.oid = c.conrelid
+          and relname = 'tablename';
+
+*/
+
+function adodb_addslashes($s)
+{
+       $len = strlen($s);
+       if ($len == 0) return "''";
+       if (strncmp($s,"'",1) === 0 && substr(s,$len-1) == "'") return $s; // already quoted
+       
+       return "'".addslashes($s)."'";
+}
+
+class ADODB_postgres64 extends ADOConnection{
+       var $databaseType = 'postgres64';
+       var $dataProvider = 'postgres';
+       var $hasInsertID = true;
+       var $_resultid = false;
+       var $concat_operator='||';
+       var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
+    var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' union 
+        select viewname,'V' from pg_views where viewname not like 'pg\_%'";
+       //"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
+       var $isoDates = true; // accepts dates in ISO format
+       var $sysDate = "CURRENT_DATE";
+       var $sysTimeStamp = "CURRENT_TIMESTAMP";
+       var $blobEncodeType = 'C';
+       var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum 
+               FROM pg_class c, pg_attribute a,pg_type t 
+               WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
+AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
+
+       var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum 
+FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n 
+WHERE relkind = 'r' AND (c.relname='%s' or c.relname = lower('%s'))
+ and c.relnamespace=n.oid and n.nspname='%s' 
+       and a.attname not like '....%%' AND a.attnum > 0 
+       AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";
+       
+       // get primary key etc -- from Freek Dijkstra
+       var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key 
+       FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'";
+       
+       var $hasAffectedRows = true;
+       var $hasLimit = false;  // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
+       // below suggested by Freek Dijkstra 
+       var $true = 't';                // string that represents TRUE for a database
+       var $false = 'f';               // string that represents FALSE for a database
+       var $fmtDate = "'Y-m-d'";       // used by DBDate() as the default date format used by the database
+       var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
+       var $hasMoveFirst = true;
+       var $hasGenID = true;
+       var $_genIDSQL = "SELECT NEXTVAL('%s')";
+       var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
+       var $_dropSeqSQL = "DROP SEQUENCE %s";
+       var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
+       var $random = 'random()';               /// random function
+       var $autoRollback = true; // apparently pgsql does not autorollback properly before 4.3.4
+                                                       // http://bugs.php.net/bug.php?id=25404
+                                                       
+       var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
+       
+       // The last (fmtTimeStamp is not entirely correct: 
+       // PostgreSQL also has support for time zones, 
+       // and writes these time in this format: "2001-03-01 18:59:26+02". 
+       // There is no code for the "+02" time zone information, so I just left that out. 
+       // I'm not familiar enough with both ADODB as well as Postgres 
+       // to know what the concequences are. The other values are correct (wheren't in 0.94)
+       // -- Freek Dijkstra 
+
+       function ADODB_postgres64() 
+       {
+       // changes the metaColumnsSQL, adds columns: attnum[6]
+       }
+       
+       function ServerInfo()
+       {
+               if (isset($this->version)) return $this->version;
+               
+               $arr['description'] = $this->GetOne("select version()");
+               $arr['version'] = ADOConnection::_findvers($arr['description']);
+               $this->version = $arr;
+               return $arr;
+       }
+/*
+       function IfNull( $field, $ifNull ) 
+       {
+               return " NULLIF($field, $ifNull) "; // if PGSQL
+       }
+*/
+       // get the last id - never tested
+       function pg_insert_id($tablename,$fieldname)
+       {
+               $result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq");
+               if ($result) {
+                       $arr = @pg_fetch_row($result,0);
+                       pg_freeresult($result);
+                       if (isset($arr[0])) return $arr[0];
+               }
+               return false;
+       }
+       
+/* Warning from http://www.php.net/manual/function.pg-getlastoid.php:
+Using a OID as a unique identifier is not generally wise. 
+Unless you are very careful, you might end up with a tuple having 
+a different OID if a database must be reloaded. */
+       function _insertid()
+       {
+               if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
+               return pg_getlastoid($this->_resultid);
+       }
+
+// I get this error with PHP before 4.0.6 - jlim
+// Warning: This compilation does not support pg_cmdtuples() in d:/inetpub/wwwroot/php/adodb/adodb-postgres.inc.php on line 44
+   function _affectedrows()
+   {
+               if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false;
+               return pg_cmdtuples($this->_resultid);
+   }
+   
+       
+               // returns true/false
+       function BeginTrans()
+       {
+               if ($this->transOff) return true;
+               $this->transCnt += 1;
+               return @pg_Exec($this->_connectionID, "begin");
+       }
+       
+       function RowLock($tables,$where) 
+       {
+               if (!$this->transCnt) $this->BeginTrans();
+               return $this->GetOne("select 1 as ignore from $tables where $where for update");
+       }
+
+       // returns true/false. 
+       function CommitTrans($ok=true) 
+       { 
+               if ($this->transOff) return true;
+               if (!$ok) return $this->RollbackTrans();
+               
+               $this->transCnt -= 1;
+               return @pg_Exec($this->_connectionID, "commit");
+       }
+       
+       // returns true/false
+       function RollbackTrans()
+       {
+               if ($this->transOff) return true;
+               $this->transCnt -= 1;
+               return @pg_Exec($this->_connectionID, "rollback");
+       }
+       
+       function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
+       {       
+               if ($mask) {
+                       $save = $this->metaTablesSQL;
+                       $mask = $this->qstr(strtolower($mask));
+                       $this->metaTablesSQL = "
+select tablename,'T' from pg_tables where tablename like $mask union 
+select viewname,'V' from pg_views where viewname like $mask";
+               }
+               $ret =& ADOConnection::MetaTables($ttype,$showSchema);
+               
+               if ($mask) {
+                       $this->metaTablesSQL = $save;
+               }
+               return $ret;
+       }
+       
+       /*
+       // if magic quotes disabled, use pg_escape_string()
+       function qstr($s,$magic_quotes=false)
+       {
+               if (!$magic_quotes) {
+                       if (ADODB_PHPVER >= 0x4200) {
+                               return  "'".pg_escape_string($s)."'";
+                       }
+                       if ($this->replaceQuote[0] == '\\'){
+                               $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
+                       }
+                       return  "'".str_replace("'",$this->replaceQuote,$s)."'"; 
+               }
+               
+               // undo magic quotes for "
+               $s = str_replace('\\"','"',$s);
+               return "'$s'";
+       }
+       */
+       
+       
+       // Format date column in sql string given an input format that understands Y M D
+       function SQLDate($fmt, $col=false)
+       {       
+               if (!$col) $col = $this->sysTimeStamp;
+               $s = 'TO_CHAR('.$col.",'";
+               
+               $len = strlen($fmt);
+               for ($i=0; $i < $len; $i++) {
+                       $ch = $fmt[$i];
+                       switch($ch) {
+                       case 'Y':
+                       case 'y':
+                               $s .= 'YYYY';
+                               break;
+                       case 'Q':
+                       case 'q':
+                               $s .= 'Q';
+                               break;
+                               
+                       case 'M':
+                               $s .= 'Mon';
+                               break;
+                               
+                       case 'm':
+                               $s .= 'MM';
+                               break;
+                       case 'D':
+                       case 'd':
+                               $s .= 'DD';
+                               break;
+                       
+                       case 'H':
+                               $s.= 'HH24';
+                               break;
+                               
+                       case 'h':
+                               $s .= 'HH';
+                               break;
+                               
+                       case 'i':
+                               $s .= 'MI';
+                               break;
+                       
+                       case 's':
+                               $s .= 'SS';
+                               break;
+                       
+                       case 'a':
+                       case 'A':
+                               $s .= 'AM';
+                               break;
+                               
+                       default:
+                       // handle escape characters...
+                               if ($ch == '\\') {
+                                       $i++;
+                                       $ch = substr($fmt,$i,1);
+                               }
+                               if (strpos('-/.:;, ',$ch) !== false) $s .= $ch;
+                               else $s .= '"'.$ch.'"';
+                               
+                       }
+               }
+               return $s. "')";
+       }
+       
+       
+       
+       /* 
+       * Load a Large Object from a file 
+       * - the procedure stores the object id in the table and imports the object using 
+       * postgres proprietary blob handling routines 
+       *
+       * contributed by Mattia Rossi mattia@technologist.com
+       * modified for safe mode by juraj chlebec
+       */ 
+       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') 
+       { 
+               pg_exec ($this->_connectionID, "begin"); 
+               
+               $fd = fopen($path,'r');
+               $contents = fread($fd,filesize($path));
+               fclose($fd);
+               
+               $oid = pg_lo_create($this->_connectionID);
+               $handle = pg_lo_open($this->_connectionID, $oid, 'w');
+               pg_lo_write($handle, $contents);
+               pg_lo_close($handle);
+               
+               // $oid = pg_lo_import ($path); 
+               pg_exec($this->_connectionID, "commit"); 
+               $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype); 
+               $rez = !empty($rs); 
+               return $rez; 
+       } 
+       
+       /* 
+       * If an OID is detected, then we use pg_lo_* to open the oid file and read the
+       * real blob from the db using the oid supplied as a parameter. If you are storing
+       * blobs using bytea, we autodetect and process it so this function is not needed.
+       *
+       * contributed by Mattia Rossi mattia@technologist.com
+       *
+       * see http://www.postgresql.org/idocs/index.php?largeobjects.html
+       */ 
+       function BlobDecode( $blob) 
+       { 
+               if (strlen($blob) > 24) return $blob;
+               
+               @pg_exec($this->_connectionID,"begin"); 
+               $fd = @pg_lo_open($this->_connectionID,$blob,"r");
+               if ($fd === false) {
+                       @pg_exec($this->_connectionID,"commit");
+                       return $blob;
+               }
+               $realblob = @pg_loreadall($fd); 
+               @pg_loclose($fd); 
+               @pg_exec($this->_connectionID,"commit"); 
+               return $realblob;
+       } 
+       
+       /* 
+               See http://www.postgresql.org/idocs/index.php?datatype-binary.html
+               
+               NOTE: SQL string literals (input strings) must be preceded with two backslashes 
+               due to the fact that they must pass through two parsers in the PostgreSQL 
+               backend.
+       */
+       function BlobEncode($blob)
+       {
+               if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob);
+               
+               /*92=backslash, 0=null, 39=single-quote*/
+               $badch = array(chr(92),chr(0),chr(39)); # \  null  '
+               $fixch = array('\\\\134','\\\\000','\\\\047');
+               return adodb_str_replace($badch,$fixch,$blob);
+               
+               // note that there is a pg_escape_bytea function only for php 4.2.0 or later
+       }
+       
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
+       {
+               // do not use bind params which uses qstr(), as blobencode() already quotes data
+               return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where");
+       }
+       
+       function OffsetDate($dayFraction,$date=false)
+       {               
+               if (!$date) $date = $this->sysDate;
+               return "($date+interval'$dayFraction days')";
+       }
+       
+
+       // for schema support, pass in the $table param "$schema.$tabname".
+       // converts field names to lowercase, $upper is ignored
+       function &MetaColumns($table,$upper=true) 
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $schema = false;
+               $this->_findschema($table,$schema);
+               
+               $table = strtolower($table);
+
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
+               
+               if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema));
+               else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table));
+               if (isset($savem)) $this->SetFetchMode($savem);
+               $ADODB_FETCH_MODE = $save;
+               
+               if ($rs === false) return false;
+               
+               if (!empty($this->metaKeySQL)) {
+                       // If we want the primary keys, we have to issue a separate query
+                       // Of course, a modified version of the metaColumnsSQL query using a 
+                       // LEFT JOIN would have been much more elegant, but postgres does 
+                       // not support OUTER JOINS. So here is the clumsy way.
+                       
+                       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+                       
+                       $rskey = $this->Execute(sprintf($this->metaKeySQL,($table)));
+                       // fetch all result in once for performance.
+                       $keys =& $rskey->GetArray();
+                       if (isset($savem)) $this->SetFetchMode($savem);
+                       $ADODB_FETCH_MODE = $save;
+                       
+                       $rskey->Close();
+                       unset($rskey);
+               }
+
+               $rsdefa = array();
+               if (!empty($this->metaDefaultsSQL)) {
+                       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+                       $sql = sprintf($this->metaDefaultsSQL, ($table));
+                       $rsdef = $this->Execute($sql);
+                       if (isset($savem)) $this->SetFetchMode($savem);
+                       $ADODB_FETCH_MODE = $save;
+                       
+                       if ($rsdef) {
+                               while (!$rsdef->EOF) {
+                                       $num = $rsdef->fields['num'];
+                                       $s = $rsdef->fields['def'];
+                                       if (substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */
+                                               $s = substr($s, 1);
+                                               $s = substr($s, 0, strlen($s) - 1);
+                                       }
+
+                                       $rsdefa[$num] = $s;
+                                       $rsdef->MoveNext();
+                               }
+                       } else {
+                               ADOConnection::outp( "==> SQL => " . $sql);
+                       }
+                       unset($rsdef);
+               }
+       
+               $retarr = array();
+               while (!$rs->EOF) {     
+                       $fld = new ADOFieldObject();
+                       $fld->name = $rs->fields[0];
+                       $fld->type = $rs->fields[1];
+                       $fld->max_length = $rs->fields[2];
+                       if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4;
+                       if ($fld->max_length <= 0) $fld->max_length = -1;
+                       
+                       // dannym
+                       // 5 hasdefault; 6 num-of-column
+                       $fld->has_default = ($rs->fields[5] == 't');
+                       if ($fld->has_default) {
+                               $fld->default_value = $rsdefa[$rs->fields[6]];
+                       }
+
+                       //Freek
+                       if ($rs->fields[4] == $this->true) {
+                               $fld->not_null = true;
+                       }
+                       
+                       // Freek
+                       if (is_array($keys)) {
+                               foreach($keys as $key) {
+                                       if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) 
+                                               $fld->primary_key = true;
+                                       if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) 
+                                               $fld->unique = true; // What name is more compatible?
+                               }
+                       }
+                       
+                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;     
+                       else $retarr[($upper) ? strtoupper($fld->name) : $fld->name] = $fld;
+                       
+                       $rs->MoveNext();
+               }
+               $rs->Close();
+               return $retarr; 
+               
+       }
+
+         function &MetaIndexes ($table, $primary = FALSE)
+      {
+         global $ADODB_FETCH_MODE;
+                
+                               $schema = false;
+                               $this->_findschema($table,$schema);
+                               
+                               if ($schema) { // requires pgsql 7.3+ - pg_namespace used.
+                                       $sql = '
+SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns" 
+FROM pg_catalog.pg_class c 
+JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid 
+JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
+       ,pg_namespace n 
+WHERE c2.relname=\'%s\' and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\' AND i.indisprimary=false';
+                               } else {
+                       $sql = '
+SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns"
+FROM pg_catalog.pg_class c
+JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid
+JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid
+WHERE c2.relname=\'%s\'';
+                       }
+                                           
+                if ($primary == FALSE) {
+                        $sql .= ' AND i.indisprimary=false;';
+                }
+                
+                $save = $ADODB_FETCH_MODE;
+                $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                if ($this->fetchMode !== FALSE) {
+                        $savem = $this->SetFetchMode(FALSE);
+                }
+                
+                $rs = $this->Execute(sprintf($sql,$table,$schema));
+                
+                if (isset($savem)) {
+                        $this->SetFetchMode($savem);
+                }
+                $ADODB_FETCH_MODE = $save;
+                
+                if (!is_object($rs)) {
+                        return FALSE;
+                }
+                
+                $col_names = $this->MetaColumnNames($table);
+                $indexes = array();
+                
+                while ($row = $rs->FetchRow()) {
+                        $columns = array();
+                        
+                        foreach (explode(' ', $row[2]) as $col) {
+                                $columns[] = $col_names[$col - 1];
+                        }
+                        
+                        $indexes[$row[0]] = array(
+                                'unique' => ($row[1] == 't'),
+                                'columns' => $columns
+                        );
+                }
+                
+                return $indexes;
+        }
+
+       // returns true or false
+       //
+       // examples:
+       //      $db->Connect("host=host1 user=user1 password=secret port=4341");
+       //      $db->Connect('host1','user1','secret');
+       function _connect($str,$user='',$pwd='',$db='',$ctype=0)
+       {
+               
+               if (!function_exists('pg_pconnect')) return false;
+               
+               $this->_errorMsg = false;
+               
+               if ($user || $pwd || $db) {
+                       $user = adodb_addslashes($user);
+                       $pwd = adodb_addslashes($pwd);
+                       if (strlen($db) == 0) $db = 'template1';
+                       $db = adodb_addslashes($db);
+                       if ($str)  {
+                               $host = split(":", $str);
+                               if ($host[0]) $str = "host=".adodb_addslashes($host[0]);
+                               else $str = 'host=localhost';
+                               if (isset($host[1])) $str .= " port=$host[1]";
+                       }
+                               if ($user) $str .= " user=".$user;
+                               if ($pwd)  $str .= " password=".$pwd;
+                               if ($db)   $str .= " dbname=".$db;
+               }
+
+               //if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432";
+               
+               if ($ctype === 1) { // persistent
+                       $this->_connectionID = pg_pconnect($str);
+               } else {
+                       if ($ctype === -1) { // nconnect, we trick pgsql ext by changing the connection str
+                       static $ncnt;
+                       
+                               if (empty($ncnt)) $ncnt = 1;
+                               else $ncnt += 1;
+                               
+                               $str .= str_repeat(' ',$ncnt);
+                       }
+                       $this->_connectionID = pg_connect($str);
+               }
+               if ($this->_connectionID === false) return false;
+               $this->Execute("set datestyle='ISO'");
+               return true;
+       }
+       
+       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
+       {
+               return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1);
+       }
+        
+       // returns true or false
+       //
+       // examples:
+       //      $db->PConnect("host=host1 user=user1 password=secret port=4341");
+       //      $db->PConnect('host1','user1','secret');
+       function _pconnect($str,$user='',$pwd='',$db='')
+       {
+               return $this->_connect($str,$user,$pwd,$db,1);
+       }
+       
+
+       // returns queryID or false
+       function _query($sql,$inputarr)
+       {
+               
+               if ($inputarr) {
+               /*
+                       It appears that PREPARE/EXECUTE is slower for many queries.
+                       
+                       For query executed 1000 times:
+                       "select id,firstname,lastname from adoxyz 
+                               where firstname not like ? and lastname not like ? and id = ?"
+                               
+                       with plan = 1.51861286163 secs
+                       no plan =   1.26903700829 secs
+
+                       
+
+               */
+                       $plan = 'P'.md5($sql);
+                               
+                       $execp = '';
+                       foreach($inputarr as $v) {
+                               if ($execp) $execp .= ',';
+                               if (is_string($v)) {
+                                       if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v);
+                               } else {
+                                       $execp .= $v;
+                               }
+                       }
+                       
+                       if ($execp) $exsql = "EXECUTE $plan ($execp)";
+                       else $exsql = "EXECUTE $plan";
+                       
+                       $rez = @pg_exec($this->_connectionID,$exsql);
+                       if (!$rez) {
+                       # Perhaps plan does not exist? Prepare/compile plan.
+                               $params = '';
+                               foreach($inputarr as $v) {
+                                       if ($params) $params .= ',';
+                                       if (is_string($v)) {
+                                               $params .= 'VARCHAR';
+                                       } else if (is_integer($v)) {
+                                               $params .= 'INTEGER';
+                                       } else {
+                                               $params .= "REAL";
+                                       }
+                               }
+                               $sqlarr = explode('?',$sql);
+                               //print_r($sqlarr);
+                               $sql = '';
+                               $i = 1;
+                               foreach($sqlarr as $v) {
+                                       $sql .= $v.' $'.$i;
+                                       $i++;
+                               }
+                               $s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2);               
+                               //adodb_pr($s);
+                               pg_exec($this->_connectionID,$s);
+                               echo $this->ErrorMsg();
+                       }
+                       
+                       $rez = pg_exec($this->_connectionID,$exsql);
+               } else {
+                       $this->_errorMsg = false;
+                       //adodb_backtrace();
+                       $rez = pg_exec($this->_connectionID,$sql);
+               }
+               // check if no data returned, then no need to create real recordset
+               if ($rez && pg_numfields($rez) <= 0) {
+                       if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') {
+                               pg_freeresult($this->_resultid);
+                       }
+                       $this->_resultid = $rez;
+                       return true;
+               }
+               
+               return $rez;
+       }
+       
+
+       /*      Returns: the last error message from previous database operation        */      
+       function ErrorMsg() 
+       {
+               if ($this->_errorMsg !== false) return $this->_errorMsg;
+               if (ADODB_PHPVER >= 0x4300) {
+                       if (!empty($this->_resultid)) {
+                               $this->_errorMsg = @pg_result_error($this->_resultid);
+                               if ($this->_errorMsg) return $this->_errorMsg;
+                       }
+                       
+                       if (!empty($this->_connectionID)) {
+                               $this->_errorMsg = @pg_last_error($this->_connectionID);
+                       } else $this->_errorMsg = @pg_last_error();
+               } else {
+                       if (empty($this->_connectionID)) $this->_errorMsg = @pg_errormessage();
+                       else $this->_errorMsg = @pg_errormessage($this->_connectionID);
+               }
+               return $this->_errorMsg;
+       }
+       
+       function ErrorNo()
+       {
+               $e = $this->ErrorMsg();
+               return strlen($e) ? $e : 0;
+       }
+
+       // returns true or false
+       function _close()
+       {
+               if ($this->transCnt) $this->RollbackTrans();
+               if ($this->_resultid) {
+                       @pg_freeresult($this->_resultid);
+                       $this->_resultid = false;
+               }
+               @pg_close($this->_connectionID);
+               $this->_connectionID = false;
+               return true;
+       }
+       
+       
+       /*
+       * Maximum size of C field
+       */
+       function CharMax()
+       {
+               return 1000000000;  // should be 1 Gb?
+       }
+       
+       /*
+       * Maximum size of X field
+       */
+       function TextMax()
+       {
+               return 1000000000; // should be 1 Gb?
+       }
+       
+               
+}
+       
+/*--------------------------------------------------------------------------------------
+        Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_postgres64 extends ADORecordSet{
+       var $_blobArr;
+       var $databaseType = "postgres64";
+       var $canSeek = true;
+       function ADORecordSet_postgres64($queryID,$mode=false) 
+       {
+               if ($mode === false) { 
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               switch ($mode)
+               {
+               case ADODB_FETCH_NUM: $this->fetchMode = PGSQL_NUM; break;
+               case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break;
+               default:
+               case ADODB_FETCH_DEFAULT:
+               case ADODB_FETCH_BOTH:$this->fetchMode = PGSQL_BOTH; break;
+               }
+               $this->ADORecordSet($queryID);
+       }
+       
+       function &GetRowAssoc($upper=true)
+       {
+               if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields;
+               $row =& ADORecordSet::GetRowAssoc($upper);
+               return $row;
+       }
+
+       function _initrs()
+       {
+       global $ADODB_COUNTRECS;
+               $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($this->_queryID):-1;
+               $this->_numOfFields = @pg_numfields($this->_queryID);
+               
+               // cache types for blob decode check
+               for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { 
+                       $f1 = $this->FetchField($i);
+                       //print_r($f1);
+                       if ($f1->type == 'bytea') $this->_blobArr[$i] = $f1->name;
+               }               
+       }
+
+               /* Use associative array to get fields array */
+       function Fields($colname)
+       {
+               if ($this->fetchMode != PGSQL_NUM) return @$this->fields[$colname];
+               
+               if (!$this->bind) {
+                       $this->bind = array();
+                       for ($i=0; $i < $this->_numOfFields; $i++) {
+                               $o = $this->FetchField($i);
+                               $this->bind[strtoupper($o->name)] = $i;
+                       }
+               }
+                return $this->fields[$this->bind[strtoupper($colname)]];
+       }
+
+       function &FetchField($fieldOffset = 0) 
+       {
+               $off=$fieldOffset; // offsets begin at 0
+               
+               $o= new ADOFieldObject();
+               $o->name = @pg_fieldname($this->_queryID,$off);
+               $o->type = @pg_fieldtype($this->_queryID,$off);
+               $o->max_length = @pg_fieldsize($this->_queryID,$off);
+               //print_r($o);          
+               //print "off=$off name=$o->name type=$o->type len=$o->max_length<br>";
+               return $o;      
+       }
+
+       function _seek($row)
+       {
+               return @pg_fetch_row($this->_queryID,$row);
+       }
+       
+       function _decode($blob)
+       {
+               eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";');
+               return $realblob;       
+       }
+       
+       function _fixblobs()
+       {
+               if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) {
+                       foreach($this->_blobArr as $k => $v) {
+                               $this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]);
+                       }
+               }
+               if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) {
+                       foreach($this->_blobArr as $k => $v) {
+                               $this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]);
+                       }
+               }
+       }
+       
+       // 10% speedup to move MoveNext to child class
+       function MoveNext() 
+       {
+               if (!$this->EOF) {
+                       $this->_currentRow++;
+                       if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
+                               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
+                               if (is_array($this->fields) && $this->fields) {
+                                       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
+                                       return true;
+                               }
+                       }
+                       $this->fields = false;
+                       $this->EOF = true;
+               }
+               return false;
+       }               
+       
+       function _fetch()
+       {
+                               
+               if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0)
+               return false;
+
+               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
+               
+       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
+                       
+               return (is_array($this->fields));
+       }
+
+       function _close() 
+       { 
+               return @pg_freeresult($this->_queryID);
+       }
+
+       function MetaType($t,$len=-1,$fieldobj=false)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               switch (strtoupper($t)) {
+                               case 'MONEY': // stupid, postgres expects money to be a string
+                               case 'INTERVAL':
+                               case 'CHAR':
+                               case 'CHARACTER':
+                               case 'VARCHAR':
+                               case 'NAME':
+                               case 'BPCHAR':
+                               case '_VARCHAR':
+                                       if ($len <= $this->blobSize) return 'C';
+                               
+                               case 'TEXT':
+                                       return 'X';
+               
+                               case 'IMAGE': // user defined type
+                               case 'BLOB': // user defined type
+                               case 'BIT':     // This is a bit string, not a single bit, so don't return 'L'
+                               case 'VARBIT':
+                               case 'BYTEA':
+                                       return 'B';
+                               
+                               case 'BOOL':
+                               case 'BOOLEAN':
+                                       return 'L';
+                               
+                               case 'DATE':
+                                       return 'D';
+                               
+                               case 'TIME':
+                               case 'DATETIME':
+                               case 'TIMESTAMP':
+                               case 'TIMESTAMPTZ':
+                                       return 'T';
+                               
+                               case 'SMALLINT': 
+                               case 'BIGINT': 
+                               case 'INTEGER': 
+                               case 'INT8': 
+                               case 'INT4':
+                               case 'INT2':
+                                       if (isset($fieldobj) &&
+                               empty($fieldobj->primary_key) && empty($fieldobj->unique)) return 'I';
+                               
+                               case 'OID':
+                               case 'SERIAL':
+                                       return 'R';
+                               
+                                default:
+                                       return 'N';
+                       }
+       }
+
+}
+?>
index 2b9eb235f030ae6e40aaf87838fd52723b1df18b..82ea97acf621a1ffbd1efa2d894aeccace921e3b 100644 (file)
-<?php\r
-/*\r
- V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 4.\r
-  \r
-  Postgres7 support.\r
-  28 Feb 2001: Currently indicate that we support LIMIT\r
-  01 Dec 2001: dannym added support for default values\r
-*/\r
-\r
-include_once(ADODB_DIR."/drivers/adodb-postgres64.inc.php");\r
-\r
-class ADODB_postgres7 extends ADODB_postgres64 {\r
-       var $databaseType = 'postgres7';        \r
-       var $hasLimit = true;   // set to true for pgsql 6.5+ only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10\r
-       var $ansiOuter = true;\r
-       var $charSet = true; //set to true for Postgres 7 and above - PG client supports encodings\r
-       \r
-       function ADODB_postgres7() \r
-       {\r
-               $this->ADODB_postgres64();\r
-       }\r
-\r
-       // the following should be compat with postgresql 7.2, \r
-       // which makes obsolete the LIMIT limit,offset syntax\r
-        function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) \r
-        {\r
-                $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';\r
-                $limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : '';\r
-                if ($secs2cache)\r
-                       $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);\r
-                else\r
-                       $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);\r
-               \r
-               return $rs;\r
-        }\r
-       /*\r
-       function Prepare($sql)\r
-       {\r
-               $info = $this->ServerInfo();\r
-               if ($info['version']>=7.3) {\r
-                       return array($sql,false);\r
-               }\r
-               return $sql;\r
-       }\r
-       */\r
-    function MetaForeignKeys($table, $owner=false, $upper=false)\r
-       {\r
-\r
-        $sql = '\r
-SELECT t.tgargs as args\r
-   FROM pg_trigger t,\r
-        pg_class c,\r
-        pg_class c2,\r
-        pg_proc f\r
-   WHERE t.tgenabled\r
-   AND t.tgrelid=c.oid\r
-   AND t.tgconstrrelid=c2.oid\r
-   AND t.tgfoid=f.oid\r
-   AND f.proname ~ \'^RI_FKey_check_ins\'\r
-   AND t.tgargs like \'$1\\\000'.strtolower($table).'%\'\r
-   ORDER BY t.tgrelid';\r
-\r
-        $rs = $this->Execute($sql);\r
-               if ($rs && !$rs->EOF) {\r
-                       $arr =& $rs->GetArray();\r
-                       $a = array();\r
-                       foreach($arr as $v) {\r
-                $data = explode(chr(0), $v['args']);\r
-                if ($upper) {\r
-                    $a[] = array(strtoupper($data[2]) => strtoupper($data[4].'='.$data[5]));\r
-                } else {\r
-                    $a[] = array($data[2] => $data[4].'='.$data[5]);\r
-                }\r
-                \r
-                       }\r
-                       return $a;\r
-               }\r
-               else return false;\r
-    }\r
-       \r
-        // this is a set of functions for managing client encoding - very important if the encodings\r
-       // of your database and your output target (i.e. HTML) don't match\r
-       //for instance, you may have UNICODE database and server it on-site as WIN1251 etc.\r
-       // GetCharSet - get the name of the character set the client is using now\r
-       // the functions should work with Postgres 7.0 and above, the set of charsets supported\r
-       // depends on compile flags of postgres distribution - if no charsets were compiled into the server\r
-       // it will return 'SQL_ANSI' always\r
-       function GetCharSet()\r
-       {\r
-               //we will use ADO's builtin property charSet\r
-               $this->charSet = @pg_client_encoding($this->_connectionID);\r
-               if (!$this->charSet) {\r
-                       return false;\r
-               } else {\r
-                       return $this->charSet;\r
-               }\r
-       }\r
-       \r
-       // SetCharSet - switch the client encoding\r
-       function SetCharSet($charset_name)\r
-       {\r
-               $this->GetCharSet();\r
-               if ($this->charSet !== $charset_name) {\r
-                       $if = pg_set_client_encoding($this->_connectionID, $charset_name);\r
-                       if ($if == "0" & $this->GetCharSet() == $charset_name) {\r
-                               return true;\r
-                       } else return false;\r
-               } else return true;\r
-       }\r
-\r
-}\r
-       \r
-/*--------------------------------------------------------------------------------------\r
-        Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordSet_postgres7 extends ADORecordSet_postgres64{\r
-\r
-       var $databaseType = "postgres7";\r
-       \r
-       \r
-       function ADORecordSet_postgres7($queryID,$mode=false) \r
-       {\r
-               $this->ADORecordSet_postgres64($queryID,$mode);\r
-       }\r
-       \r
-               // 10% speedup to move MoveNext to child class\r
-       function MoveNext() \r
-       {\r
-               if (!$this->EOF) {\r
-                       $this->_currentRow++;\r
-                       if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {\r
-                               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);\r
-                       \r
-                               if (is_array($this->fields)) {\r
-                                       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();\r
-                                       return true;\r
-                               }\r
-                       }\r
-                       $this->fields = false;\r
-                       $this->EOF = true;\r
-               }\r
-               return false;\r
-       }               \r
-\r
-}\r
+<?php
+/*
+ V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 4.
+  
+  Postgres7 support.
+  28 Feb 2001: Currently indicate that we support LIMIT
+  01 Dec 2001: dannym added support for default values
+*/
+
+include_once(ADODB_DIR."/drivers/adodb-postgres64.inc.php");
+
+class ADODB_postgres7 extends ADODB_postgres64 {
+       var $databaseType = 'postgres7';        
+       var $hasLimit = true;   // set to true for pgsql 6.5+ only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
+       var $ansiOuter = true;
+       var $charSet = true; //set to true for Postgres 7 and above - PG client supports encodings
+       
+       function ADODB_postgres7() 
+       {
+               $this->ADODB_postgres64();
+       }
+
+       
+       // the following should be compat with postgresql 7.2, 
+       // which makes obsolete the LIMIT limit,offset syntax
+        function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) 
+        {
+                $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
+                $limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : '';
+                if ($secs2cache)
+                       $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
+                else
+                       $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
+               
+               return $rs;
+        }
+       /*
+       function Prepare($sql)
+       {
+               $info = $this->ServerInfo();
+               if ($info['version']>=7.3) {
+                       return array($sql,false);
+               }
+               return $sql;
+       }
+       */
+
+       // from  Edward Jaramilla, improved version - works on pg 7.4
+function MetaForeignKeys($table, $owner=false, $upper=false)
+{
+       $sql = 'SELECT t.tgargs as args
+       FROM
+       pg_trigger t,pg_class c,pg_proc p
+       WHERE
+       t.tgenabled AND
+       t.tgrelid = c.oid AND
+       t.tgfoid = p.oid AND
+       p.proname = \'RI_FKey_check_ins\' AND
+       c.relname = \''.strtolower($table).'\'
+       ORDER BY
+               t.tgrelid';
+       
+       $rs = $this->Execute($sql);
+       
+       if ($rs && !$rs->EOF) {
+               $arr =& $rs->GetArray();
+               $a = array();
+               foreach($arr as $v)
+               {
+                       $data = explode(chr(0), $v['args']);
+                       if ($upper) {
+                               $a[strtoupper($data[2])][] = strtoupper($data[4].'='.$data[5]);
+                       } else {
+                       $a[$data[2]][] = $data[4].'='.$data[5];
+                       }
+               }
+               return $a;
+       }
+       return false;
+}
+
+
+
+    function xMetaForeignKeys($table, $owner=false, $upper=false)
+       {
+
+        $sql = '
+SELECT t.tgargs as args
+   FROM pg_trigger t,
+        pg_class c,
+        pg_class c2,
+        pg_proc f
+   WHERE t.tgenabled
+   AND t.tgrelid=c.oid
+   AND t.tgconstrrelid=c2.oid
+   AND t.tgfoid=f.oid
+   AND f.proname ~ \'^RI_FKey_check_ins\'
+   AND t.tgargs like \'$1\\\000'.strtolower($table).'%\'
+   ORDER BY t.tgrelid';
+
+        $rs = $this->Execute($sql);
+               if ($rs && !$rs->EOF) {
+                       $arr =& $rs->GetArray();
+                       $a = array();
+                       foreach($arr as $v) {
+                $data = explode(chr(0), $v['args']);
+                if ($upper) {
+                    $a[] = array(strtoupper($data[2]) => strtoupper($data[4].'='.$data[5]));
+                } else {
+                    $a[] = array($data[2] => $data[4].'='.$data[5]);
+                }
+                
+                       }
+                       return $a;
+               }
+               else return false;
+    }
+       
+        // this is a set of functions for managing client encoding - very important if the encodings
+       // of your database and your output target (i.e. HTML) don't match
+       //for instance, you may have UNICODE database and server it on-site as WIN1251 etc.
+       // GetCharSet - get the name of the character set the client is using now
+       // the functions should work with Postgres 7.0 and above, the set of charsets supported
+       // depends on compile flags of postgres distribution - if no charsets were compiled into the server
+       // it will return 'SQL_ANSI' always
+       function GetCharSet()
+       {
+               //we will use ADO's builtin property charSet
+               $this->charSet = @pg_client_encoding($this->_connectionID);
+               if (!$this->charSet) {
+                       return false;
+               } else {
+                       return $this->charSet;
+               }
+       }
+       
+       // SetCharSet - switch the client encoding
+       function SetCharSet($charset_name)
+       {
+               $this->GetCharSet();
+               if ($this->charSet !== $charset_name) {
+                       $if = pg_set_client_encoding($this->_connectionID, $charset_name);
+                       if ($if == "0" & $this->GetCharSet() == $charset_name) {
+                               return true;
+                       } else return false;
+               } else return true;
+       }
+
+}
+       
+/*--------------------------------------------------------------------------------------
+        Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordSet_postgres7 extends ADORecordSet_postgres64{
+
+       var $databaseType = "postgres7";
+       
+       
+       function ADORecordSet_postgres7($queryID,$mode=false) 
+       {
+               $this->ADORecordSet_postgres64($queryID,$mode);
+       }
+       
+               // 10% speedup to move MoveNext to child class
+       function MoveNext() 
+       {
+               if (!$this->EOF) {
+                       $this->_currentRow++;
+                       if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
+                               $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
+                       
+                               if (is_array($this->fields)) {
+                                       if ($this->fields && isset($this->_blobArr)) $this->_fixblobs();
+                                       return true;
+                               }
+                       }
+                       $this->fields = false;
+                       $this->EOF = true;
+               }
+               return false;
+       }               
+
+}
 ?>
\ No newline at end of file
index c589ce96ada5e82916bf2e10f8a8f5782bc07684..44f448e8c5ceebc6c51d4236389625ad4f38df82 100644 (file)
@@ -1,30 +1,30 @@
-<?php\r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 4.\r
-  \r
-  Synonym for csv driver.\r
-*/ \r
-\r
-if (! defined("_ADODB_PROXY_LAYER")) {\r
-        define("_ADODB_PROXY_LAYER", 1 );\r
-        include(ADODB_DIR."/drivers/adodb-csv.inc.php");\r
-        \r
-       class ADODB_proxy extends ADODB_csv {\r
-               var $databaseType = 'proxy';\r
-               var $databaseProvider = 'csv';\r
-       }\r
-       class ADORecordset_proxy extends ADORecordset_csv {\r
-       var $databaseType = "proxy";            \r
-       \r
-               function ADORecordset_proxy($id,$mode=false) \r
-               {\r
-                       $this->ADORecordset($id,$mode);\r
-               }\r
-       };\r
-} // define\r
-       \r
+<?php
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 4.
+  
+  Synonym for csv driver.
+*/ 
+
+if (! defined("_ADODB_PROXY_LAYER")) {
+        define("_ADODB_PROXY_LAYER", 1 );
+        include(ADODB_DIR."/drivers/adodb-csv.inc.php");
+        
+       class ADODB_proxy extends ADODB_csv {
+               var $databaseType = 'proxy';
+               var $databaseProvider = 'csv';
+       }
+       class ADORecordset_proxy extends ADORecordset_csv {
+       var $databaseType = "proxy";            
+       
+               function ADORecordset_proxy($id,$mode=false) 
+               {
+                       $this->ADORecordset($id,$mode);
+               }
+       };
+} // define
+       
 ?>
\ No newline at end of file
index c7408968c8cc4a09a40fb5472b1c227f2d0299f0..320671e836e24ea707fa5bf34021b166367fa839 100644 (file)
@@ -1,63 +1,63 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  SAPDB data driver. Requires ODBC.\r
-\r
-*/\r
-\r
-if (!defined('_ADODB_ODBC_LAYER')) {\r
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
-}\r
-if (!defined('ADODB_SAPDB')){\r
-define('ADODB_SAPDB',1);\r
-\r
-class ADODB_SAPDB extends ADODB_odbc {\r
-       var $databaseType = "sapdb";    \r
-       var $concat_operator = '||';\r
-       var $sysDate = 'DATE';\r
-       var $sysTimeStamp = 'TIMESTAMP';\r
-       var $fmtDate = "\\D\\A\\T\\E('Y-m-d')"; /// used by DBDate() as the default date format used by the database\r
-       var $fmtTimeStamp = "\\T\\I\\M\\E\\S\\T\\A\\M\\P('Y-m-d','H:i:s')"; /// used by DBTimeStamp as the default timestamp fmt.\r
-       \r
-       function ADODB_SAPDB()\r
-       {\r
-               //if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;\r
-               $this->ADODB_odbc();\r
-       }\r
-       \r
-       /*\r
-               SelectLimit implementation problems:\r
-       \r
-               The following will return random 10 rows as order by performed after "WHERE rowno<10"\r
-               which is not ideal...\r
-               \r
-                       select * from table where rowno < 10 order by 1\r
-         \r
-               This means that we have to use the adoconnection base class SelectLimit when\r
-               there is an "order by".\r
-               \r
-               See http://listserv.sap.com/pipermail/sapdb.general/2002-January/010405.html\r
-        */\r
-       \r
-};\r
\r
-\r
-class  ADORecordSet_sapdb extends ADORecordSet_odbc {  \r
-       \r
-       var $databaseType = "sapdb";            \r
-       \r
-       function ADORecordSet_sapdb($id,$mode=false)\r
-       {\r
-               $this->ADORecordSet_odbc($id,$mode);\r
-       }\r
-}\r
-\r
-} //define\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  SAPDB data driver. Requires ODBC.
+
+*/
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+if (!defined('ADODB_SAPDB')){
+define('ADODB_SAPDB',1);
+
+class ADODB_SAPDB extends ADODB_odbc {
+       var $databaseType = "sapdb";    
+       var $concat_operator = '||';
+       var $sysDate = 'DATE';
+       var $sysTimeStamp = 'TIMESTAMP';
+       var $fmtDate = "\\D\\A\\T\\E('Y-m-d')"; /// used by DBDate() as the default date format used by the database
+       var $fmtTimeStamp = "\\T\\I\\M\\E\\S\\T\\A\\M\\P('Y-m-d','H:i:s')"; /// used by DBTimeStamp as the default timestamp fmt.
+       
+       function ADODB_SAPDB()
+       {
+               //if (strncmp(PHP_OS,'WIN',3) === 0) $this->curmode = SQL_CUR_USE_ODBC;
+               $this->ADODB_odbc();
+       }
+       
+       /*
+               SelectLimit implementation problems:
+       
+               The following will return random 10 rows as order by performed after "WHERE rowno<10"
+               which is not ideal...
+               
+                       select * from table where rowno < 10 order by 1
+         
+               This means that we have to use the adoconnection base class SelectLimit when
+               there is an "order by".
+               
+               See http://listserv.sap.com/pipermail/sapdb.general/2002-January/010405.html
+        */
+       
+};
+
+class  ADORecordSet_sapdb extends ADORecordSet_odbc {  
+       
+       var $databaseType = "sapdb";            
+       
+       function ADORecordSet_sapdb($id,$mode=false)
+       {
+               $this->ADORecordSet_odbc($id,$mode);
+       }
+}
+
+} //define
 ?>
\ No newline at end of file
index d68de25825a2028c8e2e1bd12768931b8a3f2161..0008f187361b3072d010f52add88f69801d99911 100644 (file)
-<?php\r
-/* \r
-version V4.11 27 Jan 2004 (c) 2000-2004  John Lim (jlim@natsoft.com.my). All rights\r
-reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-\r
-  Latest version is available at http://php.weblogs.com/\r
-\r
-  21.02.2002 - Wade Johnson wade@wadejohnson.de\r
-                          Extended ODBC class for Sybase SQLAnywhere.\r
-   1) Added support to retrieve the last row insert ID on tables with\r
-         primary key column using autoincrement function.\r
-\r
-   2) Added blob support.  Usage:\r
-                a) create blob variable on db server:\r
-\r
-               $dbconn->create_blobvar($blobVarName);\r
-\r
-         b) load blob var from file.  $filename must be complete path\r
-\r
-         $dbcon->load_blobvar_from_file($blobVarName, $filename);\r
-\r
-         c) Use the $blobVarName in SQL insert or update statement in the values\r
-         clause:\r
-\r
-               $recordSet = $dbconn->Execute('INSERT INTO tabname (idcol, blobcol) '\r
-               .\r
-          'VALUES (\'test\', ' . $blobVarName . ')');\r
-\r
-        instead of loading blob from a file, you can also load from \r
-         an unformatted (raw) blob variable:\r
-         $dbcon->load_blobvar_from_var($blobVarName, $varName);\r
-\r
-         d) drop blob variable on db server to free up resources:\r
-         $dbconn->drop_blobvar($blobVarName);\r
-\r
-  Sybase_SQLAnywhere data driver. Requires ODBC.\r
-\r
-*/\r
-\r
-if (!defined('_ADODB_ODBC_LAYER')) {\r
- include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
-}\r
-\r
-if (!defined('ADODB_SYBASE_SQLANYWHERE')){\r
-\r
- define('ADODB_SYBASE_SQLANYWHERE',1);\r
-\r
- class ADODB_sqlanywhere extends ADODB_odbc {\r
-       var $databaseType = "sqlanywhere";      \r
-       var $hasInsertID = true;\r
-       \r
-       function ADODB_sqlanywhere()\r
-       {\r
-               $this->ADODB_odbc();\r
-       }\r
-\r
-        function _insertid() {\r
-          return $this->GetOne('select @@identity');\r
-        }\r
-\r
-  function create_blobvar($blobVarName) {\r
-   $this->Execute("create variable $blobVarName long binary");\r
-   return;\r
-  }\r
-\r
-  function drop_blobvar($blobVarName) {\r
-   $this->Execute("drop variable $blobVarName");\r
-   return;\r
-  }\r
-\r
-  function load_blobvar_from_file($blobVarName, $filename) {\r
-   $chunk_size = 1000;\r
-\r
-   $fd = fopen ($filename, "rb");\r
-\r
-   $integer_chunks = (integer)filesize($filename) / $chunk_size;\r
-   $modulus = filesize($filename) % $chunk_size;\r
-   if ($modulus != 0){\r
-       $integer_chunks += 1;\r
-   }\r
-\r
-   for($loop=1;$loop<=$integer_chunks;$loop++){\r
-       $contents = fread ($fd, $chunk_size);\r
-       $contents = bin2hex($contents);\r
-\r
-       $hexstring = '';\r
-\r
-       for($loop2=0;$loop2<strlen($contents);$loop2+=2){\r
-        $hexstring .= '\x' . substr($contents,$loop2,2);\r
-        }\r
-\r
-       $hexstring = $this->qstr($hexstring);\r
-\r
-       $this->Execute("set $blobVarName = $blobVarName || " . $hexstring);\r
-   }\r
-\r
-   fclose ($fd);\r
-   return;\r
-  }\r
-\r
-  function load_blobvar_from_var($blobVarName, &$varName) {\r
-   $chunk_size = 1000;\r
-\r
-   $integer_chunks = (integer)strlen($varName) / $chunk_size;\r
-   $modulus = strlen($varName) % $chunk_size;\r
-   if ($modulus != 0){\r
-       $integer_chunks += 1;\r
-   }\r
-\r
-   for($loop=1;$loop<=$integer_chunks;$loop++){\r
-       $contents = substr ($varName, (($loop - 1) * $chunk_size), $chunk_size);\r
-       $contents = bin2hex($contents);\r
-\r
-       $hexstring = '';\r
-\r
-       for($loop2=0;$loop2<strlen($contents);$loop2+=2){\r
-        $hexstring .= '\x' . substr($contents,$loop2,2);\r
-        }\r
-\r
-       $hexstring = $this->qstr($hexstring);\r
-\r
-       $this->Execute("set $blobVarName = $blobVarName || " . $hexstring);\r
-   }\r
-\r
-   return;\r
-  }\r
-\r
- /*\r
-  Insert a null into the blob field of the table first.\r
-  Then use UpdateBlob to store the blob.\r
-\r
-  Usage:\r
-\r
-  $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');\r
-  $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');\r
- */\r
-  function UpdateBlob($table,$column,&$val,$where,$blobtype='BLOB')\r
-  {\r
-   $blobVarName = 'hold_blob';\r
-   $this->create_blobvar($blobVarName);\r
-   $this->load_blobvar_from_var($blobVarName, $val);\r
-   $this->Execute("UPDATE $table SET $column=$blobVarName WHERE $where");\r
-   $this->drop_blobvar($blobVarName);\r
-   return true;\r
-  }\r
- }; //class\r
-\r
- class  ADORecordSet_sqlanywhere extends ADORecordSet_odbc {   \r
-\r
-  var $databaseType = "sqlanywhere";           \r
-\r
- function ADORecordSet_sqlanywhere($id,$mode=false)\r
- {\r
-  $this->ADORecordSet_odbc($id,$mode);\r
- }\r
-\r
-\r
- }; //class\r
-\r
-\r
-} //define\r
-?>\r
+<?php
+/* 
+version V4.20 22 Feb 2004 (c) 2000-2004  John Lim (jlim@natsoft.com.my). All rights
+reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+
+  Latest version is available at http://php.weblogs.com/
+
+  21.02.2002 - Wade Johnson wade@wadejohnson.de
+                          Extended ODBC class for Sybase SQLAnywhere.
+   1) Added support to retrieve the last row insert ID on tables with
+         primary key column using autoincrement function.
+
+   2) Added blob support.  Usage:
+                a) create blob variable on db server:
+
+               $dbconn->create_blobvar($blobVarName);
+
+         b) load blob var from file.  $filename must be complete path
+
+         $dbcon->load_blobvar_from_file($blobVarName, $filename);
+
+         c) Use the $blobVarName in SQL insert or update statement in the values
+         clause:
+
+               $recordSet = $dbconn->Execute('INSERT INTO tabname (idcol, blobcol) '
+               .
+          'VALUES (\'test\', ' . $blobVarName . ')');
+
+        instead of loading blob from a file, you can also load from 
+         an unformatted (raw) blob variable:
+         $dbcon->load_blobvar_from_var($blobVarName, $varName);
+
+         d) drop blob variable on db server to free up resources:
+         $dbconn->drop_blobvar($blobVarName);
+
+  Sybase_SQLAnywhere data driver. Requires ODBC.
+
+*/
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+ include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+
+if (!defined('ADODB_SYBASE_SQLANYWHERE')){
+
+ define('ADODB_SYBASE_SQLANYWHERE',1);
+
+ class ADODB_sqlanywhere extends ADODB_odbc {
+       var $databaseType = "sqlanywhere";      
+       var $hasInsertID = true;
+       
+       function ADODB_sqlanywhere()
+       {
+               $this->ADODB_odbc();
+       }
+
+        function _insertid() {
+          return $this->GetOne('select @@identity');
+        }
+
+  function create_blobvar($blobVarName) {
+   $this->Execute("create variable $blobVarName long binary");
+   return;
+  }
+
+  function drop_blobvar($blobVarName) {
+   $this->Execute("drop variable $blobVarName");
+   return;
+  }
+
+  function load_blobvar_from_file($blobVarName, $filename) {
+   $chunk_size = 1000;
+
+   $fd = fopen ($filename, "rb");
+
+   $integer_chunks = (integer)filesize($filename) / $chunk_size;
+   $modulus = filesize($filename) % $chunk_size;
+   if ($modulus != 0){
+       $integer_chunks += 1;
+   }
+
+   for($loop=1;$loop<=$integer_chunks;$loop++){
+       $contents = fread ($fd, $chunk_size);
+       $contents = bin2hex($contents);
+
+       $hexstring = '';
+
+       for($loop2=0;$loop2<strlen($contents);$loop2+=2){
+        $hexstring .= '\x' . substr($contents,$loop2,2);
+        }
+
+       $hexstring = $this->qstr($hexstring);
+
+       $this->Execute("set $blobVarName = $blobVarName || " . $hexstring);
+   }
+
+   fclose ($fd);
+   return;
+  }
+
+  function load_blobvar_from_var($blobVarName, &$varName) {
+   $chunk_size = 1000;
+
+   $integer_chunks = (integer)strlen($varName) / $chunk_size;
+   $modulus = strlen($varName) % $chunk_size;
+   if ($modulus != 0){
+       $integer_chunks += 1;
+   }
+
+   for($loop=1;$loop<=$integer_chunks;$loop++){
+       $contents = substr ($varName, (($loop - 1) * $chunk_size), $chunk_size);
+       $contents = bin2hex($contents);
+
+       $hexstring = '';
+
+       for($loop2=0;$loop2<strlen($contents);$loop2+=2){
+        $hexstring .= '\x' . substr($contents,$loop2,2);
+        }
+
+       $hexstring = $this->qstr($hexstring);
+
+       $this->Execute("set $blobVarName = $blobVarName || " . $hexstring);
+   }
+
+   return;
+  }
+
+ /*
+  Insert a null into the blob field of the table first.
+  Then use UpdateBlob to store the blob.
+
+  Usage:
+
+  $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
+  $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
+ */
+  function UpdateBlob($table,$column,&$val,$where,$blobtype='BLOB')
+  {
+   $blobVarName = 'hold_blob';
+   $this->create_blobvar($blobVarName);
+   $this->load_blobvar_from_var($blobVarName, $val);
+   $this->Execute("UPDATE $table SET $column=$blobVarName WHERE $where");
+   $this->drop_blobvar($blobVarName);
+   return true;
+  }
+ }; //class
+
+ class  ADORecordSet_sqlanywhere extends ADORecordSet_odbc {   
+
+  var $databaseType = "sqlanywhere";           
+
+ function ADORecordSet_sqlanywhere($id,$mode=false)
+ {
+  $this->ADORecordSet_odbc($id,$mode);
+ }
+
+
+ }; //class
+
+
+} //define
+?>
index db2d3d8c49ca73063e34e9ad4f731c0b5ba36985..447f664da4d8f061e3b8c1db756f03363d28690a 100644 (file)
-<?php\r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-\r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  SQLite info: http://www.hwaci.com/sw/sqlite/\r
-    \r
-  Install Instructions:\r
-  ====================\r
-  1. Place this in adodb/drivers\r
-  2. Rename the file, remove the .txt prefix.\r
-*/\r
-\r
-class ADODB_sqlite extends ADOConnection {\r
-       var $databaseType = "sqlite";\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $concat_operator='||';\r
-       var $_errorNo = 0;\r
-       var $hasLimit = true;   \r
-       var $hasInsertID = true;                /// supports autoincrement ID?\r
-       var $hasAffectedRows = true;    /// supports affected rows for update/delete?\r
-       var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name";\r
-       var $sysDate = "adodb_date('Y-m-d')";\r
-       var $sysTimeStamp = "adodb_date('Y-m-d H:i:s')";\r
-       \r
-       function ADODB_sqlite() \r
-       {\r
-       }\r
-       \r
-/*\r
-  function __get($name) \r
-  {\r
-       switch($name) {\r
-       case 'sysDate': return "'".date($this->fmtDate)."'";\r
-       case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'";\r
-       }\r
-  }*/\r
-       \r
-       function ServerInfo()\r
-       {\r
-               $arr['version'] = sqlite_libversion();\r
-               $arr['description'] = 'SQLite ';\r
-               $arr['encoding'] = sqlite_libencoding();\r
-               return $arr;\r
-       }\r
-       \r
-       function BeginTrans()\r
-       {         \r
-                if ($this->transOff) return true; \r
-                $ret = $this->Execute("BEGIN TRANSACTION");\r
-                $this->transCnt += 1;\r
-                return true;\r
-       }\r
-       \r
-       function CommitTrans($ok=true) \r
-       { \r
-               if ($this->transOff) return true; \r
-               if (!$ok) return $this->RollbackTrans();\r
-               $ret = $this->Execute("COMMIT");\r
-               if ($this->transCnt>0)$this->transCnt -= 1;\r
-               return !empty($ret);\r
-       }\r
-       \r
-       function RollbackTrans()\r
-       {\r
-               if ($this->transOff) return true; \r
-               $ret = $this->Execute("ROLLBACK");\r
-               if ($this->transCnt>0)$this->transCnt -= 1;\r
-               return !empty($ret);\r
-       }\r
-\r
-       function _insertid()\r
-       {\r
-               return sqlite_last_insert_rowid($this->_connectionID);\r
-       }\r
-       \r
-       function _affectedrows()\r
-       {\r
-        return sqlite_changes($this->_connectionID);\r
-    }\r
-       \r
-       function ErrorMsg() \r
-       {\r
-               if ($this->_logsql) return $this->_errorMsg;\r
-               return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : '';\r
-       }\r
\r
-       function ErrorNo() \r
-       {\r
-               return $this->_errorNo;\r
-       }\r
-       \r
-       function SQLDate($fmt, $col=false)\r
-       {\r
-               $fmt = $this->qstr($fmt);\r
-               return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)";\r
-       }\r
-       \r
-       function &MetaColumns($tab)\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $rs = $this->Execute("select * from $tab limit 1");\r
-               if (!$rs) return false;\r
-               $arr = array();\r
-               for ($i=0,$max=$rs->_numOfFields; $i < $max; $i++) {\r
-                       $fld =& $rs->FetchField($i);\r
-                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] =& $fld;    \r
-                       else $arr[strtoupper($fld->name)] =& $fld;\r
-               }\r
-               $rs->Close();\r
-               return $arr;\r
-       }\r
-       \r
-       function _createFunctions()\r
-       {\r
-               @sqlite_create_function($this->_connectionID, 'adodb_date', 'adodb_date', 1);\r
-               @sqlite_create_function($this->_connectionID, 'adodb_date2', 'adodb_date2', 2);\r
-       }\r
-       \r
-\r
-       // returns true or false\r
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (!function_exists('sqlite_open')) return false;\r
-               \r
-               $this->_connectionID = sqlite_open($argHostname);\r
-               if ($this->_connectionID === false) return false;\r
-               $this->_createFunctions();\r
-               return true;\r
-       }\r
-       \r
-       // returns true or false\r
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (!function_exists('sqlite_open')) return false;\r
-               \r
-               $this->_connectionID = sqlite_popen($argHostname);\r
-               if ($this->_connectionID === false) return false;\r
-               $this->_createFunctions();\r
-               return true;\r
-       }\r
-\r
-       // returns query ID if successful, otherwise false\r
-       function _query($sql,$inputarr=false)\r
-       {\r
-               $rez = sqlite_query($sql,$this->_connectionID);\r
-               if (!$rez) {\r
-                       $this->_errorNo = sqlite_last_error($this->_connectionID);\r
-               }\r
-               \r
-               return $rez;\r
-       }\r
-       \r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) \r
-       {\r
-               $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';\r
-               $limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : '');\r
-               if ($secs2cache)\r
-                       $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);\r
-               else\r
-                       $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);\r
-                       \r
-               return $rs;\r
-       }\r
-       \r
-       /*\r
-               This algorithm is not very efficient, but works even if table locking\r
-               is not available.\r
-               \r
-               Will return false if unable to generate an ID after $MAXLOOPS attempts.\r
-       */\r
-       var $_genSeqSQL = "create table %s (id integer)";\r
-       \r
-       function GenID($seq='adodbseq',$start=1)\r
-       {       \r
-               // if you have to modify the parameter below, your database is overloaded,\r
-               // or you need to implement generation of id's yourself!\r
-               $MAXLOOPS = 100;\r
-               //$this->debug=1;\r
-               while (--$MAXLOOPS>=0) {\r
-                       $num = $this->GetOne("select id from $seq");\r
-                       if ($num === false) {\r
-                               $this->Execute(sprintf($this->_genSeqSQL ,$seq));       \r
-                               $start -= 1;\r
-                               $num = '0';\r
-                               $ok = $this->Execute("insert into $seq values($start)");\r
-                               if (!$ok) return false;\r
-                       } \r
-                       $this->Execute("update $seq set id=id+1 where id=$num");\r
-                       \r
-                       if ($this->affected_rows() > 0) {\r
-                               $num += 1;\r
-                               $this->genID = $num;\r
-                               return $num;\r
-                       }\r
-               }\r
-               if ($fn = $this->raiseErrorFn) {\r
-                       $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);\r
-               }\r
-               return false;\r
-       }\r
-\r
-       function CreateSequence($seqname='adodbseq',$start=1)\r
-       {\r
-               if (empty($this->_genSeqSQL)) return false;\r
-               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));\r
-               if (!$ok) return false;\r
-               $start -= 1;\r
-               return $this->Execute("insert into $seqname values($start)");\r
-       }\r
-       \r
-       var $_dropSeqSQL = 'drop table %s';\r
-       function DropSequence($seqname)\r
-       {\r
-               if (empty($this->_dropSeqSQL)) return false;\r
-               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));\r
-       }\r
-       \r
-       // returns true or false\r
-       function _close()\r
-       {\r
-               return @sqlite_close($this->_connectionID);\r
-       }\r
-\r
-\r
-}\r
-\r
-/*--------------------------------------------------------------------------------------\r
-                Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-\r
-class ADORecordset_sqlite extends ADORecordSet {\r
-\r
-       var $databaseType = "sqlite";\r
-       var $bind = false;\r
-\r
-       function ADORecordset_sqlite($queryID,$mode=false)\r
-       {\r
-               \r
-               if ($mode === false) { \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               switch($mode) {\r
-               case ADODB_FETCH_NUM: $this->fetchMode = SQLITE_NUM; break;\r
-               case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE_ASSOC; break;\r
-               default: $this->fetchMode = SQLITE_BOTH; break;\r
-               }\r
-               \r
-               $this->_queryID = $queryID;\r
-       \r
-               $this->_inited = true;\r
-               $this->fields = array();\r
-               if ($queryID) {\r
-                       $this->_currentRow = 0;\r
-                       $this->EOF = !$this->_fetch();\r
-                       @$this->_initrs();\r
-               } else {\r
-                       $this->_numOfRows = 0;\r
-                       $this->_numOfFields = 0;\r
-                       $this->EOF = true;\r
-               }\r
-               \r
-               return $this->_queryID;\r
-       }\r
-\r
-\r
-       function &FetchField($fieldOffset = -1)\r
-       {\r
-               $fld = new ADOFieldObject;\r
-               $fld->name = sqlite_field_name($this->_queryID, $fieldOffset);\r
-               $fld->type = 'VARCHAR';\r
-               $fld->max_length = -1;\r
-               return $fld;\r
-       }\r
-       \r
-   function _initrs()\r
-   {\r
-               $this->_numOfRows = @sqlite_num_rows($this->_queryID);\r
-               $this->_numOfFields = @sqlite_num_fields($this->_queryID);\r
-   }\r
-\r
-       function Fields($colname)\r
-       {\r
-               if ($this->fetchMode != SQLITE_NUM) return $this->fields[$colname];\r
-               if (!$this->bind) {\r
-                       $this->bind = array();\r
-                       for ($i=0; $i < $this->_numOfFields; $i++) {\r
-                               $o = $this->FetchField($i);\r
-                               $this->bind[strtoupper($o->name)] = $i;\r
-                       }\r
-               }\r
-               \r
-                return $this->fields[$this->bind[strtoupper($colname)]];\r
-       }\r
-       \r
-   function _seek($row)\r
-   {\r
-               return sqlite_seek($this->_queryID, $row);\r
-   }\r
-\r
-       function _fetch($ignore_fields=false) \r
-       {\r
-               $this->fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode);\r
-               return !empty($this->fields);\r
-       }\r
-       \r
-       function _close() \r
-       {\r
-       }\r
-\r
-}\r
+<?php
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+
+  Latest version is available at http://php.weblogs.com/
+  
+  SQLite info: http://www.hwaci.com/sw/sqlite/
+    
+  Install Instructions:
+  ====================
+  1. Place this in adodb/drivers
+  2. Rename the file, remove the .txt prefix.
+*/
+
+class ADODB_sqlite extends ADOConnection {
+       var $databaseType = "sqlite";
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $concat_operator='||';
+       var $_errorNo = 0;
+       var $hasLimit = true;   
+       var $hasInsertID = true;                /// supports autoincrement ID?
+       var $hasAffectedRows = true;    /// supports affected rows for update/delete?
+       var $metaTablesSQL = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name";
+       var $sysDate = "adodb_date('Y-m-d')";
+       var $sysTimeStamp = "adodb_date('Y-m-d H:i:s')";
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";
+       
+       function ADODB_sqlite() 
+       {
+       }
+       
+/*
+  function __get($name) 
+  {
+       switch($name) {
+       case 'sysDate': return "'".date($this->fmtDate)."'";
+       case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'";
+       }
+  }*/
+       
+       function ServerInfo()
+       {
+               $arr['version'] = sqlite_libversion();
+               $arr['description'] = 'SQLite ';
+               $arr['encoding'] = sqlite_libencoding();
+               return $arr;
+       }
+       
+       function BeginTrans()
+       {         
+                if ($this->transOff) return true; 
+                $ret = $this->Execute("BEGIN TRANSACTION");
+                $this->transCnt += 1;
+                return true;
+       }
+       
+       function CommitTrans($ok=true) 
+       { 
+               if ($this->transOff) return true; 
+               if (!$ok) return $this->RollbackTrans();
+               $ret = $this->Execute("COMMIT");
+               if ($this->transCnt>0)$this->transCnt -= 1;
+               return !empty($ret);
+       }
+       
+       function RollbackTrans()
+       {
+               if ($this->transOff) return true; 
+               $ret = $this->Execute("ROLLBACK");
+               if ($this->transCnt>0)$this->transCnt -= 1;
+               return !empty($ret);
+       }
+
+       function _insertid()
+       {
+               return sqlite_last_insert_rowid($this->_connectionID);
+       }
+       
+       function _affectedrows()
+       {
+        return sqlite_changes($this->_connectionID);
+    }
+       
+       function ErrorMsg() 
+       {
+               if ($this->_logsql) return $this->_errorMsg;
+               return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : '';
+       }
+       function ErrorNo() 
+       {
+               return $this->_errorNo;
+       }
+       
+       function SQLDate($fmt, $col=false)
+       {
+               $fmt = $this->qstr($fmt);
+               return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)";
+       }
+       
+       function &MetaColumns($tab)
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $rs = $this->Execute("select * from $tab limit 1");
+               if (!$rs) return false;
+               $arr = array();
+               for ($i=0,$max=$rs->_numOfFields; $i < $max; $i++) {
+                       $fld =& $rs->FetchField($i);
+                       if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] =& $fld;    
+                       else $arr[strtoupper($fld->name)] =& $fld;
+               }
+               $rs->Close();
+               return $arr;
+       }
+       
+       function _createFunctions()
+       {
+               @sqlite_create_function($this->_connectionID, 'adodb_date', 'adodb_date', 1);
+               @sqlite_create_function($this->_connectionID, 'adodb_date2', 'adodb_date2', 2);
+       }
+       
+
+       // returns true or false
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (!function_exists('sqlite_open')) return false;
+               
+               $this->_connectionID = sqlite_open($argHostname);
+               if ($this->_connectionID === false) return false;
+               $this->_createFunctions();
+               return true;
+       }
+       
+       // returns true or false
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (!function_exists('sqlite_open')) return false;
+               
+               $this->_connectionID = sqlite_popen($argHostname);
+               if ($this->_connectionID === false) return false;
+               $this->_createFunctions();
+               return true;
+       }
+
+       // returns query ID if successful, otherwise false
+       function _query($sql,$inputarr=false)
+       {
+               $rez = sqlite_query($sql,$this->_connectionID);
+               if (!$rez) {
+                       $this->_errorNo = sqlite_last_error($this->_connectionID);
+               }
+               
+               return $rez;
+       }
+       
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) 
+       {
+               $offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
+               $limitStr  = ($nrows >= 0)  ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : '');
+               if ($secs2cache)
+                       $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr);
+               else
+                       $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr);
+                       
+               return $rs;
+       }
+       
+       /*
+               This algorithm is not very efficient, but works even if table locking
+               is not available.
+               
+               Will return false if unable to generate an ID after $MAXLOOPS attempts.
+       */
+       var $_genSeqSQL = "create table %s (id integer)";
+       
+       function GenID($seq='adodbseq',$start=1)
+       {       
+               // if you have to modify the parameter below, your database is overloaded,
+               // or you need to implement generation of id's yourself!
+               $MAXLOOPS = 100;
+               //$this->debug=1;
+               while (--$MAXLOOPS>=0) {
+                       $num = $this->GetOne("select id from $seq");
+                       if ($num === false) {
+                               $this->Execute(sprintf($this->_genSeqSQL ,$seq));       
+                               $start -= 1;
+                               $num = '0';
+                               $ok = $this->Execute("insert into $seq values($start)");
+                               if (!$ok) return false;
+                       } 
+                       $this->Execute("update $seq set id=id+1 where id=$num");
+                       
+                       if ($this->affected_rows() > 0) {
+                               $num += 1;
+                               $this->genID = $num;
+                               return $num;
+                       }
+               }
+               if ($fn = $this->raiseErrorFn) {
+                       $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
+               }
+               return false;
+       }
+
+       function CreateSequence($seqname='adodbseq',$start=1)
+       {
+               if (empty($this->_genSeqSQL)) return false;
+               $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
+               if (!$ok) return false;
+               $start -= 1;
+               return $this->Execute("insert into $seqname values($start)");
+       }
+       
+       var $_dropSeqSQL = 'drop table %s';
+       function DropSequence($seqname)
+       {
+               if (empty($this->_dropSeqSQL)) return false;
+               return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
+       }
+       
+       // returns true or false
+       function _close()
+       {
+               return @sqlite_close($this->_connectionID);
+       }
+
+
+}
+
+/*--------------------------------------------------------------------------------------
+                Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+
+class ADORecordset_sqlite extends ADORecordSet {
+
+       var $databaseType = "sqlite";
+       var $bind = false;
+
+       function ADORecordset_sqlite($queryID,$mode=false)
+       {
+               
+               if ($mode === false) { 
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               switch($mode) {
+               case ADODB_FETCH_NUM: $this->fetchMode = SQLITE_NUM; break;
+               case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE_ASSOC; break;
+               default: $this->fetchMode = SQLITE_BOTH; break;
+               }
+               
+               $this->_queryID = $queryID;
+       
+               $this->_inited = true;
+               $this->fields = array();
+               if ($queryID) {
+                       $this->_currentRow = 0;
+                       $this->EOF = !$this->_fetch();
+                       @$this->_initrs();
+               } else {
+                       $this->_numOfRows = 0;
+                       $this->_numOfFields = 0;
+                       $this->EOF = true;
+               }
+               
+               return $this->_queryID;
+       }
+
+
+       function &FetchField($fieldOffset = -1)
+       {
+               $fld = new ADOFieldObject;
+               $fld->name = sqlite_field_name($this->_queryID, $fieldOffset);
+               $fld->type = 'VARCHAR';
+               $fld->max_length = -1;
+               return $fld;
+       }
+       
+   function _initrs()
+   {
+               $this->_numOfRows = @sqlite_num_rows($this->_queryID);
+               $this->_numOfFields = @sqlite_num_fields($this->_queryID);
+   }
+
+       function Fields($colname)
+       {
+               if ($this->fetchMode != SQLITE_NUM) return $this->fields[$colname];
+               if (!$this->bind) {
+                       $this->bind = array();
+                       for ($i=0; $i < $this->_numOfFields; $i++) {
+                               $o = $this->FetchField($i);
+                               $this->bind[strtoupper($o->name)] = $i;
+                       }
+               }
+               
+                return $this->fields[$this->bind[strtoupper($colname)]];
+       }
+       
+   function _seek($row)
+   {
+               return sqlite_seek($this->_queryID, $row);
+   }
+
+       function _fetch($ignore_fields=false) 
+       {
+               $this->fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode);
+               return !empty($this->fields);
+       }
+       
+       function _close() 
+       {
+       }
+
+}
 ?>
\ No newline at end of file
index b16266749789bd81bb781b5d0e99571132e3dc52..2c8982210fbfbc4d92ce016bc665599901ace4f5 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim. All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Sybase driver contributed by Toni (toni.tunkkari@finebyte.com)\r
-  \r
-  - MSSQL date patch applied.\r
-  \r
-  Date patch by Toni 15 Feb 2002\r
-*/\r
\r
-class ADODB_sybase extends ADOConnection {\r
-       var $databaseType = "sybase";   \r
-       //var $dataProvider = 'sybase';\r
-       var $replaceQuote = "''"; // string to use to replace quotes\r
-       var $fmtDate = "'Y-m-d'";\r
-       var $fmtTimeStamp = "'Y-m-d H:i:s'";\r
-       var $hasInsertID = true;\r
-       var $hasAffectedRows = true;\r
-       var $metaTablesSQL="select name from sysobjects where type='U' or type='V'";\r
-       // see http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8\r
-       var $metaColumnsSQL = "SELECT c.column_name, c.column_type, c.width FROM syscolumn c, systable t WHERE t.table_name='%s' AND c.table_id=t.table_id AND t.table_type='BASE'";\r
-       /*\r
-       "select c.name,t.name,c.length from \r
-       syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id \r
-       where o.name='%s'";\r
-       */\r
-       var $concat_operator = '+'; \r
-       var $sysDate = 'GetDate()';\r
-       var $arrayClass = 'ADORecordSet_array_sybase';\r
-       var $sysDate = 'GetDate()';\r
-       var $leftOuter = '*=';\r
-       var $rightOuter = '=*';\r
-       \r
-       \r
-       \r
-       function ADODB_sybase() \r
-       {                       \r
-       }\r
\r
-       // might require begintrans -- committrans\r
-       function _insertid()\r
-       {\r
-               return $this->GetOne('select @@identity');\r
-       }\r
-         // might require begintrans -- committrans\r
-       function _affectedrows()\r
-       {\r
-          return $this->GetOne('select @@rowcount');\r
-       }\r
-\r
-                         \r
-       function BeginTrans()\r
-       {       \r
-       \r
-               if ($this->transOff) return true;\r
-               $this->transCnt += 1;\r
-                  \r
-               $this->Execute('BEGIN TRAN');\r
-               return true;\r
-       }\r
-       \r
-       function CommitTrans($ok=true) \r
-       { \r
-               if ($this->transOff) return true;\r
-               \r
-               if (!$ok) return $this->RollbackTrans();\r
-       \r
-               $this->transCnt -= 1;\r
-               $this->Execute('COMMIT TRAN');\r
-               return true;\r
-       }\r
-       \r
-       function RollbackTrans()\r
-       {\r
-               if ($this->transOff) return true;\r
-               $this->transCnt -= 1;\r
-               $this->Execute('ROLLBACK TRAN');\r
-               return true;\r
-       }\r
-       \r
-       // http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4\r
-       function RowLock($tables,$where) \r
-       {\r
-               if (!$this->_hastrans) $this->BeginTrans();\r
-               $tables = str_replace(',',' HOLDLOCK,',$tables);\r
-               return $this->GetOne("select top 1 null as ignore from $tables HOLDLOCK where $where");\r
-               \r
-       }       \r
-               \r
-       function SelectDB($dbName) {\r
-               $this->databaseName = $dbName;\r
-               if ($this->_connectionID) {\r
-                       return @sybase_select_db($dbName);              \r
-               }\r
-               else return false;      \r
-       }\r
-\r
-       /*      Returns: the last error message from previous database operation\r
-               Note: This function is NOT available for Microsoft SQL Server.  */      \r
-\r
-       function ErrorMsg() \r
-       {\r
-               if ($this->_logsql) return $this->_errorMsg;\r
-               $this->_errorMsg = sybase_get_last_message();\r
-               return $this->_errorMsg;\r
-       }\r
-\r
-       // returns true or false\r
-       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (!function_exists('sybase_connect')) return false;\r
-               \r
-               $this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);\r
-               if ($this->_connectionID === false) return false;\r
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-               return true;    \r
-       }\r
-       // returns true or false\r
-       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)\r
-       {\r
-               if (!function_exists('sybase_connect')) return false;\r
-               \r
-               $this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);\r
-               if ($this->_connectionID === false) return false;\r
-               if ($argDatabasename) return $this->SelectDB($argDatabasename);\r
-               return true;    \r
-       }\r
-       \r
-       // returns query ID if successful, otherwise false\r
-       function _query($sql,$inputarr)\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-       \r
-               if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300)\r
-                       return sybase_unbuffered_query($sql,$this->_connectionID);\r
-               else\r
-                       return sybase_query($sql,$this->_connectionID);\r
-       }\r
-       \r
-       // See http://www.isug.com/Sybase_FAQ/ASE/section6.2.html#6.2.12\r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) \r
-       {\r
-               if ($secs2cache > 0) {// we do not cache rowcount, so we have to load entire recordset\r
-                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
-                       return $rs;\r
-               }\r
-               $cnt = ($nrows > 0) ? $nrows : 0;\r
-               if ($offset > 0 && $cnt) $cnt += $offset;\r
-               \r
-               $this->Execute("set rowcount $cnt"); \r
-               $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
-               $this->Execute("set rowcount 0"); \r
-               \r
-               return $rs;\r
-       }\r
-\r
-       // returns true or false\r
-       function _close()\r
-       { \r
-               return @sybase_close($this->_connectionID);\r
-       }\r
-       \r
-       function UnixDate($v)\r
-       {\r
-               return ADORecordSet_array_sybase::UnixDate($v);\r
-       }\r
-       \r
-       function UnixTimeStamp($v)\r
-       {\r
-               return ADORecordSet_array_sybase::UnixTimeStamp($v);\r
-       }       \r
-       \r
-       \r
-\r
-       # Added 2003-10-05 by Chris Phillipson\r
-    # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=16756?target=%25N%15_12018_START_RESTART_N%25\r
-    # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version\r
-    // Format date column in sql string given an input format that understands Y M D\r
-    function SQLDate($fmt, $col=false)\r
-    {\r
-        if (!$col) $col = $this->sysTimeStamp;\r
-        $s = '';\r
-\r
-        $len = strlen($fmt);\r
-        for ($i=0; $i < $len; $i++) {\r
-            if ($s) $s .= '+';\r
-            $ch = $fmt[$i];\r
-            switch($ch) {\r
-            case 'Y':\r
-            case 'y':\r
-                $s .= "datename(yy,$col)";\r
-                break;\r
-            case 'M':\r
-                $s .= "convert(char(3),$col,0)";\r
-                break;\r
-            case 'm':\r
-                $s .= "replace(str(month($col),2),' ','0')";\r
-                break;\r
-            case 'Q':\r
-            case 'q':\r
-                $s .= "datename(qq,$col)";\r
-                break;\r
-            case 'D':\r
-            case 'd':\r
-                $s .= "replace(str(datepart(dd,$col),2),' ','0')";\r
-                break;\r
-            case 'h':\r
-                $s .= "substring(convert(char(14),$col,0),13,2)";\r
-                break;\r
-\r
-            case 'H':\r
-                $s .= "replace(str(datepart(hh,$col),2),' ','0')";\r
-                break;\r
-\r
-            case 'i':\r
-                $s .= "replace(str(datepart(mi,$col),2),' ','0')";\r
-                break;\r
-            case 's':\r
-                $s .= "replace(str(datepart(ss,$col),2),' ','0')";\r
-                break;\r
-            case 'a':\r
-            case 'A':\r
-                $s .= "substring(convert(char(19),$col,0),18,2)";\r
-                break;\r
-\r
-            default:\r
-                if ($ch == '\\') {\r
-                    $i++;\r
-                    $ch = substr($fmt,$i,1);\r
-                }\r
-                $s .= $this->qstr($ch);\r
-                break;\r
-            }\r
-        }\r
-        return $s;\r
-    }\r
-       \r
-       # Added 2003-10-07 by Chris Phillipson\r
-    # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8\r
-    # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version\r
-    function MetaPrimaryKeys($table)\r
-    {\r
-        $sql = "SELECT c.column_name " .\r
-               "FROM syscolumn c, systable t " .\r
-               "WHERE t.table_name='$table' AND c.table_id=t.table_id " .\r
-               "AND t.table_type='BASE' " .\r
-               "AND c.pkey = 'Y' " .\r
-               "ORDER BY c.column_id";\r
-\r
-        $a = $this->GetCol($sql);\r
-        if ($a && sizeof($a)>0) return $a;\r
-        return false;\r
-    }\r
-}\r
-       \r
-/*--------------------------------------------------------------------------------------\r
-        Class Name: Recordset\r
---------------------------------------------------------------------------------------*/\r
-global $ADODB_sybase_mths;\r
-$ADODB_sybase_mths = array(\r
-       'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,\r
-       'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);\r
-\r
-class ADORecordset_sybase extends ADORecordSet {       \r
-\r
-       var $databaseType = "sybase";\r
-       var $canSeek = true;\r
-       // _mths works only in non-localised system\r
-       var  $_mths = array('JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);    \r
-\r
-       function ADORecordset_sybase($id,$mode=false)\r
-       {\r
-               if ($mode === false) { \r
-                       global $ADODB_FETCH_MODE;\r
-                       $mode = $ADODB_FETCH_MODE;\r
-               }\r
-               if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC;\r
-               else $this->fetchMode = $mode;\r
-               return $this->ADORecordSet($id,$mode);\r
-       }\r
-       \r
-       /*      Returns: an object containing field information. \r
-               Get column information in the Recordset object. fetchField() can be used in order to obtain information about\r
-               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by\r
-               fetchField() is retrieved.      */\r
-       function &FetchField($fieldOffset = -1) \r
-       {\r
-               if ($fieldOffset != -1) {\r
-                       $o = @sybase_fetch_field($this->_queryID, $fieldOffset);\r
-               }\r
-               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */\r
-                       $o = @sybase_fetch_field($this->_queryID);\r
-               }\r
-               // older versions of PHP did not support type, only numeric\r
-               if ($o && !isset($o->type)) $o->type = ($o->numeric) ? 'float' : 'varchar';\r
-               return $o;\r
-       }\r
-       \r
-       function _initrs()\r
-       {\r
-       global $ADODB_COUNTRECS;\r
-               $this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1;\r
-               $this->_numOfFields = @sybase_num_fields($this->_queryID);\r
-       }\r
-       \r
-       function _seek($row) \r
-       {\r
-               return @sybase_data_seek($this->_queryID, $row);\r
-       }               \r
-\r
-       function _fetch($ignore_fields=false) \r
-       {\r
-               if ($this->fetchMode == ADODB_FETCH_NUM) {\r
-                       $this->fields = @sybase_fetch_row($this->_queryID);\r
-               } else if ($this->fetchMode == ADODB_FETCH_ASSOC) {\r
-                       $this->fields = @sybase_fetch_row($this->_queryID);\r
-                       if (is_array($this->fields)) {\r
-                               $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);\r
-                               return true;\r
-                       }\r
-                       return false;\r
-               }  else {\r
-                       $this->fields = @sybase_fetch_array($this->_queryID);\r
-               }\r
-               if ( is_array($this->fields)) {\r
-                       return true;\r
-               }\r
-\r
-               return false;\r
-       }\r
-       \r
-       /*      close() only needs to be called if you are worried about using too much memory while your script\r
-               is running. All associated result memory for the specified result identifier will automatically be freed.       */\r
-       function _close() {\r
-               return @sybase_free_result($this->_queryID);            \r
-       }\r
-       \r
-       // sybase/mssql uses a default date like Dec 30 2000 12:00AM\r
-       function UnixDate($v)\r
-       {\r
-               return ADORecordSet_array_sybase::UnixDate($v);\r
-       }\r
-       \r
-       function UnixTimeStamp($v)\r
-       {\r
-               return ADORecordSet_array_sybase::UnixTimeStamp($v);\r
-       }\r
-}\r
-\r
-class ADORecordSet_array_sybase extends ADORecordSet_array {\r
-       function ADORecordSet_array_sybase($id=-1)\r
-       {\r
-               $this->ADORecordSet_array($id);\r
-       }\r
-       \r
-               // sybase/mssql uses a default date like Dec 30 2000 12:00AM\r
-       function UnixDate($v)\r
-       {\r
-       global $ADODB_sybase_mths;\r
-       \r
-               //Dec 30 2000 12:00AM\r
-               if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})"\r
-                       ,$v, $rr)) return parent::UnixDate($v);\r
-                       \r
-               if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
-               \r
-               $themth = substr(strtoupper($rr[1]),0,3);\r
-               $themth = $ADODB_sybase_mths[$themth];\r
-               if ($themth <= 0) return false;\r
-               // h-m-s-MM-DD-YY\r
-               return  mktime(0,0,0,$themth,$rr[2],$rr[3]);\r
-       }\r
-       \r
-       function UnixTimeStamp($v)\r
-       {\r
-       global $ADODB_sybase_mths;\r
-               //11.02.2001 Toni Tunkkari toni.tunkkari@finebyte.com\r
-               //Changed [0-9] to [0-9 ] in day conversion\r
-               if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})"\r
-                       ,$v, $rr)) return parent::UnixTimeStamp($v);\r
-               if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;\r
-               \r
-               $themth = substr(strtoupper($rr[1]),0,3);\r
-               $themth = $ADODB_sybase_mths[$themth];\r
-               if ($themth <= 0) return false;\r
-               \r
-               switch (strtoupper($rr[6])) {\r
-               case 'P':\r
-                       if ($rr[4]<12) $rr[4] += 12;\r
-                       break;\r
-               case 'A':\r
-                       if ($rr[4]==12) $rr[4] = 0;\r
-                       break;\r
-               default:\r
-                       break;\r
-               }\r
-               // h-m-s-MM-DD-YY\r
-               return  mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]);\r
-       }\r
-}\r
-?>\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim. All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Sybase driver contributed by Toni (toni.tunkkari@finebyte.com)
+  
+  - MSSQL date patch applied.
+  
+  Date patch by Toni 15 Feb 2002
+*/
+class ADODB_sybase extends ADOConnection {
+       var $databaseType = "sybase";   
+       //var $dataProvider = 'sybase';
+       var $replaceQuote = "''"; // string to use to replace quotes
+       var $fmtDate = "'Y-m-d'";
+       var $fmtTimeStamp = "'Y-m-d H:i:s'";
+       var $hasInsertID = true;
+       var $hasAffectedRows = true;
+       var $metaTablesSQL="select name from sysobjects where type='U' or type='V'";
+       // see http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8
+       var $metaColumnsSQL = "SELECT c.column_name, c.column_type, c.width FROM syscolumn c, systable t WHERE t.table_name='%s' AND c.table_id=t.table_id AND t.table_type='BASE'";
+       /*
+       "select c.name,t.name,c.length from 
+       syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id 
+       where o.name='%s'";
+       */
+       var $concat_operator = '+'; 
+       var $arrayClass = 'ADORecordSet_array_sybase';
+       var $sysDate = 'GetDate()';
+       var $leftOuter = '*=';
+       var $rightOuter = '=*';
+       
+       function ADODB_sybase() 
+       {                       
+       }
+       // might require begintrans -- committrans
+       function _insertid()
+       {
+               return $this->GetOne('select @@identity');
+       }
+         // might require begintrans -- committrans
+       function _affectedrows()
+       {
+          return $this->GetOne('select @@rowcount');
+       }
+
+                         
+       function BeginTrans()
+       {       
+       
+               if ($this->transOff) return true;
+               $this->transCnt += 1;
+                  
+               $this->Execute('BEGIN TRAN');
+               return true;
+       }
+       
+       function CommitTrans($ok=true) 
+       { 
+               if ($this->transOff) return true;
+               
+               if (!$ok) return $this->RollbackTrans();
+       
+               $this->transCnt -= 1;
+               $this->Execute('COMMIT TRAN');
+               return true;
+       }
+       
+       function RollbackTrans()
+       {
+               if ($this->transOff) return true;
+               $this->transCnt -= 1;
+               $this->Execute('ROLLBACK TRAN');
+               return true;
+       }
+       
+       // http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4
+       function RowLock($tables,$where) 
+       {
+               if (!$this->_hastrans) $this->BeginTrans();
+               $tables = str_replace(',',' HOLDLOCK,',$tables);
+               return $this->GetOne("select top 1 null as ignore from $tables HOLDLOCK where $where");
+               
+       }       
+               
+       function SelectDB($dbName) {
+               $this->databaseName = $dbName;
+               if ($this->_connectionID) {
+                       return @sybase_select_db($dbName);              
+               }
+               else return false;      
+       }
+
+       /*      Returns: the last error message from previous database operation
+               Note: This function is NOT available for Microsoft SQL Server.  */      
+
+       function ErrorMsg() 
+       {
+               if ($this->_logsql) return $this->_errorMsg;
+               $this->_errorMsg = sybase_get_last_message();
+               return $this->_errorMsg;
+       }
+
+       // returns true or false
+       function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (!function_exists('sybase_connect')) return false;
+               
+               $this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);
+               if ($this->_connectionID === false) return false;
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);
+               return true;    
+       }
+       // returns true or false
+       function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
+       {
+               if (!function_exists('sybase_connect')) return false;
+               
+               $this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);
+               if ($this->_connectionID === false) return false;
+               if ($argDatabasename) return $this->SelectDB($argDatabasename);
+               return true;    
+       }
+       
+       // returns query ID if successful, otherwise false
+       function _query($sql,$inputarr)
+       {
+       global $ADODB_COUNTRECS;
+       
+               if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300)
+                       return sybase_unbuffered_query($sql,$this->_connectionID);
+               else
+                       return sybase_query($sql,$this->_connectionID);
+       }
+       
+       // See http://www.isug.com/Sybase_FAQ/ASE/section6.2.html#6.2.12
+       function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) 
+       {
+               if ($secs2cache > 0) {// we do not cache rowcount, so we have to load entire recordset
+                       $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+                       return $rs;
+               }
+               $cnt = ($nrows > 0) ? $nrows : 0;
+               if ($offset > 0 && $cnt) $cnt += $offset;
+               
+               $this->Execute("set rowcount $cnt"); 
+               $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+               $this->Execute("set rowcount 0"); 
+               
+               return $rs;
+       }
+
+       // returns true or false
+       function _close()
+       { 
+               return @sybase_close($this->_connectionID);
+       }
+       
+       function UnixDate($v)
+       {
+               return ADORecordSet_array_sybase::UnixDate($v);
+       }
+       
+       function UnixTimeStamp($v)
+       {
+               return ADORecordSet_array_sybase::UnixTimeStamp($v);
+       }       
+       
+       
+
+       # Added 2003-10-05 by Chris Phillipson
+    # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=16756?target=%25N%15_12018_START_RESTART_N%25
+    # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version
+    // Format date column in sql string given an input format that understands Y M D
+    function SQLDate($fmt, $col=false)
+    {
+        if (!$col) $col = $this->sysTimeStamp;
+        $s = '';
+
+        $len = strlen($fmt);
+        for ($i=0; $i < $len; $i++) {
+            if ($s) $s .= '+';
+            $ch = $fmt[$i];
+            switch($ch) {
+            case 'Y':
+            case 'y':
+                $s .= "datename(yy,$col)";
+                break;
+            case 'M':
+                $s .= "convert(char(3),$col,0)";
+                break;
+            case 'm':
+                $s .= "replace(str(month($col),2),' ','0')";
+                break;
+            case 'Q':
+            case 'q':
+                $s .= "datename(qq,$col)";
+                break;
+            case 'D':
+            case 'd':
+                $s .= "replace(str(datepart(dd,$col),2),' ','0')";
+                break;
+            case 'h':
+                $s .= "substring(convert(char(14),$col,0),13,2)";
+                break;
+
+            case 'H':
+                $s .= "replace(str(datepart(hh,$col),2),' ','0')";
+                break;
+
+            case 'i':
+                $s .= "replace(str(datepart(mi,$col),2),' ','0')";
+                break;
+            case 's':
+                $s .= "replace(str(datepart(ss,$col),2),' ','0')";
+                break;
+            case 'a':
+            case 'A':
+                $s .= "substring(convert(char(19),$col,0),18,2)";
+                break;
+
+            default:
+                if ($ch == '\\') {
+                    $i++;
+                    $ch = substr($fmt,$i,1);
+                }
+                $s .= $this->qstr($ch);
+                break;
+            }
+        }
+        return $s;
+    }
+       
+       # Added 2003-10-07 by Chris Phillipson
+    # Used ASA SQL Reference Manual -- http://sybooks.sybase.com/onlinebooks/group-aw/awg0800e/dbrfen8/@ebt-link;pt=5981;uf=0?target=0;window=new;showtoc=true;book=dbrfen8
+    # to convert similar Microsoft SQL*Server (mssql) API into Sybase compatible version
+    function MetaPrimaryKeys($table)
+    {
+        $sql = "SELECT c.column_name " .
+               "FROM syscolumn c, systable t " .
+               "WHERE t.table_name='$table' AND c.table_id=t.table_id " .
+               "AND t.table_type='BASE' " .
+               "AND c.pkey = 'Y' " .
+               "ORDER BY c.column_id";
+
+        $a = $this->GetCol($sql);
+        if ($a && sizeof($a)>0) return $a;
+        return false;
+    }
+}
+       
+/*--------------------------------------------------------------------------------------
+        Class Name: Recordset
+--------------------------------------------------------------------------------------*/
+global $ADODB_sybase_mths;
+$ADODB_sybase_mths = array(
+       'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,
+       'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
+
+class ADORecordset_sybase extends ADORecordSet {       
+
+       var $databaseType = "sybase";
+       var $canSeek = true;
+       // _mths works only in non-localised system
+       var  $_mths = array('JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);    
+
+       function ADORecordset_sybase($id,$mode=false)
+       {
+               if ($mode === false) { 
+                       global $ADODB_FETCH_MODE;
+                       $mode = $ADODB_FETCH_MODE;
+               }
+               if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC;
+               else $this->fetchMode = $mode;
+               return $this->ADORecordSet($id,$mode);
+       }
+       
+       /*      Returns: an object containing field information. 
+               Get column information in the Recordset object. fetchField() can be used in order to obtain information about
+               fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
+               fetchField() is retrieved.      */
+       function &FetchField($fieldOffset = -1) 
+       {
+               if ($fieldOffset != -1) {
+                       $o = @sybase_fetch_field($this->_queryID, $fieldOffset);
+               }
+               else if ($fieldOffset == -1) {  /*      The $fieldOffset argument is not provided thus its -1   */
+                       $o = @sybase_fetch_field($this->_queryID);
+               }
+               // older versions of PHP did not support type, only numeric
+               if ($o && !isset($o->type)) $o->type = ($o->numeric) ? 'float' : 'varchar';
+               return $o;
+       }
+       
+       function _initrs()
+       {
+       global $ADODB_COUNTRECS;
+               $this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1;
+               $this->_numOfFields = @sybase_num_fields($this->_queryID);
+       }
+       
+       function _seek($row) 
+       {
+               return @sybase_data_seek($this->_queryID, $row);
+       }               
+
+       function _fetch($ignore_fields=false) 
+       {
+               if ($this->fetchMode == ADODB_FETCH_NUM) {
+                       $this->fields = @sybase_fetch_row($this->_queryID);
+               } else if ($this->fetchMode == ADODB_FETCH_ASSOC) {
+                       $this->fields = @sybase_fetch_row($this->_queryID);
+                       if (is_array($this->fields)) {
+                               $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE);
+                               return true;
+                       }
+                       return false;
+               }  else {
+                       $this->fields = @sybase_fetch_array($this->_queryID);
+               }
+               if ( is_array($this->fields)) {
+                       return true;
+               }
+
+               return false;
+       }
+       
+       /*      close() only needs to be called if you are worried about using too much memory while your script
+               is running. All associated result memory for the specified result identifier will automatically be freed.       */
+       function _close() {
+               return @sybase_free_result($this->_queryID);            
+       }
+       
+       // sybase/mssql uses a default date like Dec 30 2000 12:00AM
+       function UnixDate($v)
+       {
+               return ADORecordSet_array_sybase::UnixDate($v);
+       }
+       
+       function UnixTimeStamp($v)
+       {
+               return ADORecordSet_array_sybase::UnixTimeStamp($v);
+       }
+}
+
+class ADORecordSet_array_sybase extends ADORecordSet_array {
+       function ADORecordSet_array_sybase($id=-1)
+       {
+               $this->ADORecordSet_array($id);
+       }
+       
+               // sybase/mssql uses a default date like Dec 30 2000 12:00AM
+       function UnixDate($v)
+       {
+       global $ADODB_sybase_mths;
+       
+               //Dec 30 2000 12:00AM
+               if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})"
+                       ,$v, $rr)) return parent::UnixDate($v);
+                       
+               if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+               
+               $themth = substr(strtoupper($rr[1]),0,3);
+               $themth = $ADODB_sybase_mths[$themth];
+               if ($themth <= 0) return false;
+               // h-m-s-MM-DD-YY
+               return  mktime(0,0,0,$themth,$rr[2],$rr[3]);
+       }
+       
+       function UnixTimeStamp($v)
+       {
+       global $ADODB_sybase_mths;
+               //11.02.2001 Toni Tunkkari toni.tunkkari@finebyte.com
+               //Changed [0-9] to [0-9 ] in day conversion
+               if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})"
+                       ,$v, $rr)) return parent::UnixTimeStamp($v);
+               if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
+               
+               $themth = substr(strtoupper($rr[1]),0,3);
+               $themth = $ADODB_sybase_mths[$themth];
+               if ($themth <= 0) return false;
+               
+               switch (strtoupper($rr[6])) {
+               case 'P':
+                       if ($rr[4]<12) $rr[4] += 12;
+                       break;
+               case 'A':
+                       if ($rr[4]==12) $rr[4] = 0;
+                       break;
+               default:
+                       break;
+               }
+               // h-m-s-MM-DD-YY
+               return  mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]);
+       }
+}
+?>
index 86e1e752abb0e466e5bd91a55368dc92df3a958f..2032ea4541a7ac02894c20bdbfa7f4b94a58d67a 100644 (file)
@@ -1,98 +1,98 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.\r
-*/\r
-\r
-if (!defined('_ADODB_ODBC_LAYER')) {\r
-       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");\r
-}\r
-if (!defined('ADODB_VFP')){\r
-define('ADODB_VFP',1);\r
-class ADODB_vfp extends ADODB_odbc {\r
-       var $databaseType = "vfp";      \r
-       var $fmtDate = "{^Y-m-d}";\r
-       var $fmtTimeStamp = "{^Y-m-d, h:i:sA}";\r
-       var $replaceQuote = "'+chr(39)+'" ;\r
-       var $true = '.T.';\r
-       var $false = '.F.';\r
-       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE\r
-       var $upperCase = 'upper';\r
-       var $_bindInputArray = false; // strangely enough, setting to true does not work reliably\r
-       var $sysTimeStamp = 'datetime()';\r
-       var $sysDate = 'date()';\r
-       var $ansiOuter = true;\r
-       var $hasTransactions = false;\r
-       var $curmode = SQL_CUR_USE_ODBC ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L\r
-       \r
-       function ADODB_vfp()\r
-       {\r
-               $this->ADODB_odbc();\r
-       }\r
-       \r
-       function BeginTrans() { return false;}\r
-       \r
-       // quote string to be sent back to database\r
-       function qstr($s,$nofixquotes=false)\r
-       {\r
-               if (!$nofixquotes) return  "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'";\r
-               return "'".$s."'";\r
-       }\r
-\r
-       \r
-       // TOP requires ORDER BY for VFP\r
-       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)\r
-       {\r
-               if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1';\r
-               return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);\r
-       }\r
-\r
-\r
-};\r
\r
-\r
-class  ADORecordSet_vfp extends ADORecordSet_odbc {    \r
-       \r
-       var $databaseType = "vfp";              \r
-\r
-       \r
-       function ADORecordSet_vfp($id,$mode=false)\r
-       {\r
-               return $this->ADORecordSet_odbc($id,$mode);\r
-       }\r
-\r
-       function MetaType($t,$len=-1)\r
-       {\r
-               if (is_object($t)) {\r
-                       $fieldobj = $t;\r
-                       $t = $fieldobj->type;\r
-                       $len = $fieldobj->max_length;\r
-               }\r
-               switch (strtoupper($t)) {\r
-               case 'C':\r
-                       if ($len <= $this->blobSize) return 'C';\r
-               case 'M':\r
-                       return 'X';\r
-                        \r
-               case 'D': return 'D';\r
-               \r
-               case 'T': return 'T';\r
-               \r
-               case 'L': return 'L';\r
-               \r
-               case 'I': return 'I';\r
-               \r
-               default: return 'N';\r
-               }\r
-       }\r
-}\r
-\r
-} //define\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.
+*/
+
+if (!defined('_ADODB_ODBC_LAYER')) {
+       include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
+}
+if (!defined('ADODB_VFP')){
+define('ADODB_VFP',1);
+class ADODB_vfp extends ADODB_odbc {
+       var $databaseType = "vfp";      
+       var $fmtDate = "{^Y-m-d}";
+       var $fmtTimeStamp = "{^Y-m-d, h:i:sA}";
+       var $replaceQuote = "'+chr(39)+'" ;
+       var $true = '.T.';
+       var $false = '.F.';
+       var $hasTop = 'top';            // support mssql SELECT TOP 10 * FROM TABLE
+       var $upperCase = 'upper';
+       var $_bindInputArray = false; // strangely enough, setting to true does not work reliably
+       var $sysTimeStamp = 'datetime()';
+       var $sysDate = 'date()';
+       var $ansiOuter = true;
+       var $hasTransactions = false;
+       var $curmode = SQL_CUR_USE_ODBC ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
+       
+       function ADODB_vfp()
+       {
+               $this->ADODB_odbc();
+       }
+       
+       function BeginTrans() { return false;}
+       
+       // quote string to be sent back to database
+       function qstr($s,$nofixquotes=false)
+       {
+               if (!$nofixquotes) return  "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'";
+               return "'".$s."'";
+       }
+
+       
+       // TOP requires ORDER BY for VFP
+       function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
+       {
+               if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1';
+               return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
+       }
+
+
+};
+
+class  ADORecordSet_vfp extends ADORecordSet_odbc {    
+       
+       var $databaseType = "vfp";              
+
+       
+       function ADORecordSet_vfp($id,$mode=false)
+       {
+               return $this->ADORecordSet_odbc($id,$mode);
+       }
+
+       function MetaType($t,$len=-1)
+       {
+               if (is_object($t)) {
+                       $fieldobj = $t;
+                       $t = $fieldobj->type;
+                       $len = $fieldobj->max_length;
+               }
+               switch (strtoupper($t)) {
+               case 'C':
+                       if ($len <= $this->blobSize) return 'C';
+               case 'M':
+                       return 'X';
+                        
+               case 'D': return 'D';
+               
+               case 'T': return 'T';
+               
+               case 'L': return 'L';
+               
+               case 'I': return 'I';
+               
+               default: return 'N';
+               }
+       }
+}
+
+} //define
 ?>
\ No newline at end of file
index 65831629fa7075f0e9c630b7958ed11aa4a49e5c..786fc32bfe6f793c86cd5ee5c86d6782e4953f54 100644 (file)
-ADOdb is dual licensed using BSD and LGPL. \r
-\r
-In plain English, you do not need to distribute your application  in source code form, nor do you need to distribute ADOdb source code, provided you follow the rest of terms of the BSD license.\r
-\r
-Commercial use of ADOdb is encouraged. Make money and multiply!\r
-\r
-BSD Style-License\r
-=================\r
-\r
-Copyright (c) 2000, 2001, 2002, 2003 John Lim\r
-All rights reserved.\r
-\r
-Redistribution and use in source and binary forms, with or without modification, \r
-are permitted provided that the following conditions are met:\r
-\r
-Redistributions of source code must retain the above copyright notice, this list \r
-of conditions and the following disclaimer. \r
-\r
-Redistributions in binary form must reproduce the above copyright notice, this list \r
-of conditions and the following disclaimer in the documentation and/or other materials \r
-provided with the distribution. \r
-\r
-Neither the name of the John Lim nor the names of its contributors may be used to \r
-endorse or promote products derived from this software without specific prior written \r
-permission. \r
-\r
-DISCLAIMER:\r
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY \r
-EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF \r
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL \r
-JOHN LIM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, \r
-EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \r
-SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \r
-HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, \r
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS \r
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
-\r
-==========================================================\r
-GNU LESSER GENERAL PUBLIC LICENSE\r
-Version 2.1, February 1999 \r
\r
-Copyright (C) 1991, 1999 Free Software Foundation, Inc.\r
-59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
-Everyone is permitted to copy and distribute verbatim copies\r
-of this license document, but changing it is not allowed.\r
-\r
-[This is the first released version of the Lesser GPL.  It also counts\r
- as the successor of the GNU Library Public License, version 2, hence\r
- the version number 2.1.]\r
\r
\r
-Preamble\r
-The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. \r
-\r
-This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. \r
-\r
-When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. \r
-\r
-To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. \r
-\r
-For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. \r
-\r
-We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. \r
-\r
-To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. \r
-\r
-Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. \r
-\r
-Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. \r
-\r
-When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. \r
-\r
-We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. \r
-\r
-For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. \r
-\r
-In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. \r
-\r
-Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. \r
-\r
-The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. \r
-\r
-\r
-TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\r
-0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". \r
-\r
-A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. \r
-\r
-The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) \r
-\r
-"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. \r
-\r
-Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. \r
-\r
-1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. \r
-\r
-You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. \r
-\r
-2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: \r
-\r
-\r
-a) The modified work must itself be a software library. \r
-b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. \r
-c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. \r
-d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. \r
-(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) \r
-\r
-These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. \r
-\r
-Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. \r
-\r
-In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. \r
-\r
-3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. \r
-\r
-Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. \r
-\r
-This option is useful when you wish to copy part of the code of the Library into a program that is not a library. \r
-\r
-4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. \r
-\r
-If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. \r
-\r
-5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. \r
-\r
-However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. \r
-\r
-When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. \r
-\r
-If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) \r
-\r
-Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. \r
-\r
-6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. \r
-\r
-You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: \r
-\r
-\r
-a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) \r
-b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. \r
-c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. \r
-d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. \r
-e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. \r
-For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. \r
-\r
-It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. \r
-\r
-7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: \r
-\r
-\r
-a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. \r
-b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. \r
-8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. \r
-\r
-9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. \r
-\r
-10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. \r
-\r
-11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. \r
-\r
-If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. \r
-\r
-It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. \r
-\r
-This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. \r
-\r
-12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. \r
-\r
-13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. \r
-\r
-Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. \r
-\r
-14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. \r
-\r
-NO WARRANTY \r
-\r
-15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. \r
-\r
-16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. \r
-\r
-\r
+ADOdb is dual licensed using BSD and LGPL. 
+
+In plain English, you do not need to distribute your application  in source code form, nor do you need to distribute ADOdb source code, provided you follow the rest of terms of the BSD license.
+
+Commercial use of ADOdb is encouraged. Make money and multiply!
+
+BSD Style-License
+=================
+
+Copyright (c) 2000, 2001, 2002, 2003 John Lim
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, 
+are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this list 
+of conditions and the following disclaimer. 
+
+Redistributions in binary form must reproduce the above copyright notice, this list 
+of conditions and the following disclaimer in the documentation and/or other materials 
+provided with the distribution. 
+
+Neither the name of the John Lim nor the names of its contributors may be used to 
+endorse or promote products derived from this software without specific prior written 
+permission. 
+
+DISCLAIMER:
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
+EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
+JOHN LIM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+==========================================================
+GNU LESSER GENERAL PUBLIC LICENSE
+Version 2.1, February 1999 
+Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+Preamble
+The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. 
+
+This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. 
+
+When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. 
+
+To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. 
+
+For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. 
+
+We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. 
+
+To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. 
+
+Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. 
+
+Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. 
+
+When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. 
+
+We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. 
+
+For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. 
+
+In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. 
+
+Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. 
+
+The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. 
+
+
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". 
+
+A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. 
+
+The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) 
+
+"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. 
+
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 
+
+1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. 
+
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 
+
+2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: 
+
+
+a) The modified work must itself be a software library. 
+b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. 
+c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. 
+d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. 
+(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) 
+
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. 
+
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. 
+
+In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 
+
+3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. 
+
+Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. 
+
+This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 
+
+4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. 
+
+If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 
+
+5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. 
+
+However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. 
+
+When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. 
+
+If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) 
+
+Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 
+
+6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. 
+
+You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: 
+
+
+a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) 
+b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. 
+c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. 
+d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. 
+e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. 
+For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. 
+
+It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 
+
+7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: 
+
+
+a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. 
+b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 
+8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 
+
+9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 
+
+10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 
+
+11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. 
+
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. 
+
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. 
+
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 
+
+12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 
+
+13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 
+
+Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 
+
+14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. 
+
+NO WARRANTY 
+
+15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 
+
+16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 
+
+
 END OF TERMS AND CONDITIONS
\ No newline at end of file
index 64e26222d0723d61d7b8880362d5feba569def3b..75bc51149c7303f72ec1b3c32101d9ac98b2bbbc 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. See License.txt. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Library for basic performance monitoring and tuning \r
-  \r
-*/\r
-\r
-\r
-// Simple guide to configuring db2: so-so http://www.devx.com/gethelpon/10MinuteSolution/16575\r
-\r
-// SELECT * FROM TABLE(SNAPSHOT_APPL('SAMPLE', -1)) as t\r
-class perf_db2 extends adodb_perf{\r
-       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
-                 created TIMESTAMP NOT NULL,\r
-                 sql0 varchar(250) NOT NULL,\r
-                 sql1 varchar(4000) NOT NULL,\r
-                 params varchar(3000) NOT NULL,\r
-                 tracer varchar(500) NOT NULL,\r
-                 timer decimal(16,6) NOT NULL\r
-               )";\r
-               \r
-       var $settings = array(\r
-       'Ratios',\r
-               'data cache hit ratio' => array('RATIO',\r
-                       "SELECT \r
-                               case when sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)=0 then 0 \r
-                               else 100*(1-sum(POOL_DATA_P_READS+POOL_INDEX_P_READS)/sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)) end \r
-                               FROM TABLE(SNAPSHOT_APPL('',-2)) as t",\r
-                       '=WarnCacheRatio'),\r
-                       \r
-       'Data Cache',\r
-               'data cache buffers' => array('DATAC',\r
-               'select sum(npages) from SYSCAT.BUFFERPOOLS',\r
-                       'See <a href=http://www7b.boulder.ibm.com/dmdd/library/techarticle/anshum/0107anshum.html#bufferpoolsize>tuning reference</a>.' ),\r
-               'cache blocksize' => array('DATAC',\r
-               'select avg(pagesize) from SYSCAT.BUFFERPOOLS',\r
-                       '' ),\r
-               'data cache size' => array('DATAC',\r
-               'select sum(npages*pagesize) from SYSCAT.BUFFERPOOLS',\r
-                       '' ),\r
-       'Connections',\r
-               'current connections' => array('SESS',\r
-                       "SELECT count(*) FROM TABLE(SNAPSHOT_APPL_INFO('',-2)) as t",\r
-                       ''),\r
-\r
-               false\r
-       );\r
-\r
-\r
-       function perf_db2(&$conn)\r
-       {\r
-               $this->conn =& $conn;\r
-       }\r
-       \r
-       function Explain($sql,$partial=false)\r
-       {\r
-               $save = $this->conn->LogSQL(false);\r
-               if ($partial) {\r
-                       $sqlq = $this->conn->qstr($sql.'%');\r
-                       $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");\r
-                       if ($arr) {\r
-                               foreach($arr as $row) {\r
-                                       $sql = reset($row);\r
-                                       if (crc32($sql) == $partial) break;\r
-                               }\r
-                       }\r
-               }\r
-               $qno = rand();\r
-               $ok = $this->conn->Execute("EXPLAIN PLAN SET QUERYNO=$qno FOR $sql");\r
-               ob_start();\r
-               if (!$ok) echo "<p>Have EXPLAIN tables been created?</p>";\r
-               else {\r
-                       $rs = $this->conn->Execute("select * from explain_statement where queryno=$qno");\r
-                       if ($rs) rs2html($rs);\r
-               }\r
-               $s = ob_get_contents();\r
-               ob_end_clean();\r
-               $this->conn->LogSQL($save);\r
-               \r
-               $s .= $this->Tracer($sql);\r
-               return $s;\r
-       }\r
-       \r
-       \r
-       function Tables()\r
-       {\r
-               $rs = $this->conn->Execute("select tabschema,tabname,card as rows,\r
-                       npages pages_used,fpages pages_allocated, tbspace tablespace  \r
-                       from syscat.tables where tabschema not in ('SYSCAT','SYSIBM','SYSSTAT') order by 1,2");\r
-               return rs2html($rs,false,false,false,false);\r
-       }\r
-}\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+
+// Simple guide to configuring db2: so-so http://www.devx.com/gethelpon/10MinuteSolution/16575
+
+// SELECT * FROM TABLE(SNAPSHOT_APPL('SAMPLE', -1)) as t
+class perf_db2 extends adodb_perf{
+       var $createTableSQL = "CREATE TABLE adodb_logsql (
+                 created TIMESTAMP NOT NULL,
+                 sql0 varchar(250) NOT NULL,
+                 sql1 varchar(4000) NOT NULL,
+                 params varchar(3000) NOT NULL,
+                 tracer varchar(500) NOT NULL,
+                 timer decimal(16,6) NOT NULL
+               )";
+               
+       var $settings = array(
+       'Ratios',
+               'data cache hit ratio' => array('RATIO',
+                       "SELECT 
+                               case when sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)=0 then 0 
+                               else 100*(1-sum(POOL_DATA_P_READS+POOL_INDEX_P_READS)/sum(POOL_DATA_L_READS+POOL_INDEX_L_READS)) end 
+                               FROM TABLE(SNAPSHOT_APPL('',-2)) as t",
+                       '=WarnCacheRatio'),
+                       
+       'Data Cache',
+               'data cache buffers' => array('DATAC',
+               'select sum(npages) from SYSCAT.BUFFERPOOLS',
+                       'See <a href=http://www7b.boulder.ibm.com/dmdd/library/techarticle/anshum/0107anshum.html#bufferpoolsize>tuning reference</a>.' ),
+               'cache blocksize' => array('DATAC',
+               'select avg(pagesize) from SYSCAT.BUFFERPOOLS',
+                       '' ),
+               'data cache size' => array('DATAC',
+               'select sum(npages*pagesize) from SYSCAT.BUFFERPOOLS',
+                       '' ),
+       'Connections',
+               'current connections' => array('SESS',
+                       "SELECT count(*) FROM TABLE(SNAPSHOT_APPL_INFO('',-2)) as t",
+                       ''),
+
+               false
+       );
+
+
+       function perf_db2(&$conn)
+       {
+               $this->conn =& $conn;
+       }
+       
+       function Explain($sql,$partial=false)
+       {
+               $save = $this->conn->LogSQL(false);
+               if ($partial) {
+                       $sqlq = $this->conn->qstr($sql.'%');
+                       $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
+                       if ($arr) {
+                               foreach($arr as $row) {
+                                       $sql = reset($row);
+                                       if (crc32($sql) == $partial) break;
+                               }
+                       }
+               }
+               $qno = rand();
+               $ok = $this->conn->Execute("EXPLAIN PLAN SET QUERYNO=$qno FOR $sql");
+               ob_start();
+               if (!$ok) echo "<p>Have EXPLAIN tables been created?</p>";
+               else {
+                       $rs = $this->conn->Execute("select * from explain_statement where queryno=$qno");
+                       if ($rs) rs2html($rs);
+               }
+               $s = ob_get_contents();
+               ob_end_clean();
+               $this->conn->LogSQL($save);
+               
+               $s .= $this->Tracer($sql);
+               return $s;
+       }
+       
+       
+       function Tables()
+       {
+               $rs = $this->conn->Execute("select tabschema,tabname,card as rows,
+                       npages pages_used,fpages pages_allocated, tbspace tablespace  
+                       from syscat.tables where tabschema not in ('SYSCAT','SYSIBM','SYSSTAT') order by 1,2");
+               return rs2html($rs,false,false,false,false);
+       }
+}
 ?>
\ No newline at end of file
index 2b2923b86877a8a1d2256e2ca67284b45f372fd2..b6ac4492835826c1d7ffb1c503e80679827d1ffd 100644 (file)
@@ -1,67 +1,67 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. See License.txt. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Library for basic performance monitoring and tuning \r
-  \r
-*/\r
-\r
-//\r
-// Thx to  Fernando Ortiz, mailto:fortiz#lacorona.com.mx\r
-// With info taken from http://www.oninit.com/oninit/sysmaster/index.html\r
-//\r
-class perf_informix extends adodb_perf{\r
-\r
-       // Maximum size on varchar upto 9.30 255 chars\r
-       // better truncate varchar to 255 than char(4000) ?\r
-       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
-               created datetime year to second NOT NULL,\r
-               sql0 varchar(250) NOT NULL,\r
-               sql1 varchar(255) NOT NULL,\r
-               params varchar(255) NOT NULL,\r
-               tracer varchar(255) NOT NULL,\r
-               timer decimal(16,6) NOT NULL\r
-       )";\r
-       \r
-       var $tablesSQL = "select a.tabname tablename, ti_nptotal*2 size_in_k, ti_nextns extents, ti_nrows records from systables c, sysmaster:systabnames a, sysmaster:systabinfo b where c.tabname not matches 'sys*' and c.partnum = a.partnum and c.partnum = b.ti_partnum";\r
-       \r
-       var $settings = array(\r
-       'Ratios',\r
-               'data cache hit ratio' => array('RATIOH',\r
-               "select round((1-(wt.value / (rd.value + wr.value)))*100,2)\r
-               from sysmaster:sysprofile wr, sysmaster:sysprofile rd, sysmaster:sysprofile wt\r
-               where rd.name = 'pagreads' and\r
-               wr.name = 'pagwrites' and\r
-               wt.name = 'buffwts'",\r
-               '=WarnCacheRatio'),\r
-       'IO',\r
-               'data reads' => array('IO',\r
-               "select value from sysmaster:sysprofile where name='pagreads'",\r
-               'Page reads'),\r
-               \r
-               'data writes' => array('IO',\r
-               "select value from sysmaster:sysprofile where name='pagwrites'",\r
-               'Page writes'),\r
-       \r
-       'Connections',\r
-               'current connections' => array('SESS',\r
-               'select count(*) from sysmaster:syssessions',\r
-               'Number of sessions'),\r
-       \r
-       false\r
-       \r
-       );\r
-       \r
-       function perf_informix(&$conn)\r
-       {\r
-               $this->conn =& $conn;\r
-       }\r
-\r
-}\r
-?>\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+//
+// Thx to  Fernando Ortiz, mailto:fortiz#lacorona.com.mx
+// With info taken from http://www.oninit.com/oninit/sysmaster/index.html
+//
+class perf_informix extends adodb_perf{
+
+       // Maximum size on varchar upto 9.30 255 chars
+       // better truncate varchar to 255 than char(4000) ?
+       var $createTableSQL = "CREATE TABLE adodb_logsql (
+               created datetime year to second NOT NULL,
+               sql0 varchar(250) NOT NULL,
+               sql1 varchar(255) NOT NULL,
+               params varchar(255) NOT NULL,
+               tracer varchar(255) NOT NULL,
+               timer decimal(16,6) NOT NULL
+       )";
+       
+       var $tablesSQL = "select a.tabname tablename, ti_nptotal*2 size_in_k, ti_nextns extents, ti_nrows records from systables c, sysmaster:systabnames a, sysmaster:systabinfo b where c.tabname not matches 'sys*' and c.partnum = a.partnum and c.partnum = b.ti_partnum";
+       
+       var $settings = array(
+       'Ratios',
+               'data cache hit ratio' => array('RATIOH',
+               "select round((1-(wt.value / (rd.value + wr.value)))*100,2)
+               from sysmaster:sysprofile wr, sysmaster:sysprofile rd, sysmaster:sysprofile wt
+               where rd.name = 'pagreads' and
+               wr.name = 'pagwrites' and
+               wt.name = 'buffwts'",
+               '=WarnCacheRatio'),
+       'IO',
+               'data reads' => array('IO',
+               "select value from sysmaster:sysprofile where name='pagreads'",
+               'Page reads'),
+               
+               'data writes' => array('IO',
+               "select value from sysmaster:sysprofile where name='pagwrites'",
+               'Page writes'),
+       
+       'Connections',
+               'current connections' => array('SESS',
+               'select count(*) from sysmaster:syssessions',
+               'Number of sessions'),
+       
+       false
+       
+       );
+       
+       function perf_informix(&$conn)
+       {
+               $this->conn =& $conn;
+       }
+
+}
+?>
index 1cf7d6906a973e4d1a0e9804ff1245ffd84d6ab3..9ea5c497ef61b1ac5c3c21b7eac807862cb073f6 100644 (file)
-<?php\r
-\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. See License.txt. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Library for basic performance monitoring and tuning \r
-  \r
-*/\r
-\r
-/*\r
-       MSSQL has moved most performance info to Performance Monitor\r
-*/\r
-class perf_mssql extends adodb_perf{\r
-       var $sql1 = 'cast(sql1 as text)';\r
-       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
-                 created datetime NOT NULL,\r
-                 sql0 varchar(250) NOT NULL,\r
-                 sql1 varchar(4000) NOT NULL,\r
-                 params varchar(3000) NOT NULL,\r
-                 tracer varchar(500) NOT NULL,\r
-                 timer decimal(16,6) NOT NULL\r
-               )";\r
-               \r
-       var $settings = array(\r
-       'Ratios',\r
-               'data cache hit ratio' => array('RATIO',\r
-                       "select round((a.cntr_value*100.0)/b.cntr_value,2) from master.dbo.sysperfinfo a, master.dbo.sysperfinfo b where a.counter_name = 'Buffer cache hit ratio' and b.counter_name='Buffer cache hit ratio base'",\r
-                       '=WarnCacheRatio'),\r
-               'prepared sql hit ratio' => array('RATIO',\r
-                       array('dbcc cachestats','Prepared',1,100),\r
-                       ''),\r
-               'adhoc sql hit ratio' => array('RATIO',\r
-                       array('dbcc cachestats','Adhoc',1,100),\r
-                       ''),\r
-       'IO',\r
-               'data reads' => array('IO',\r
-               "select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page reads/sec'"),\r
-               'data writes' => array('IO',\r
-               "select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page writes/sec'"),\r
-                       \r
-       'Data Cache',\r
-               'data cache size' => array('DATAC',\r
-               "select cntr_value*8192 from master.dbo.sysperfinfo where counter_name = 'Total Pages' and object_name='SQLServer:Buffer Manager'",\r
-                       '' ),\r
-               'data cache blocksize' => array('DATAC',\r
-                       "select 8192",'page size'),\r
-       'Connections',\r
-               'current connections' => array('SESS',\r
-                       '=sp_who',\r
-                       ''),\r
-               'max connections' => array('SESS',\r
-                       "SELECT @@MAX_CONNECTIONS",\r
-                       ''),\r
-\r
-               false\r
-       );\r
-       \r
-       \r
-       function perf_mssql(&$conn)\r
-       {\r
-               if ($conn->dataProvider == 'odbc') {\r
-                       $this->sql1 = 'sql1';\r
-                       //$this->explain = false;\r
-               }\r
-               $this->conn =& $conn;\r
-       }\r
-       \r
-       function Explain($sql,$partial=false)\r
-       {\r
-               \r
-               $save = $this->conn->LogSQL(false);\r
-               if ($partial) {\r
-                       $sqlq = $this->conn->qstr($sql.'%');\r
-                       $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");\r
-                       if ($arr) {\r
-                               foreach($arr as $row) {\r
-                                       $sql = reset($row);\r
-                                       if (crc32($sql) == $partial) break;\r
-                               }\r
-                       }\r
-               }\r
-               \r
-               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';\r
-               $this->conn->Execute("SET SHOWPLAN_ALL ON;");\r
-               $sql = str_replace('?',"''",$sql);\r
-               global $ADODB_FETCH_MODE;\r
-               \r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $rs =& $this->conn->Execute($sql);\r
-               //adodb_printr($rs);\r
-               $ADODB_FETCH_MODE = $save;\r
-               if ($rs) {\r
-                       $rs->MoveNext();\r
-                       $s .= '<table bgcolor=white border=0 cellpadding="1" callspacing=0><tr><td nowrap align=center> Rows<td nowrap align=center> IO<td nowrap align=center> CPU<td align=left> &nbsp; &nbsp; Plan</tr>';\r
-                       while (!$rs->EOF) {\r
-                               $s .= '<tr><td>'.round($rs->fields[8],1).'<td>'.round($rs->fields[9],3).'<td align=right>'.round($rs->fields[10],3).'<td nowrap><pre>'.htmlspecialchars($rs->fields[0])."</td></pre></tr>\n"; ## NOTE CORRUPT </td></pre> tag is intentional!!!!\r
-                               $rs->MoveNext();\r
-                       }\r
-                       $s .= '</table>';\r
-                       \r
-                       $rs->NextRecordSet();\r
-               }\r
-               \r
-               $this->conn->Execute("SET SHOWPLAN_ALL OFF;");\r
-               $this->conn->LogSQL($save);\r
-               $s .= $this->Tracer($sql);\r
-               return $s;\r
-       }\r
-       \r
-       function Tables()\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-       \r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               //$this->conn->debug=1;\r
-               $s = '<table border=1 bgcolor=white><tr><td><b>tablename</b></td><td><b>size_in_k</b></td><td><b>index size</b></td><td><b>reserved size</b></td></tr>';\r
-               $rs1 = $this->conn->Execute("select distinct name from sysobjects where xtype='U'");\r
-               if ($rs1) {\r
-                       while (!$rs1->EOF) {\r
-                               $tab = $rs1->fields[0];\r
-                               $tabq = $this->conn->qstr($tab);\r
-                               $rs2 = $this->conn->Execute("sp_spaceused $tabq");\r
-                               if ($rs2) {\r
-                                       $s .= '<tr><td>'.$tab.'</td><td align=right>'.$rs2->fields[3].'</td><td align=right>'.$rs2->fields[4].'</td><td align=right>'.$rs2->fields[2].'</td></tr>';\r
-                                       $rs2->Close();\r
-                               }\r
-                               $rs1->MoveNext();\r
-                       }\r
-                       $rs1->Close();\r
-               }\r
-               $ADODB_FETCH_MODE = $save;\r
-               return $s.'</table>';\r
-       }\r
-       \r
-       function sp_who()\r
-       {\r
-               $arr = $this->conn->GetArray('sp_who');\r
-               return sizeof($arr);\r
-       }\r
-       \r
-       function HealthCheck($cli=false)\r
-       {\r
-               \r
-               $this->conn->Execute('dbcc traceon(3604)');\r
-               $html =  adodb_perf::HealthCheck($cli);\r
-               $this->conn->Execute('dbcc traceoff(3604)');\r
-               return $html;\r
-       }\r
-       \r
-       \r
-}\r
-\r
+<?php
+
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+/*
+       MSSQL has moved most performance info to Performance Monitor
+*/
+class perf_mssql extends adodb_perf{
+       var $sql1 = 'cast(sql1 as text)';
+       var $createTableSQL = "CREATE TABLE adodb_logsql (
+                 created datetime NOT NULL,
+                 sql0 varchar(250) NOT NULL,
+                 sql1 varchar(4000) NOT NULL,
+                 params varchar(3000) NOT NULL,
+                 tracer varchar(500) NOT NULL,
+                 timer decimal(16,6) NOT NULL
+               )";
+               
+       var $settings = array(
+       'Ratios',
+               'data cache hit ratio' => array('RATIO',
+                       "select round((a.cntr_value*100.0)/b.cntr_value,2) from master.dbo.sysperfinfo a, master.dbo.sysperfinfo b where a.counter_name = 'Buffer cache hit ratio' and b.counter_name='Buffer cache hit ratio base'",
+                       '=WarnCacheRatio'),
+               'prepared sql hit ratio' => array('RATIO',
+                       array('dbcc cachestats','Prepared',1,100),
+                       ''),
+               'adhoc sql hit ratio' => array('RATIO',
+                       array('dbcc cachestats','Adhoc',1,100),
+                       ''),
+       'IO',
+               'data reads' => array('IO',
+               "select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page reads/sec'"),
+               'data writes' => array('IO',
+               "select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page writes/sec'"),
+                       
+       'Data Cache',
+               'data cache size' => array('DATAC',
+               "select cntr_value*8192 from master.dbo.sysperfinfo where counter_name = 'Total Pages' and object_name='SQLServer:Buffer Manager'",
+                       '' ),
+               'data cache blocksize' => array('DATAC',
+                       "select 8192",'page size'),
+       'Connections',
+               'current connections' => array('SESS',
+                       '=sp_who',
+                       ''),
+               'max connections' => array('SESS',
+                       "SELECT @@MAX_CONNECTIONS",
+                       ''),
+
+               false
+       );
+       
+       
+       function perf_mssql(&$conn)
+       {
+               if ($conn->dataProvider == 'odbc') {
+                       $this->sql1 = 'sql1';
+                       //$this->explain = false;
+               }
+               $this->conn =& $conn;
+       }
+       
+       function Explain($sql,$partial=false)
+       {
+               
+               $save = $this->conn->LogSQL(false);
+               if ($partial) {
+                       $sqlq = $this->conn->qstr($sql.'%');
+                       $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
+                       if ($arr) {
+                               foreach($arr as $row) {
+                                       $sql = reset($row);
+                                       if (crc32($sql) == $partial) break;
+                               }
+                       }
+               }
+               
+               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
+               $this->conn->Execute("SET SHOWPLAN_ALL ON;");
+               $sql = str_replace('?',"''",$sql);
+               global $ADODB_FETCH_MODE;
+               
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $rs =& $this->conn->Execute($sql);
+               //adodb_printr($rs);
+               $ADODB_FETCH_MODE = $save;
+               if ($rs) {
+                       $rs->MoveNext();
+                       $s .= '<table bgcolor=white border=0 cellpadding="1" callspacing=0><tr><td nowrap align=center> Rows<td nowrap align=center> IO<td nowrap align=center> CPU<td align=left> &nbsp; &nbsp; Plan</tr>';
+                       while (!$rs->EOF) {
+                               $s .= '<tr><td>'.round($rs->fields[8],1).'<td>'.round($rs->fields[9],3).'<td align=right>'.round($rs->fields[10],3).'<td nowrap><pre>'.htmlspecialchars($rs->fields[0])."</td></pre></tr>\n"; ## NOTE CORRUPT </td></pre> tag is intentional!!!!
+                               $rs->MoveNext();
+                       }
+                       $s .= '</table>';
+                       
+                       $rs->NextRecordSet();
+               }
+               
+               $this->conn->Execute("SET SHOWPLAN_ALL OFF;");
+               $this->conn->LogSQL($save);
+               $s .= $this->Tracer($sql);
+               return $s;
+       }
+       
+       function Tables()
+       {
+       global $ADODB_FETCH_MODE;
+       
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               //$this->conn->debug=1;
+               $s = '<table border=1 bgcolor=white><tr><td><b>tablename</b></td><td><b>size_in_k</b></td><td><b>index size</b></td><td><b>reserved size</b></td></tr>';
+               $rs1 = $this->conn->Execute("select distinct name from sysobjects where xtype='U'");
+               if ($rs1) {
+                       while (!$rs1->EOF) {
+                               $tab = $rs1->fields[0];
+                               $tabq = $this->conn->qstr($tab);
+                               $rs2 = $this->conn->Execute("sp_spaceused $tabq");
+                               if ($rs2) {
+                                       $s .= '<tr><td>'.$tab.'</td><td align=right>'.$rs2->fields[3].'</td><td align=right>'.$rs2->fields[4].'</td><td align=right>'.$rs2->fields[2].'</td></tr>';
+                                       $rs2->Close();
+                               }
+                               $rs1->MoveNext();
+                       }
+                       $rs1->Close();
+               }
+               $ADODB_FETCH_MODE = $save;
+               return $s.'</table>';
+       }
+       
+       function sp_who()
+       {
+               $arr = $this->conn->GetArray('sp_who');
+               return sizeof($arr);
+       }
+       
+       function HealthCheck($cli=false)
+       {
+               
+               $this->conn->Execute('dbcc traceon(3604)');
+               $html =  adodb_perf::HealthCheck($cli);
+               $this->conn->Execute('dbcc traceoff(3604)');
+               return $html;
+       }
+       
+       
+}
+
 ?>
\ No newline at end of file
index bfa1883d4f1aed46a38178b1f372e151f40c452b..274bca9b30c42fa45353d781185f763e56acc0e8 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. See License.txt. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Library for basic performance monitoring and tuning \r
-  \r
-*/\r
-\r
-class perf_mysql extends adodb_perf{\r
-       \r
-       var $tablesSQL = 'show table status';\r
-       \r
-       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
-                 created datetime NOT NULL,\r
-                 sql0 varchar(250) NOT NULL,\r
-                 sql1 text NOT NULL,\r
-                 params text NOT NULL,\r
-                 tracer text NOT NULL,\r
-                 timer decimal(16,6) NOT NULL\r
-               )";\r
-               \r
-       var $settings = array(\r
-       'Ratios',\r
-               'MyISAM cache hit ratio' => array('RATIO',\r
-                       '=GetKeyHitRatio',\r
-                       '=WarnCacheRatio'),\r
-               'InnoDB cache hit ratio' => array('RATIO',\r
-                       '=GetInnoDBHitRatio',\r
-                       '=WarnCacheRatio'),\r
-               'data cache hit ratio' => array('HIDE', # only if called\r
-                       '=FindDBHitRatio',\r
-                       '=WarnCacheRatio'),\r
-               'sql cache hit ratio' => array('RATIO',\r
-                       '=GetQHitRatio',\r
-                       ''),\r
-       'IO',\r
-               'data reads' => array('IO',\r
-                       '=GetReads',\r
-                       'Number of selects (Key_reads is not accurate)'),\r
-               'data writes' => array('IO',\r
-                       '=GetWrites',\r
-                       'Number of inserts/updates/deletes * coef (Key_writes is not accurate)'),\r
-               \r
-       'Data Cache',\r
-               'MyISAM data cache size' => array('DATAC',\r
-                       array("show variables", 'key_buffer_size'),\r
-                       '' ),\r
-               'BDB data cache size' => array('DATAC',\r
-                       array("show variables", 'bdb_cache_size'),\r
-                       '' ),\r
-               'InnoDB data cache size' => array('DATAC',\r
-                       array("show variables", 'innodb_buffer_pool_size'),\r
-                       '' ),\r
-       'Memory Usage',\r
-               'read buffer size' => array('CACHE',\r
-                       array("show variables", 'read_buffer_size'),\r
-                       '(per session)'),\r
-               'sort buffer size' => array('CACHE',\r
-                       array("show variables", 'sort_buffer_size'),\r
-                       'Size of sort buffer (per session)' ),\r
-               'table cache' => array('CACHE',\r
-                       array("show variables", 'table_cache'),\r
-                       'Number of tables to keep open'),\r
-       'Connections',  \r
-               'current connections' => array('SESS',\r
-                       array('show status','Threads_connected'),\r
-                       ''),\r
-               'max connections' => array( 'SESS',\r
-                       array("show variables",'max_connections'),\r
-                       ''),\r
-       \r
-               false\r
-       );\r
-       \r
-       function perf_mysql(&$conn)\r
-       {\r
-               $this->conn =& $conn;\r
-       }\r
-       \r
-       function Explain($sql,$partial=false)\r
-       {\r
-               \r
-               if (strtoupper(substr(trim($sql),0,6)) !== 'SELECT') return '<p>Unable to EXPLAIN non-select statement</p>';\r
-               $save = $this->conn->LogSQL(false);\r
-               if ($partial) {\r
-                       $sqlq = $this->conn->qstr($sql.'%');\r
-                       $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");\r
-                       if ($arr) {\r
-                               foreach($arr as $row) {\r
-                                       $sql = reset($row);\r
-                                       if (crc32($sql) == $partial) break;\r
-                               }\r
-                       }\r
-               }\r
-               $sql = str_replace('?',"''",$sql);\r
-               \r
-               if ($partial) {\r
-                       $sqlq = $this->conn->qstr($sql.'%');\r
-                       $sql = $this->conn->GetOne("select sql1 from adodb_logsql where sql1 like $sqlq");\r
-               }\r
-               \r
-               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';\r
-               $rs = $this->conn->Execute('EXPLAIN '.$sql);\r
-               $s .= rs2html($rs,false,false,false,false);\r
-               $this->conn->LogSQL($save);\r
-               $s .= $this->Tracer($sql);\r
-               return $s;\r
-       }\r
-       \r
-       function Tables()\r
-       {\r
-               if (!$this->tablesSQL) return false;\r
-               \r
-               $rs = $this->conn->Execute($this->tablesSQL);\r
-               if (!$rs) return false;\r
-               \r
-               $html = rs2html($rs,false,false,false,false);\r
-               return $html;\r
-       }\r
-       \r
-       function GetReads()\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $rs = $this->conn->Execute('show status');\r
-               $ADODB_FETCH_MODE = $save;\r
-               \r
-               if (!$rs) return 0;\r
-               $val = 0;\r
-               while (!$rs->EOF) {\r
-                       switch($rs->fields[0]) {\r
-                       case 'Com_select': \r
-                               $val = $rs->fields[1];\r
-                               $rs->Close();\r
-                               return $val;\r
-                       }\r
-                       $rs->MoveNext();\r
-               } \r
-               \r
-               $rs->Close();\r
-               \r
-               return $val;\r
-       }\r
-       \r
-       function GetWrites()\r
-       {\r
-       global $ADODB_FETCH_MODE;\r
-               $save = $ADODB_FETCH_MODE;\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-               $rs = $this->conn->Execute('show status');\r
-               $ADODB_FETCH_MODE = $save;\r
-               \r
-               if (!$rs) return 0;\r
-               $val = 0.0;\r
-               while (!$rs->EOF) {\r
-                       switch($rs->fields[0]) {\r
-                       case 'Com_insert': \r
-                               $val += $rs->fields[1]; break;\r
-                       case 'Com_delete': \r
-                               $val += $rs->fields[1]; break;\r
-                       case 'Com_update': \r
-                               $val += $rs->fields[1]/2;\r
-                               $rs->Close();\r
-                               return $val;\r
-                       }\r
-                       $rs->MoveNext();\r
-               } \r
-               \r
-               $rs->Close();\r
-               \r
-               return $val;\r
-       }\r
-       \r
-       function FindDBHitRatio()\r
-       {\r
-               // first find out type of table\r
-               //$this->conn->debug=1;\r
-               $rs = $this->conn->Execute('show table status');\r
-               if (!$rs) return '';\r
-               $type = strtoupper($rs->fields[1]);\r
-               $rs->Close();\r
-               switch($type){\r
-               case 'MYISAM':\r
-               case 'ISAM':\r
-                       return $this->DBParameter('MyISAM cache hit ratio').' (MyISAM)';\r
-               case 'INNODB':\r
-                       return $this->DBParameter('InnoDB cache hit ratio').' (InnoDB)';\r
-               default:\r
-                       return $type.' not supported';\r
-               }\r
-               \r
-       }\r
-       \r
-       function GetQHitRatio()\r
-       {\r
-               //Total number of queries = Qcache_inserts + Qcache_hits + Qcache_not_cached\r
-               $hits = $this->_DBParameter(array("show status","Qcache_hits"));\r
-               $total = $this->_DBParameter(array("show status","Qcache_inserts"));\r
-               $total += $this->_DBParameter(array("show status","Qcache_not_cached"));\r
-               \r
-               $total += $hits;\r
-               if ($total) return ($hits*100)/$total;\r
-               return 0;\r
-       }\r
-       \r
-       /*\r
-               Use session variable to store Hit percentage, because MySQL\r
-               does not remember last value of SHOW INNODB STATUS hit ratio\r
-               \r
-               # 1st query to SHOW INNODB STATUS\r
-               0.00 reads/s, 0.00 creates/s, 0.00 writes/s\r
-               Buffer pool hit rate 1000 / 1000\r
-               \r
-               # 2nd query to SHOW INNODB STATUS\r
-               0.00 reads/s, 0.00 creates/s, 0.00 writes/s\r
-               No buffer pool activity since the last printout\r
-       */\r
-       function GetInnoDBHitRatio()\r
-       {\r
-       global $HTTP_SESSION_VARS;\r
-       \r
-               $rs = $this->conn->Execute('show innodb status');\r
-               if (!$rs || $rs->EOF) return 0;\r
-               $stat = $rs->fields[0];\r
-               $at = strpos($stat,'Buffer pool hit rate');\r
-               $stat = substr($stat,$at,200);\r
-               if (preg_match('!Buffer pool hit rate\s*([0-9]*) / ([0-9]*)!',$stat,$arr)) {\r
-                       $val = 100*$arr[1]/$arr[2];\r
-                       $HTTP_SESSION_VARS['INNODB_HIT_PCT'] = $val;\r
-                       return $val;\r
-               } else {\r
-                       if (isset($HTTP_SESSION_VARS['INNODB_HIT_PCT'])) return $HTTP_SESSION_VARS['INNODB_HIT_PCT'];\r
-                       return 0;\r
-               }\r
-               return 0;\r
-       }\r
-       \r
-       function GetKeyHitRatio()\r
-       {\r
-               $hits = $this->_DBParameter(array("show status","Key_read_requests"));\r
-               $reqs = $this->_DBParameter(array("show status","Key_reads"));\r
-               if ($reqs == 0) return 0;\r
-               \r
-               return ($hits/($reqs+$hits))*100;\r
-       }\r
-       \r
-}\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+class perf_mysql extends adodb_perf{
+       
+       var $tablesSQL = 'show table status';
+       
+       var $createTableSQL = "CREATE TABLE adodb_logsql (
+                 created datetime NOT NULL,
+                 sql0 varchar(250) NOT NULL,
+                 sql1 text NOT NULL,
+                 params text NOT NULL,
+                 tracer text NOT NULL,
+                 timer decimal(16,6) NOT NULL
+               )";
+               
+       var $settings = array(
+       'Ratios',
+               'MyISAM cache hit ratio' => array('RATIO',
+                       '=GetKeyHitRatio',
+                       '=WarnCacheRatio'),
+               'InnoDB cache hit ratio' => array('RATIO',
+                       '=GetInnoDBHitRatio',
+                       '=WarnCacheRatio'),
+               'data cache hit ratio' => array('HIDE', # only if called
+                       '=FindDBHitRatio',
+                       '=WarnCacheRatio'),
+               'sql cache hit ratio' => array('RATIO',
+                       '=GetQHitRatio',
+                       ''),
+       'IO',
+               'data reads' => array('IO',
+                       '=GetReads',
+                       'Number of selects (Key_reads is not accurate)'),
+               'data writes' => array('IO',
+                       '=GetWrites',
+                       'Number of inserts/updates/deletes * coef (Key_writes is not accurate)'),
+               
+       'Data Cache',
+               'MyISAM data cache size' => array('DATAC',
+                       array("show variables", 'key_buffer_size'),
+                       '' ),
+               'BDB data cache size' => array('DATAC',
+                       array("show variables", 'bdb_cache_size'),
+                       '' ),
+               'InnoDB data cache size' => array('DATAC',
+                       array("show variables", 'innodb_buffer_pool_size'),
+                       '' ),
+       'Memory Usage',
+               'read buffer size' => array('CACHE',
+                       array("show variables", 'read_buffer_size'),
+                       '(per session)'),
+               'sort buffer size' => array('CACHE',
+                       array("show variables", 'sort_buffer_size'),
+                       'Size of sort buffer (per session)' ),
+               'table cache' => array('CACHE',
+                       array("show variables", 'table_cache'),
+                       'Number of tables to keep open'),
+       'Connections',  
+               'current connections' => array('SESS',
+                       array('show status','Threads_connected'),
+                       ''),
+               'max connections' => array( 'SESS',
+                       array("show variables",'max_connections'),
+                       ''),
+       
+               false
+       );
+       
+       function perf_mysql(&$conn)
+       {
+               $this->conn =& $conn;
+       }
+       
+       function Explain($sql,$partial=false)
+       {
+               
+               if (strtoupper(substr(trim($sql),0,6)) !== 'SELECT') return '<p>Unable to EXPLAIN non-select statement</p>';
+               $save = $this->conn->LogSQL(false);
+               if ($partial) {
+                       $sqlq = $this->conn->qstr($sql.'%');
+                       $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq");
+                       if ($arr) {
+                               foreach($arr as $row) {
+                                       $sql = reset($row);
+                                       if (crc32($sql) == $partial) break;
+                               }
+                       }
+               }
+               $sql = str_replace('?',"''",$sql);
+               
+               if ($partial) {
+                       $sqlq = $this->conn->qstr($sql.'%');
+                       $sql = $this->conn->GetOne("select sql1 from adodb_logsql where sql1 like $sqlq");
+               }
+               
+               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
+               $rs = $this->conn->Execute('EXPLAIN '.$sql);
+               $s .= rs2html($rs,false,false,false,false);
+               $this->conn->LogSQL($save);
+               $s .= $this->Tracer($sql);
+               return $s;
+       }
+       
+       function Tables()
+       {
+               if (!$this->tablesSQL) return false;
+               
+               $rs = $this->conn->Execute($this->tablesSQL);
+               if (!$rs) return false;
+               
+               $html = rs2html($rs,false,false,false,false);
+               return $html;
+       }
+       
+       function GetReads()
+       {
+       global $ADODB_FETCH_MODE;
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $rs = $this->conn->Execute('show status');
+               $ADODB_FETCH_MODE = $save;
+               
+               if (!$rs) return 0;
+               $val = 0;
+               while (!$rs->EOF) {
+                       switch($rs->fields[0]) {
+                       case 'Com_select': 
+                               $val = $rs->fields[1];
+                               $rs->Close();
+                               return $val;
+                       }
+                       $rs->MoveNext();
+               } 
+               
+               $rs->Close();
+               
+               return $val;
+       }
+       
+       function GetWrites()
+       {
+       global $ADODB_FETCH_MODE;
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               $rs = $this->conn->Execute('show status');
+               $ADODB_FETCH_MODE = $save;
+               
+               if (!$rs) return 0;
+               $val = 0.0;
+               while (!$rs->EOF) {
+                       switch($rs->fields[0]) {
+                       case 'Com_insert': 
+                               $val += $rs->fields[1]; break;
+                       case 'Com_delete': 
+                               $val += $rs->fields[1]; break;
+                       case 'Com_update': 
+                               $val += $rs->fields[1]/2;
+                               $rs->Close();
+                               return $val;
+                       }
+                       $rs->MoveNext();
+               } 
+               
+               $rs->Close();
+               
+               return $val;
+       }
+       
+       function FindDBHitRatio()
+       {
+               // first find out type of table
+               //$this->conn->debug=1;
+               $rs = $this->conn->Execute('show table status');
+               if (!$rs) return '';
+               $type = strtoupper($rs->fields[1]);
+               $rs->Close();
+               switch($type){
+               case 'MYISAM':
+               case 'ISAM':
+                       return $this->DBParameter('MyISAM cache hit ratio').' (MyISAM)';
+               case 'INNODB':
+                       return $this->DBParameter('InnoDB cache hit ratio').' (InnoDB)';
+               default:
+                       return $type.' not supported';
+               }
+               
+       }
+       
+       function GetQHitRatio()
+       {
+               //Total number of queries = Qcache_inserts + Qcache_hits + Qcache_not_cached
+               $hits = $this->_DBParameter(array("show status","Qcache_hits"));
+               $total = $this->_DBParameter(array("show status","Qcache_inserts"));
+               $total += $this->_DBParameter(array("show status","Qcache_not_cached"));
+               
+               $total += $hits;
+               if ($total) return ($hits*100)/$total;
+               return 0;
+       }
+       
+       /*
+               Use session variable to store Hit percentage, because MySQL
+               does not remember last value of SHOW INNODB STATUS hit ratio
+               
+               # 1st query to SHOW INNODB STATUS
+               0.00 reads/s, 0.00 creates/s, 0.00 writes/s
+               Buffer pool hit rate 1000 / 1000
+               
+               # 2nd query to SHOW INNODB STATUS
+               0.00 reads/s, 0.00 creates/s, 0.00 writes/s
+               No buffer pool activity since the last printout
+       */
+       function GetInnoDBHitRatio()
+       {
+       global $HTTP_SESSION_VARS;
+       
+               $rs = $this->conn->Execute('show innodb status');
+               if (!$rs || $rs->EOF) return 0;
+               $stat = $rs->fields[0];
+               $rs->Close();
+               $at = strpos($stat,'Buffer pool hit rate');
+               $stat = substr($stat,$at,200);
+               if (preg_match('!Buffer pool hit rate\s*([0-9]*) / ([0-9]*)!',$stat,$arr)) {
+                       $val = 100*$arr[1]/$arr[2];
+                       $HTTP_SESSION_VARS['INNODB_HIT_PCT'] = $val;
+                       return $val;
+               } else {
+                       if (isset($HTTP_SESSION_VARS['INNODB_HIT_PCT'])) return $HTTP_SESSION_VARS['INNODB_HIT_PCT'];
+                       return 0;
+               }
+               return 0;
+       }
+       
+       function GetKeyHitRatio()
+       {
+               $hits = $this->_DBParameter(array("show status","Key_read_requests"));
+               $reqs = $this->_DBParameter(array("show status","Key_reads"));
+               if ($reqs == 0) return 0;
+               
+               return ($hits/($reqs+$hits))*100;
+       }
+       
+}
 ?>
\ No newline at end of file
index cc1151ea575cda83b7e55ee224355fff18e9c979..ba278e1182e0b385e90be2e22942ea9e269a33d7 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. See License.txt. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Library for basic performance monitoring and tuning \r
-  \r
-*/\r
-\r
-class perf_oci8 extends ADODB_perf{\r
-       \r
-       var $tablesSQL = "select segment_name as \"tablename\", sum(bytes)/1024 as \"size_in_k\",tablespace_name as \"tablespace\",count(*) \"extents\" from sys.user_extents \r
-          group by segment_name,tablespace_name";\r
-        \r
-       var $version;\r
-       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
-                 created date NOT NULL,\r
-                 sql0 varchar(250) NOT NULL,\r
-                 sql1 varchar(4000) NOT NULL,\r
-                 params varchar(4000),\r
-                 tracer varchar(4000),\r
-                 timer decimal(16,6) NOT NULL\r
-               )";\r
-       \r
-       var $settings = array(\r
-       'Ratios',\r
-               'data cache hit ratio' => array('RATIOH',\r
-                       "select round((1-(phy.value / (cur.value + con.value)))*100,2) \r
-                       from v\$sysstat cur, v\$sysstat con, v\$sysstat phy\r
-                       where cur.name = 'db block gets' and\r
-                             con.name = 'consistent gets' and\r
-                             phy.name = 'physical reads'",\r
-                       '=WarnCacheRatio'),\r
-               \r
-               'sql cache hit ratio' => array( 'RATIOH',\r
-                       'select round(100*(sum(pins)-sum(reloads))/sum(pins),2)  from v$librarycache',\r
-                       'increase <i>shared_pool_size</i> if too ratio low'),\r
-                       \r
-               'datadict cache hit ratio' => array('RATIOH',\r
-               "select      \r
-           round((1 - (sum(getmisses) / (sum(gets) +          \r
-                sum(getmisses))))*100,2)\r
-               from  v\$rowcache",\r
-               'increase <i>shared_pool_size</i> if too ratio low'),\r
-               \r
-               'memory sort ratio' => array('RATIOH',\r
-               "SELECT ROUND((100 * b.VALUE) /DECODE ((a.VALUE + b.VALUE), \r
-       0,1,(a.VALUE + b.VALUE)),2)\r
-FROM   v\$sysstat a, \r
-       v\$sysstat b\r
-WHERE  a.name = 'sorts (disk)'\r
-AND    b.name = 'sorts (memory)'",\r
-       "% of memory sorts compared to disk sorts - should be over 95%"),\r
-\r
-       'IO',\r
-               'data reads' => array('IO',\r
-               "select value from v\$sysstat where name='physical reads'"),\r
-       \r
-       'data writes' => array('IO',\r
-               "select value from v\$sysstat where name='physical writes'"),\r
-       \r
-       'Data Cache',\r
-               'data cache buffers' => array( 'DATAC',\r
-               "select a.value/b.value  from v\$parameter a, v\$parameter b \r
-                       where a.name = 'db_cache_size' and b.name= 'db_block_size'",\r
-                       'Number of cache buffers. Tune <i>db_cache_size</i> if the <i>data cache hit ratio</i> is too low.'),\r
-               'data cache blocksize' => array('DATAC',\r
-                       "select value from v\$parameter where name='db_block_size'",\r
-                       '' ),                   \r
-       'Memory Pools',\r
-               'data cache size' => array('DATAC',\r
-                       "select value from v\$parameter where name = 'db_cache_size'",\r
-                       'db_cache_size' ),\r
-               'shared pool size' => array('DATAC',\r
-                       "select value from v\$parameter where name = 'shared_pool_size'",\r
-                       'shared_pool_size, which holds shared cursors, stored procedures and similar shared structs' ),\r
-               'java pool size' => array('DATAJ',\r
-                       "select value from v\$parameter where name = 'java_pool_size'",\r
-                       'java_pool_size' ),\r
-               'large pool buffer size' => array('CACHE',\r
-                       "select value from v\$parameter where name='large_pool_size'",\r
-                       'this pool is for large mem allocations (not because it is larger than shared pool), for MTS sessions, parallel queries, io buffers (large_pool_size) ' ),\r
-\r
-               'pga buffer size' => array('CACHE',                     \r
-                       "select value from v\$parameter where name='pga_aggregate_target'",\r
-                       'program global area is private memory for sorting, and hash and bitmap merges - since oracle 9i (pga_aggregate_target)' ),\r
-\r
-               \r
-               'Connections',\r
-               'current connections' => array('SESS',\r
-                       'select count(*) from sys.v_$session where username is not null',\r
-                       ''),\r
-               'max connections' => array( 'SESS',\r
-                       "select value from v\$parameter where name='sessions'",\r
-                       ''),\r
-\r
-       'Memory Utilization',           \r
-               'data cache utilization ratio' => array('RATIOU',\r
-                       "select round((1-bytes/sgasize)*100, 2)\r
-                       from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f\r
-                       where name = 'free memory' and pool = 'shared pool'",\r
-               'Percentage of data cache actually in use - too low is bad, too high is worse'),\r
-               \r
-               'shared pool utilization ratio' => array('RATIOU',\r
-               'select round((sga.bytes/p.value)*100,2)\r
-               from v$sgastat sga, v$parameter p\r
-               where sga.name = \'free memory\' and sga.pool = \'shared pool\'\r
-               and p.name = \'shared_pool_size\'',\r
-               'Percentage of shared pool actually used - too low is bad, too high is worse'),\r
-               \r
-               'large pool utilization ratio' => array('RATIOU',\r
-                       "select round((1-bytes/sgasize)*100, 2)\r
-                       from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f\r
-                       where name = 'free memory' and pool = 'large pool'",\r
-               'Percentage of large_pool actually in use - too low is bad, too high is worse'),\r
-               'sort buffer size' => array('CACHE',\r
-                       "select value from v\$parameter where name='sort_area_size'",\r
-                       'sort_area_size (per query), uses memory in pga' ),\r
-\r
-               'pga usage at peak' => array('RATIOU',\r
-               '=PGA','Mb utilization at peak transactions (requires Oracle 9i+)'),\r
-       'Transactions',\r
-               'rollback segments' => array('ROLLBACK',\r
-                       "select count(*) from sys.v_\$rollstat",\r
-                       ''),\r
-       \r
-               'peak transactions' => array('ROLLBACK',\r
-                       "select max_utilization  tx_hwm\r
-               from sys.v_\$resource_limit\r
-               where resource_name = 'transactions'",\r
-                       'Taken from high-water-mark'),\r
-               'max transactions' => array('ROLLBACK',\r
-                       "select value from v\$parameter where name = 'transactions'",\r
-                       'max transactions / rollback segments < 3.5 (or transactions_per_rollback_segment)'),\r
-       'Parameters',   \r
-               'cursor sharing' => array('CURSOR',\r
-                       "select value from v\$parameter where name = 'cursor_sharing'",\r
-                       'Cursor reuse strategy. Recommended is FORCE (8i+) or SIMILAR (9i+). See <a href=http://www.praetoriate.com/oracle_tips_cursor_sharing.htm>cursor_sharing</a>.'),\r
-                       \r
-               'index cache cost' => array('COST',\r
-                       "select value from v\$parameter where name = 'optimizer_index_caching'",\r
-                       '% of indexed data blocks expected in the cache.\r
-                       Recommended is 20-80. Default is 0. See <a href=http://www.dba-oracle.com/oracle_tips_cbo_part1.htm>optimizer_index_caching</a>.'),\r
-               \r
-               'random page cost' => array('COST',\r
-                       "select value from v\$parameter where name = 'optimizer_index_cost_adj'",\r
-                       'Recommended is 10-50 for TP, and 50 for data warehouses. Default is 100. See <a href=http://www.dba-oracle.com/oracle_tips_cost_adj.htm>optimizer_index_cost_adj</a>. '),              \r
-               \r
-               false\r
-               \r
-       );\r
-       \r
-       \r
-       function perf_oci8(&$conn)\r
-       {\r
-               $savelog = $conn->LogSQL(false);        \r
-               $this->version = $conn->ServerInfo();\r
-               $conn->LogSQL($savelog);        \r
-               $this->conn =& $conn;\r
-       }\r
-       \r
-       \r
-       function PGA()\r
-       {\r
-               if ($this->version['version'] < 9) return 'Oracle 9i or later required';\r
-               \r
-               $rs = $this->conn->Execute("select a.mb,a.targ as pga_size_pct,a.pct from \r
-          (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb,\r
-                  pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r \r
-                  from v\$pga_target_advice) a left join\r
-          (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb,\r
-                  pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r \r
-                  from v\$pga_target_advice) b on \r
-         a.r = b.r+1 where \r
-               b.pct < 100");\r
-               if (!$rs) return "Only in 9i or later";\r
-               $rs->Close();\r
-               if ($rs->EOF) return "PGA could be too big";\r
-               \r
-               return reset($rs->fields);\r
-       }\r
-       \r
-       function Explain($sql,$partial=false) \r
-       {\r
-               $savelog = $this->conn->LogSQL(false);\r
-               $rs =& $this->conn->SelectLimit("select ID FROM PLAN_TABLE");\r
-               if (!$rs) {\r
-                       echo "<p><b>Missing PLAN_TABLE</b></p>\r
-<pre>\r
-CREATE TABLE PLAN_TABLE (\r
-  STATEMENT_ID                    VARCHAR2(30),\r
-  TIMESTAMP                       DATE,\r
-  REMARKS                         VARCHAR2(80),\r
-  OPERATION                       VARCHAR2(30),\r
-  OPTIONS                         VARCHAR2(30),\r
-  OBJECT_NODE                     VARCHAR2(128),\r
-  OBJECT_OWNER                    VARCHAR2(30),\r
-  OBJECT_NAME                     VARCHAR2(30),\r
-  OBJECT_INSTANCE                 NUMBER(38),\r
-  OBJECT_TYPE                     VARCHAR2(30),\r
-  OPTIMIZER                       VARCHAR2(255),\r
-  SEARCH_COLUMNS                  NUMBER,\r
-  ID                              NUMBER(38),\r
-  PARENT_ID                       NUMBER(38),\r
-  POSITION                        NUMBER(38),\r
-  COST                            NUMBER(38),\r
-  CARDINALITY                     NUMBER(38),\r
-  BYTES                           NUMBER(38),\r
-  OTHER_TAG                       VARCHAR2(255),\r
-  PARTITION_START                 VARCHAR2(255),\r
-  PARTITION_STOP                  VARCHAR2(255),\r
-  PARTITION_ID                    NUMBER(38),\r
-  OTHER                           LONG,\r
-  DISTRIBUTION                    VARCHAR2(30)\r
-);\r
-</pre>";\r
-                       return false;\r
-               }\r
-               \r
-               $rs->Close();\r
-       //      $this->conn->debug=1;\r
-       \r
-               if ($partial) {\r
-                       $sqlq = $this->conn->qstr($sql.'%');\r
-                       $arr = $this->conn->GetArray("select distinct distinct sql1 from adodb_logsql where sql1 like $sqlq");\r
-                       if ($arr) {\r
-                               foreach($arr as $row) {\r
-                                       $sql = reset($row);\r
-                                       if (crc32($sql) == $partial) break;\r
-                               }\r
-                       }\r
-               }\r
-               \r
-               $s = "<p><b>Explain</b>: ".htmlspecialchars($sql)."</p>";       \r
-               \r
-               $this->conn->BeginTrans();\r
-               $id = "ADODB ".microtime();\r
-               $rs =& $this->conn->Execute("EXPLAIN PLAN SET STATEMENT_ID='$id' FOR $sql");\r
-               $m = $this->conn->ErrorMsg();\r
-               if ($m) {\r
-                       $this->conn->RollbackTrans();\r
-                       $this->conn->LogSQL($savelog);\r
-                       $s .= "<p>$m</p>";\r
-                       return $s;\r
-               }\r
-               $rs = $this->conn->Execute("\r
-               select \r
-  '<pre>'||lpad('--', (level-1)*2,'-') || trim(operation) || ' ' || trim(options)||'</pre>'  as Operation, \r
-  object_name,COST,CARDINALITY,bytes\r
-               FROM plan_table \r
-START WITH id = 0  and STATEMENT_ID='$id'  \r
-CONNECT BY prior id=parent_id and statement_id='$id'");\r
-               \r
-               $s .= rs2html($rs,false,false,false,false);\r
-               $this->conn->RollbackTrans();\r
-               $this->conn->LogSQL($savelog);\r
-               $s .= $this->Tracer($sql,$partial);\r
-               return $s;\r
-       }\r
-       \r
-       \r
-       function CheckMemory()\r
-       {\r
-               if ($this->version['version'] < 9) return 'Oracle 9i or later required';\r
-               \r
-                $rs =& $this->conn->Execute("\r
-select  a.size_for_estimate as cache_mb_estimate,\r
-       case when a.size_factor=1 then \r
-               '&lt;&lt;= current'\r
-        when a.estd_physical_read_factor-b.estd_physical_read_factor > 0 and a.estd_physical_read_factor<1 then\r
-               '- BETTER - '\r
-       else ' ' end as currsize, \r
-   a.estd_physical_read_factor-b.estd_physical_read_factor as best_when_0\r
-   from (select size_for_estimate,size_factor,estd_physical_read_factor,rownum  r from v\$db_cache_advice) a , \r
-   (select size_for_estimate,size_factor,estd_physical_read_factor,rownum r from v\$db_cache_advice) b where a.r = b.r-1");\r
-               if (!$rs) return false;\r
-               \r
-               /*\r
-               The v$db_cache_advice utility show the marginal changes in physical data block reads for different sizes of db_cache_size\r
-               */\r
-               $s = "<h3>Data Cache Estimate</h3>";\r
-               if ($rs->EOF) {\r
-                       $s .= "<p>Cache that is 50% of current size is still too big</p>";\r
-               } else {\r
-                       $s .= "Ideal size of Data Cache is when \"best_when_0\" changes from a positive number and becomes zero.";\r
-                       $s .= rs2html($rs,false,false,false,false);\r
-               }\r
-               return $s;\r
-       }\r
-       \r
-       /*\r
-               Generate html for suspicious/expensive sql\r
-       */\r
-       function tohtml(&$rs,$type)\r
-       {\r
-               $o1 = $rs->FetchField(0);\r
-               $o2 = $rs->FetchField(1);\r
-               $o3 = $rs->FetchField(2);\r
-               if ($rs->EOF) return '<p>None found</p>';\r
-               $check = '';\r
-               $sql = '';\r
-               $s = "\n\n<table border=1 bgcolor=white><tr><td><b>".$o1->name.'</b></td><td><b>'.$o2->name.'</b></td><td><b>'.$o3->name.'</b></td></tr>';\r
-               while (!$rs->EOF) {\r
-                       if ($check != $rs->fields[0].'::'.$rs->fields[1]) {\r
-                               if ($check) {\r
-                                       $carr = explode('::',$check);\r
-                                       $prefix = "<a href=\"?$type=1&sql=".rawurlencode($sql).'&x#explain">';\r
-                                       $suffix = '</a>';\r
-                                       if (strlen($prefix)>2000) {\r
-                                               $prefix = '';\r
-                                               $suffix = '';\r
-                                       }\r
-                                       \r
-                                       $s .=  "\n<tr><td align=right>".$carr[0].'</td><td align=right>'.$carr[1].'</td><td>'.$prefix.$sql.$suffix.'</td></tr>';\r
-                               }\r
-                               $sql = $rs->fields[2];\r
-                               $check = $rs->fields[0].'::'.$rs->fields[1];                    \r
-                       } else\r
-                               $sql .= $rs->fields[2];\r
-                       \r
-                       $rs->MoveNext();\r
-               }\r
-               $rs->Close();\r
-               \r
-               $carr = explode('::',$check);\r
-               $prefix = "<a target=".rand()." href=\"?&hidem=1&$type=1&sql=".rawurlencode($sql).'&x#explain">';\r
-               $suffix = '</a>';\r
-               if (strlen($prefix)>2000) {\r
-                       $prefix = '';\r
-                       $suffix = '';\r
-               }\r
-               $s .=  "\n<tr><td align=right>".$carr[0].'</td><td align=right>'.$carr[1].'</td><td>'.$prefix.$sql.$suffix.'</td></tr>';\r
-                                       \r
-               return $s."</table>\n\n";\r
-       }\r
-       \r
-       // code thanks to Ixora. \r
-       // http://www.ixora.com.au/scripts/query_opt.htm\r
-       // requires oracle 8.1.7 or later\r
-       function SuspiciousSQL($numsql=10)\r
-       {\r
-               $sql = "\r
-select\r
-  substr(to_char(s.pct, '99.00'), 2) || '%'  load,\r
-  s.executions  executes,\r
-  p.sql_text\r
-from\r
-  ( \r
-    select\r
-      address,\r
-      buffer_gets,\r
-      executions,\r
-      pct,\r
-      rank() over (order by buffer_gets desc)  ranking\r
-    from\r
-      ( \r
-       select\r
-         address,\r
-         buffer_gets,\r
-         executions,\r
-         100 * ratio_to_report(buffer_gets) over ()  pct\r
-       from\r
-         sys.v_\$sql\r
-       where\r
-         command_type != 47 and module != 'T.O.A.D.'\r
-      )\r
-    where\r
-      buffer_gets > 50 * executions\r
-  )  s,\r
-  sys.v_\$sqltext  p\r
-where\r
-  s.ranking <= $numsql and\r
-  p.address = s.address\r
-order by\r
-  1 desc, s.address, p.piece";\r
-\r
-               global $ADODB_CACHE_MODE,$HTTP_GET_VARS;\r
-               if (isset($HTTP_GET_VARS['expsixora']) && isset($HTTP_GET_VARS['sql'])) {\r
-                               $partial = empty($HTTP_GET_VARS['part']);\r
-                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";\r
-               }\r
-\r
-               if (isset($HTTP_GET_VARS['sql'])) return $this->_SuspiciousSQL();\r
-               \r
-               $save = $ADODB_CACHE_MODE;\r
-               $ADODB_CACHE_MODE = ADODB_FETCH_NUM;\r
-               $savelog = $this->conn->LogSQL(false);\r
-               $rs =& $this->conn->SelectLimit($sql);\r
-               $this->conn->LogSQL($savelog);\r
-               $ADODB_CACHE_MODE = $save;\r
-               if ($rs) {\r
-                       $s = "\n<h3>Ixora Suspicious SQL</h3>";\r
-                       $s .= $this->tohtml($rs,'expsixora');\r
-               } else \r
-                       $s = '';\r
-               \r
-               if ($s) $s .= '<p>';\r
-               $s .= $this->_SuspiciousSQL();\r
-               return $s;\r
-       }\r
-       \r
-       // code thanks to Ixora. \r
-       // http://www.ixora.com.au/scripts/query_opt.htm\r
-       // requires oracle 8.1.7 or later\r
-       function ExpensiveSQL($numsql = 10)\r
-       {\r
-               $sql = "\r
-select\r
-  substr(to_char(s.pct, '99.00'), 2) || '%'  load,\r
-  s.executions  executes,\r
-  p.sql_text\r
-from\r
-  ( \r
-    select\r
-      address,\r
-      disk_reads,\r
-      executions,\r
-      pct,\r
-      rank() over (order by disk_reads desc)  ranking\r
-    from\r
-      (\r
-       select\r
-         address,\r
-         disk_reads,\r
-         executions,\r
-         100 * ratio_to_report(disk_reads) over ()  pct\r
-       from\r
-         sys.v_\$sql\r
-       where\r
-         command_type != 47 and module != 'T.O.A.D.'\r
-      )\r
-    where\r
-      disk_reads > 50 * executions\r
-  )  s,\r
-  sys.v_\$sqltext  p\r
-where\r
-  s.ranking <= $numsql and\r
-  p.address = s.address\r
-order by\r
-  1 desc, s.address, p.piece\r
-";\r
-               global $ADODB_CACHE_MODE,$HTTP_GET_VARS;\r
-               if (isset($HTTP_GET_VARS['expeixora']) && isset($HTTP_GET_VARS['sql'])) {\r
-                       $partial = empty($HTTP_GET_VARS['part']);       \r
-                       echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";\r
-               }\r
-               \r
-               if (isset($HTTP_GET_VARS['sql'])) {\r
-                        $var =& $this->_ExpensiveSQL();\r
-                        return $var;\r
-               }\r
-               $save = $ADODB_CACHE_MODE;\r
-               $ADODB_CACHE_MODE = ADODB_FETCH_NUM;\r
-               $savelog = $this->conn->LogSQL(false);\r
-               $rs =& $this->conn->Execute($sql);\r
-               $this->conn->LogSQL($savelog);\r
-               $ADODB_CACHE_MODE = $save;\r
-               if ($rs) {\r
-                       $s = "\n<h3>Ixora Expensive SQL</h3>";\r
-                       $s .= $this->tohtml($rs,'expeixora');\r
-               } else \r
-                       $s = '';\r
-               \r
-               \r
-               if ($s) $s .= '<p>';\r
-               $s .= $this->_ExpensiveSQL();\r
-               return $s;\r
-       }\r
-       \r
-}\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+class perf_oci8 extends ADODB_perf{
+       
+       var $tablesSQL = "select segment_name as \"tablename\", sum(bytes)/1024 as \"size_in_k\",tablespace_name as \"tablespace\",count(*) \"extents\" from sys.user_extents 
+          group by segment_name,tablespace_name";
+        
+       var $version;
+       var $createTableSQL = "CREATE TABLE adodb_logsql (
+                 created date NOT NULL,
+                 sql0 varchar(250) NOT NULL,
+                 sql1 varchar(4000) NOT NULL,
+                 params varchar(4000),
+                 tracer varchar(4000),
+                 timer decimal(16,6) NOT NULL
+               )";
+       
+       var $settings = array(
+       'Ratios',
+               'data cache hit ratio' => array('RATIOH',
+                       "select round((1-(phy.value / (cur.value + con.value)))*100,2) 
+                       from v\$sysstat cur, v\$sysstat con, v\$sysstat phy
+                       where cur.name = 'db block gets' and
+                             con.name = 'consistent gets' and
+                             phy.name = 'physical reads'",
+                       '=WarnCacheRatio'),
+               
+               'sql cache hit ratio' => array( 'RATIOH',
+                       'select round(100*(sum(pins)-sum(reloads))/sum(pins),2)  from v$librarycache',
+                       'increase <i>shared_pool_size</i> if too ratio low'),
+                       
+               'datadict cache hit ratio' => array('RATIOH',
+               "select      
+           round((1 - (sum(getmisses) / (sum(gets) +          
+                sum(getmisses))))*100,2)
+               from  v\$rowcache",
+               'increase <i>shared_pool_size</i> if too ratio low'),
+               
+               'memory sort ratio' => array('RATIOH',
+               "SELECT ROUND((100 * b.VALUE) /DECODE ((a.VALUE + b.VALUE), 
+       0,1,(a.VALUE + b.VALUE)),2)
+FROM   v\$sysstat a, 
+       v\$sysstat b
+WHERE  a.name = 'sorts (disk)'
+AND    b.name = 'sorts (memory)'",
+       "% of memory sorts compared to disk sorts - should be over 95%"),
+
+       'IO',
+               'data reads' => array('IO',
+               "select value from v\$sysstat where name='physical reads'"),
+       
+       'data writes' => array('IO',
+               "select value from v\$sysstat where name='physical writes'"),
+       
+       'Data Cache',
+               'data cache buffers' => array( 'DATAC',
+               "select a.value/b.value  from v\$parameter a, v\$parameter b 
+                       where a.name = 'db_cache_size' and b.name= 'db_block_size'",
+                       'Number of cache buffers. Tune <i>db_cache_size</i> if the <i>data cache hit ratio</i> is too low.'),
+               'data cache blocksize' => array('DATAC',
+                       "select value from v\$parameter where name='db_block_size'",
+                       '' ),                   
+       'Memory Pools',
+               'data cache size' => array('DATAC',
+                       "select value from v\$parameter where name = 'db_cache_size'",
+                       'db_cache_size' ),
+               'shared pool size' => array('DATAC',
+                       "select value from v\$parameter where name = 'shared_pool_size'",
+                       'shared_pool_size, which holds shared cursors, stored procedures and similar shared structs' ),
+               'java pool size' => array('DATAJ',
+                       "select value from v\$parameter where name = 'java_pool_size'",
+                       'java_pool_size' ),
+               'large pool buffer size' => array('CACHE',
+                       "select value from v\$parameter where name='large_pool_size'",
+                       'this pool is for large mem allocations (not because it is larger than shared pool), for MTS sessions, parallel queries, io buffers (large_pool_size) ' ),
+
+               'pga buffer size' => array('CACHE',                     
+                       "select value from v\$parameter where name='pga_aggregate_target'",
+                       'program global area is private memory for sorting, and hash and bitmap merges - since oracle 9i (pga_aggregate_target)' ),
+
+               
+               'Connections',
+               'current connections' => array('SESS',
+                       'select count(*) from sys.v_$session where username is not null',
+                       ''),
+               'max connections' => array( 'SESS',
+                       "select value from v\$parameter where name='sessions'",
+                       ''),
+
+       'Memory Utilization',           
+               'data cache utilization ratio' => array('RATIOU',
+                       "select round((1-bytes/sgasize)*100, 2)
+                       from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f
+                       where name = 'free memory' and pool = 'shared pool'",
+               'Percentage of data cache actually in use - too low is bad, too high is worse'),
+               
+               'shared pool utilization ratio' => array('RATIOU',
+               'select round((sga.bytes/p.value)*100,2)
+               from v$sgastat sga, v$parameter p
+               where sga.name = \'free memory\' and sga.pool = \'shared pool\'
+               and p.name = \'shared_pool_size\'',
+               'Percentage of shared pool actually used - too low is bad, too high is worse'),
+               
+               'large pool utilization ratio' => array('RATIOU',
+                       "select round((1-bytes/sgasize)*100, 2)
+                       from (select sum(bytes) sgasize from sys.v_\$sgastat) s, sys.v_\$sgastat f
+                       where name = 'free memory' and pool = 'large pool'",
+               'Percentage of large_pool actually in use - too low is bad, too high is worse'),
+               'sort buffer size' => array('CACHE',
+                       "select value from v\$parameter where name='sort_area_size'",
+                       'sort_area_size (per query), uses memory in pga' ),
+
+               'pga usage at peak' => array('RATIOU',
+               '=PGA','Mb utilization at peak transactions (requires Oracle 9i+)'),
+       'Transactions',
+               'rollback segments' => array('ROLLBACK',
+                       "select count(*) from sys.v_\$rollstat",
+                       ''),
+       
+               'peak transactions' => array('ROLLBACK',
+                       "select max_utilization  tx_hwm
+               from sys.v_\$resource_limit
+               where resource_name = 'transactions'",
+                       'Taken from high-water-mark'),
+               'max transactions' => array('ROLLBACK',
+                       "select value from v\$parameter where name = 'transactions'",
+                       'max transactions / rollback segments < 3.5 (or transactions_per_rollback_segment)'),
+       'Parameters',   
+               'cursor sharing' => array('CURSOR',
+                       "select value from v\$parameter where name = 'cursor_sharing'",
+                       'Cursor reuse strategy. Recommended is FORCE (8i+) or SIMILAR (9i+). See <a href=http://www.praetoriate.com/oracle_tips_cursor_sharing.htm>cursor_sharing</a>.'),
+                       
+               'index cache cost' => array('COST',
+                       "select value from v\$parameter where name = 'optimizer_index_caching'",
+                       '% of indexed data blocks expected in the cache.
+                       Recommended is 20-80. Default is 0. See <a href=http://www.dba-oracle.com/oracle_tips_cbo_part1.htm>optimizer_index_caching</a>.'),
+               
+               'random page cost' => array('COST',
+                       "select value from v\$parameter where name = 'optimizer_index_cost_adj'",
+                       'Recommended is 10-50 for TP, and 50 for data warehouses. Default is 100. See <a href=http://www.dba-oracle.com/oracle_tips_cost_adj.htm>optimizer_index_cost_adj</a>. '),              
+               
+               false
+               
+       );
+       
+       
+       function perf_oci8(&$conn)
+       {
+               $savelog = $conn->LogSQL(false);        
+               $this->version = $conn->ServerInfo();
+               $conn->LogSQL($savelog);        
+               $this->conn =& $conn;
+       }
+       
+       
+       function PGA()
+       {
+               if ($this->version['version'] < 9) return 'Oracle 9i or later required';
+               
+               $rs = $this->conn->Execute("select a.mb,a.targ as pga_size_pct,a.pct from 
+          (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb,
+                  pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r 
+                  from v\$pga_target_advice) a left join
+          (select round(pga_target_for_estimate/1024.0/1024.0,0) Mb,
+                  pga_target_factor targ,estd_pga_cache_hit_percentage pct,rownum as r 
+                  from v\$pga_target_advice) b on 
+         a.r = b.r+1 where 
+               b.pct < 100");
+               if (!$rs) return "Only in 9i or later";
+               $rs->Close();
+               if ($rs->EOF) return "PGA could be too big";
+               
+               return reset($rs->fields);
+       }
+       
+       function Explain($sql,$partial=false) 
+       {
+               $savelog = $this->conn->LogSQL(false);
+               $rs =& $this->conn->SelectLimit("select ID FROM PLAN_TABLE");
+               if (!$rs) {
+                       echo "<p><b>Missing PLAN_TABLE</b></p>
+<pre>
+CREATE TABLE PLAN_TABLE (
+  STATEMENT_ID                    VARCHAR2(30),
+  TIMESTAMP                       DATE,
+  REMARKS                         VARCHAR2(80),
+  OPERATION                       VARCHAR2(30),
+  OPTIONS                         VARCHAR2(30),
+  OBJECT_NODE                     VARCHAR2(128),
+  OBJECT_OWNER                    VARCHAR2(30),
+  OBJECT_NAME                     VARCHAR2(30),
+  OBJECT_INSTANCE                 NUMBER(38),
+  OBJECT_TYPE                     VARCHAR2(30),
+  OPTIMIZER                       VARCHAR2(255),
+  SEARCH_COLUMNS                  NUMBER,
+  ID                              NUMBER(38),
+  PARENT_ID                       NUMBER(38),
+  POSITION                        NUMBER(38),
+  COST                            NUMBER(38),
+  CARDINALITY                     NUMBER(38),
+  BYTES                           NUMBER(38),
+  OTHER_TAG                       VARCHAR2(255),
+  PARTITION_START                 VARCHAR2(255),
+  PARTITION_STOP                  VARCHAR2(255),
+  PARTITION_ID                    NUMBER(38),
+  OTHER                           LONG,
+  DISTRIBUTION                    VARCHAR2(30)
+);
+</pre>";
+                       return false;
+               }
+               
+               $rs->Close();
+       //      $this->conn->debug=1;
+       
+               if ($partial) {
+                       $sqlq = $this->conn->qstr($sql.'%');
+                       $arr = $this->conn->GetArray("select distinct distinct sql1 from adodb_logsql where sql1 like $sqlq");
+                       if ($arr) {
+                               foreach($arr as $row) {
+                                       $sql = reset($row);
+                                       if (crc32($sql) == $partial) break;
+                               }
+                       }
+               }
+               
+               $s = "<p><b>Explain</b>: ".htmlspecialchars($sql)."</p>";       
+               
+               $this->conn->BeginTrans();
+               $id = "ADODB ".microtime();
+               $rs =& $this->conn->Execute("EXPLAIN PLAN SET STATEMENT_ID='$id' FOR $sql");
+               $m = $this->conn->ErrorMsg();
+               if ($m) {
+                       $this->conn->RollbackTrans();
+                       $this->conn->LogSQL($savelog);
+                       $s .= "<p>$m</p>";
+                       return $s;
+               }
+               $rs = $this->conn->Execute("
+               select 
+  '<pre>'||lpad('--', (level-1)*2,'-') || trim(operation) || ' ' || trim(options)||'</pre>'  as Operation, 
+  object_name,COST,CARDINALITY,bytes
+               FROM plan_table 
+START WITH id = 0  and STATEMENT_ID='$id'  
+CONNECT BY prior id=parent_id and statement_id='$id'");
+               
+               $s .= rs2html($rs,false,false,false,false);
+               $this->conn->RollbackTrans();
+               $this->conn->LogSQL($savelog);
+               $s .= $this->Tracer($sql,$partial);
+               return $s;
+       }
+       
+       
+       function CheckMemory()
+       {
+               if ($this->version['version'] < 9) return 'Oracle 9i or later required';
+               
+                $rs =& $this->conn->Execute("
+select  a.size_for_estimate as cache_mb_estimate,
+       case when a.size_factor=1 then 
+               '&lt;&lt;= current'
+        when a.estd_physical_read_factor-b.estd_physical_read_factor > 0 and a.estd_physical_read_factor<1 then
+               '- BETTER - '
+       else ' ' end as currsize, 
+   a.estd_physical_read_factor-b.estd_physical_read_factor as best_when_0
+   from (select size_for_estimate,size_factor,estd_physical_read_factor,rownum  r from v\$db_cache_advice) a , 
+   (select size_for_estimate,size_factor,estd_physical_read_factor,rownum r from v\$db_cache_advice) b where a.r = b.r-1");
+               if (!$rs) return false;
+               
+               /*
+               The v$db_cache_advice utility show the marginal changes in physical data block reads for different sizes of db_cache_size
+               */
+               $s = "<h3>Data Cache Estimate</h3>";
+               if ($rs->EOF) {
+                       $s .= "<p>Cache that is 50% of current size is still too big</p>";
+               } else {
+                       $s .= "Ideal size of Data Cache is when \"best_when_0\" changes from a positive number and becomes zero.";
+                       $s .= rs2html($rs,false,false,false,false);
+               }
+               return $s;
+       }
+       
+       /*
+               Generate html for suspicious/expensive sql
+       */
+       function tohtml(&$rs,$type)
+       {
+               $o1 = $rs->FetchField(0);
+               $o2 = $rs->FetchField(1);
+               $o3 = $rs->FetchField(2);
+               if ($rs->EOF) return '<p>None found</p>';
+               $check = '';
+               $sql = '';
+               $s = "\n\n<table border=1 bgcolor=white><tr><td><b>".$o1->name.'</b></td><td><b>'.$o2->name.'</b></td><td><b>'.$o3->name.'</b></td></tr>';
+               while (!$rs->EOF) {
+                       if ($check != $rs->fields[0].'::'.$rs->fields[1]) {
+                               if ($check) {
+                                       $carr = explode('::',$check);
+                                       $prefix = "<a href=\"?$type=1&sql=".rawurlencode($sql).'&x#explain">';
+                                       $suffix = '</a>';
+                                       if (strlen($prefix)>2000) {
+                                               $prefix = '';
+                                               $suffix = '';
+                                       }
+                                       
+                                       $s .=  "\n<tr><td align=right>".$carr[0].'</td><td align=right>'.$carr[1].'</td><td>'.$prefix.$sql.$suffix.'</td></tr>';
+                               }
+                               $sql = $rs->fields[2];
+                               $check = $rs->fields[0].'::'.$rs->fields[1];                    
+                       } else
+                               $sql .= $rs->fields[2];
+                       
+                       $rs->MoveNext();
+               }
+               $rs->Close();
+               
+               $carr = explode('::',$check);
+               $prefix = "<a target=".rand()." href=\"?&hidem=1&$type=1&sql=".rawurlencode($sql).'&x#explain">';
+               $suffix = '</a>';
+               if (strlen($prefix)>2000) {
+                       $prefix = '';
+                       $suffix = '';
+               }
+               $s .=  "\n<tr><td align=right>".$carr[0].'</td><td align=right>'.$carr[1].'</td><td>'.$prefix.$sql.$suffix.'</td></tr>';
+                                       
+               return $s."</table>\n\n";
+       }
+       
+       // code thanks to Ixora. 
+       // http://www.ixora.com.au/scripts/query_opt.htm
+       // requires oracle 8.1.7 or later
+       function SuspiciousSQL($numsql=10)
+       {
+               $sql = "
+select
+  substr(to_char(s.pct, '99.00'), 2) || '%'  load,
+  s.executions  executes,
+  p.sql_text
+from
+  ( 
+    select
+      address,
+      buffer_gets,
+      executions,
+      pct,
+      rank() over (order by buffer_gets desc)  ranking
+    from
+      ( 
+       select
+         address,
+         buffer_gets,
+         executions,
+         100 * ratio_to_report(buffer_gets) over ()  pct
+       from
+         sys.v_\$sql
+       where
+         command_type != 47 and module != 'T.O.A.D.'
+      )
+    where
+      buffer_gets > 50 * executions
+  )  s,
+  sys.v_\$sqltext  p
+where
+  s.ranking <= $numsql and
+  p.address = s.address
+order by
+  1 desc, s.address, p.piece";
+
+               global $ADODB_CACHE_MODE,$HTTP_GET_VARS;
+               if (isset($HTTP_GET_VARS['expsixora']) && isset($HTTP_GET_VARS['sql'])) {
+                               $partial = empty($HTTP_GET_VARS['part']);
+                               echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
+               }
+
+               if (isset($HTTP_GET_VARS['sql'])) return $this->_SuspiciousSQL();
+               
+               $save = $ADODB_CACHE_MODE;
+               $ADODB_CACHE_MODE = ADODB_FETCH_NUM;
+               $savelog = $this->conn->LogSQL(false);
+               $rs =& $this->conn->SelectLimit($sql);
+               $this->conn->LogSQL($savelog);
+               $ADODB_CACHE_MODE = $save;
+               if ($rs) {
+                       $s = "\n<h3>Ixora Suspicious SQL</h3>";
+                       $s .= $this->tohtml($rs,'expsixora');
+               } else 
+                       $s = '';
+               
+               if ($s) $s .= '<p>';
+               $s .= $this->_SuspiciousSQL();
+               return $s;
+       }
+       
+       // code thanks to Ixora. 
+       // http://www.ixora.com.au/scripts/query_opt.htm
+       // requires oracle 8.1.7 or later
+       function ExpensiveSQL($numsql = 10)
+       {
+               $sql = "
+select
+  substr(to_char(s.pct, '99.00'), 2) || '%'  load,
+  s.executions  executes,
+  p.sql_text
+from
+  ( 
+    select
+      address,
+      disk_reads,
+      executions,
+      pct,
+      rank() over (order by disk_reads desc)  ranking
+    from
+      (
+       select
+         address,
+         disk_reads,
+         executions,
+         100 * ratio_to_report(disk_reads) over ()  pct
+       from
+         sys.v_\$sql
+       where
+         command_type != 47 and module != 'T.O.A.D.'
+      )
+    where
+      disk_reads > 50 * executions
+  )  s,
+  sys.v_\$sqltext  p
+where
+  s.ranking <= $numsql and
+  p.address = s.address
+order by
+  1 desc, s.address, p.piece
+";
+               global $ADODB_CACHE_MODE,$HTTP_GET_VARS;
+               if (isset($HTTP_GET_VARS['expeixora']) && isset($HTTP_GET_VARS['sql'])) {
+                       $partial = empty($HTTP_GET_VARS['part']);       
+                       echo "<a name=explain></a>".$this->Explain($HTTP_GET_VARS['sql'],$partial)."\n";
+               }
+               
+               if (isset($HTTP_GET_VARS['sql'])) {
+                        $var =& $this->_ExpensiveSQL();
+                        return $var;
+               }
+               $save = $ADODB_CACHE_MODE;
+               $ADODB_CACHE_MODE = ADODB_FETCH_NUM;
+               $savelog = $this->conn->LogSQL(false);
+               $rs =& $this->conn->Execute($sql);
+               $this->conn->LogSQL($savelog);
+               $ADODB_CACHE_MODE = $save;
+               if ($rs) {
+                       $s = "\n<h3>Ixora Expensive SQL</h3>";
+                       $s .= $this->tohtml($rs,'expeixora');
+               } else 
+                       $s = '';
+               
+               
+               if ($s) $s .= '<p>';
+               $s .= $this->_ExpensiveSQL();
+               return $s;
+       }
+       
+}
 ?>
\ No newline at end of file
index 5ae20e4d2a7d04ae8972b1c54edec138ac3f688f..2d5912ce5a16787aa84d1c75dff1d6418b01413b 100644 (file)
-<?php\r
-\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. See License.txt. \r
-  Set tabs to 4 for best viewing.\r
-  \r
-  Latest version is available at http://php.weblogs.com/\r
-  \r
-  Library for basic performance monitoring and tuning \r
-  \r
-*/\r
-\r
-/*\r
-       Notice that PostgreSQL has no sql query cache\r
-*/\r
-class perf_postgres extends adodb_perf{\r
-       \r
-       var $tablesSQL = \r
-       "select a.relname as tablename,(a.relpages+CASE WHEN b.relpages is null THEN 0 ELSE b.relpages END+CASE WHEN c.relpages is null THEN 0 ELSE c.relpages END)*8 as size_in_K,a.relfilenode as \"OID\"  from pg_class a left join pg_class b\r
-               on b.relname = 'pg_toast_'||trim(a.relfilenode) \r
-               left join pg_class c on c.relname = 'pg_toast_'||trim(a.relfilenode)||'_index'\r
-               where a.relname in (select tablename from pg_tables where tablename not like 'pg_%')";\r
-       \r
-       var $createTableSQL = "CREATE TABLE adodb_logsql (\r
-                 created timestamp NOT NULL,\r
-                 sql0 varchar(250) NOT NULL,\r
-                 sql1 text NOT NULL,\r
-                 params text NOT NULL,\r
-                 tracer text NOT NULL,\r
-                 timer decimal(16,6) NOT NULL\r
-               )";     \r
-       \r
-       var $settings = array(\r
-       'Ratios',\r
-               'statistics collector' => array('RATIO',\r
-                       "select case when count(*)=3 then 'TRUE' else 'FALSE' end from pg_settings where (name='stats_block_level' or name='stats_row_level' or name='stats_start_collector') and setting='on' ",\r
-                       'Value must be TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i> and <i>stats_block_level</i> must be set to true in postgresql.conf)'),\r
-               'data cache hit ratio' => array('RATIO',\r
-                       "select case when blks_hit=0 then 0 else (1-blks_read::float/blks_hit)*100 end from pg_stat_database where datname='\$DATABASE'",\r
-                       '=WarnCacheRatio'),\r
-       'IO',\r
-               'data reads' => array('IO',\r
-               'select sum(heap_blks_read+toast_blks_read) from pg_statio_user_tables',\r
-               ),\r
-               'data writes' => array('IO',\r
-               'select sum(n_tup_ins/4.0+n_tup_upd/8.0+n_tup_del/4.0)/16 from pg_stat_user_tables',\r
-               'Count of inserts/updates/deletes * coef'),\r
-\r
-       'Data Cache',\r
-               'data cache buffers' => array('DATAC',\r
-                       "select setting from pg_settings where name='shared_buffers'",\r
-                       'Number of cache buffers. <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic>Tuning</a>'),\r
-               'cache blocksize' => array('DATAC',\r
-                       'select 8192',\r
-                       '(estimate)' ),\r
-               'data cache size' => array( 'DATAC',\r
-               "select setting::integer*8192 from pg_settings where name='shared_buffers'",\r
-                       '' ),\r
-               'operating system cache size' => array( 'DATA',\r
-               "select setting::integer*8192 from pg_settings where name='effective_cache_size'",\r
-                       '(effective cache size)' ),\r
-       'Memory Usage',\r
-               'sort buffer size' => array('CACHE',\r
-                       "select setting::integer*1024 from pg_settings where name='sort_mem'",\r
-                       'Size of sort buffer (per query)' ),\r
-       'Connections',\r
-               'current connections' => array('SESS',\r
-                       'select count(*) from pg_stat_activity',\r
-                       ''),\r
-               'max connections' => array('SESS',\r
-                       "select setting from pg_settings where name='max_connections'",\r
-                       ''),\r
-       'Parameters',\r
-               'rollback buffers' => array('COST',\r
-                       "select setting from pg_settings where name='wal_buffers'",\r
-                       'WAL buffers'),\r
-               'random page cost' => array('COST',\r
-                       "select setting from pg_settings where name='random_page_cost'",\r
-                       'Cost of doing a seek (default=4). See <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#less>random_page_cost</a>'),\r
-               false\r
-       );\r
-       \r
-       function perf_postgres(&$conn)\r
-       {\r
-               $this->conn =& $conn;\r
-       }\r
-       \r
-       function Explain($sql,$partial=false)\r
-       {\r
-               $save = $this->conn->LogSQL(false);\r
-               \r
-               if ($partial) {\r
-                       $sqlq = $this->conn->qstr($sql.'%');\r
-                       $arr = $this->conn->GetArray("select distinct distinct sql1 from adodb_logsql where sql1 like $sqlq");\r
-                       if ($arr) {\r
-                               foreach($arr as $row) {\r
-                                       $sql = reset($row);\r
-                                       if (crc32($sql) == $partial) break;\r
-                               }\r
-                       }\r
-               }\r
-               $sql = str_replace('?',"''",$sql);\r
-               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';\r
-               $rs = $this->conn->Execute('EXPLAIN '.$sql);\r
-               $this->conn->LogSQL($save);\r
-               $s .= '<pre>';\r
-               if ($rs)\r
-                       while (!$rs->EOF) {\r
-                               $s .= reset($rs->fields)."\n";\r
-                               $rs->MoveNext();\r
-                       }\r
-               $s .= '</pre>';\r
-               $s .= $this->Tracer($sql,$partial);\r
-               return $s;\r
-       }\r
-}\r
+<?php
+
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
+  Set tabs to 4 for best viewing.
+  
+  Latest version is available at http://php.weblogs.com/
+  
+  Library for basic performance monitoring and tuning 
+  
+*/
+
+/*
+       Notice that PostgreSQL has no sql query cache
+*/
+class perf_postgres extends adodb_perf{
+       
+       var $tablesSQL = 
+       "select a.relname as tablename,(a.relpages+CASE WHEN b.relpages is null THEN 0 ELSE b.relpages END+CASE WHEN c.relpages is null THEN 0 ELSE c.relpages END)*8 as size_in_K,a.relfilenode as \"OID\"  from pg_class a left join pg_class b
+               on b.relname = 'pg_toast_'||trim(a.relfilenode) 
+               left join pg_class c on c.relname = 'pg_toast_'||trim(a.relfilenode)||'_index'
+               where a.relname in (select tablename from pg_tables where tablename not like 'pg_%')";
+       
+       var $createTableSQL = "CREATE TABLE adodb_logsql (
+                 created timestamp NOT NULL,
+                 sql0 varchar(250) NOT NULL,
+                 sql1 text NOT NULL,
+                 params text NOT NULL,
+                 tracer text NOT NULL,
+                 timer decimal(16,6) NOT NULL
+               )";     
+       
+       var $settings = array(
+       'Ratios',
+               'statistics collector' => array('RATIO',
+                       "select case when count(*)=3 then 'TRUE' else 'FALSE' end from pg_settings where (name='stats_block_level' or name='stats_row_level' or name='stats_start_collector') and setting='on' ",
+                       'Value must be TRUE to enable hit ratio statistics (<i>stats_start_collector</i>,<i>stats_row_level</i> and <i>stats_block_level</i> must be set to true in postgresql.conf)'),
+               'data cache hit ratio' => array('RATIO',
+                       "select case when blks_hit=0 then 0 else (1-blks_read::float/blks_hit)*100 end from pg_stat_database where datname='\$DATABASE'",
+                       '=WarnCacheRatio'),
+       'IO',
+               'data reads' => array('IO',
+               'select sum(heap_blks_read+toast_blks_read) from pg_statio_user_tables',
+               ),
+               'data writes' => array('IO',
+               'select sum(n_tup_ins/4.0+n_tup_upd/8.0+n_tup_del/4.0)/16 from pg_stat_user_tables',
+               'Count of inserts/updates/deletes * coef'),
+
+       'Data Cache',
+               'data cache buffers' => array('DATAC',
+                       "select setting from pg_settings where name='shared_buffers'",
+                       'Number of cache buffers. <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#basic>Tuning</a>'),
+               'cache blocksize' => array('DATAC',
+                       'select 8192',
+                       '(estimate)' ),
+               'data cache size' => array( 'DATAC',
+               "select setting::integer*8192 from pg_settings where name='shared_buffers'",
+                       '' ),
+               'operating system cache size' => array( 'DATA',
+               "select setting::integer*8192 from pg_settings where name='effective_cache_size'",
+                       '(effective cache size)' ),
+       'Memory Usage',
+               'sort buffer size' => array('CACHE',
+                       "select setting::integer*1024 from pg_settings where name='sort_mem'",
+                       'Size of sort buffer (per query)' ),
+       'Connections',
+               'current connections' => array('SESS',
+                       'select count(*) from pg_stat_activity',
+                       ''),
+               'max connections' => array('SESS',
+                       "select setting from pg_settings where name='max_connections'",
+                       ''),
+       'Parameters',
+               'rollback buffers' => array('COST',
+                       "select setting from pg_settings where name='wal_buffers'",
+                       'WAL buffers'),
+               'random page cost' => array('COST',
+                       "select setting from pg_settings where name='random_page_cost'",
+                       'Cost of doing a seek (default=4). See <a href=http://www.varlena.com/GeneralBits/Tidbits/perf.html#less>random_page_cost</a>'),
+               false
+       );
+       
+       function perf_postgres(&$conn)
+       {
+               $this->conn =& $conn;
+       }
+       
+       function Explain($sql,$partial=false)
+       {
+               $save = $this->conn->LogSQL(false);
+               
+               if ($partial) {
+                       $sqlq = $this->conn->qstr($sql.'%');
+                       $arr = $this->conn->GetArray("select distinct distinct sql1 from adodb_logsql where sql1 like $sqlq");
+                       if ($arr) {
+                               foreach($arr as $row) {
+                                       $sql = reset($row);
+                                       if (crc32($sql) == $partial) break;
+                               }
+                       }
+               }
+               $sql = str_replace('?',"''",$sql);
+               $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>';
+               $rs = $this->conn->Execute('EXPLAIN '.$sql);
+               $this->conn->LogSQL($save);
+               $s .= '<pre>';
+               if ($rs)
+                       while (!$rs->EOF) {
+                               $s .= reset($rs->fields)."\n";
+                               $rs->MoveNext();
+                       }
+               $s .= '</pre>';
+               $s .= $this->Tracer($sql,$partial);
+               return $s;
+       }
+}
 ?>
\ No newline at end of file
index f9c547f11b7c53654c78c2bd883a37840beed127..8d0f7a7b0404cffd61eea16ca845e2e890c3396e 100644 (file)
-<?php\r
-/** \r
- * @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license. \r
- * Whenever there is any discrepancy between the two licenses, \r
- * the BSD license will take precedence. \r
- *\r
- * Set tabs to 4 for best viewing.\r
- * \r
- * Latest version is available at http://php.weblogs.com\r
- *\r
- * Requires PHP4.01pl2 or later because it uses include_once\r
-*/\r
-\r
-/*\r
- * Concept from daniel.lucazeau@ajornet.com. \r
- *\r
- * @param db           Adodb database connection\r
- * @param tables       List of tables to join\r
- * @rowfields          List of fields to display on each row\r
- * @colfield           Pivot field to slice and display in columns, if we want to calculate\r
- *                                             ranges, we pass in an array (see example2)\r
- * @where                      Where clause. Optional.\r
- * @aggfield           This is the field to sum. Optional. \r
- *                                             Since 2.3.1, if you can use your own aggregate function \r
- *                                             instead of SUM, eg. $sumfield = 'AVG(fieldname)';\r
- * @sumlabel           Prefix to display in sum columns. Optional.\r
- * @aggfn                      Aggregate function to use (could be AVG, SUM, COUNT)\r
- * @showcount          Show count of records\r
- *\r
- * @returns                    Sql generated\r
- */\r
\r
- function PivotTableSQL($db,$tables,$rowfields,$colfield, $where=false,\r
-       $aggfield = false,$sumlabel='Sum ',$aggfn ='SUM', $showcount = true)\r
- {\r
-       if ($aggfield) $hidecnt = true;\r
-       else $hidecnt = false;\r
-       \r
-       \r
-       //$hidecnt = false;\r
-       \r
-       if ($where) $where = "\nWHERE $where";\r
-       if (!is_array($colfield)) $colarr = $db->GetCol("select distinct $colfield from $tables $where order by 1");\r
-       if (!$aggfield) $hidecnt = false;\r
-       \r
-       $sel = "$rowfields, ";\r
-       if (is_array($colfield)) {\r
-               foreach ($colfield as $k => $v) {\r
-                       if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", ";\r
-                       if ($aggfield)\r
-                               $sel .= "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", ";\r
-               } \r
-       } else {\r
-               foreach ($colarr as $v) {\r
-                       if (!is_numeric($v)) $vq = $db->qstr($v);\r
-                       else $vq = $v;\r
-                       if (strlen($v) == 0     ) $v = 'null';\r
-                       if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", ";\r
-                       if ($aggfield) {\r
-                               if ($hidecnt) $label = $v;\r
-                               else $label = "{$v}_$aggfield";\r
-                               $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", ";\r
-                       }\r
-               }\r
-       }\r
-       if ($aggfield && $aggfield != '1'){\r
-               $agg = "$aggfn($aggfield)";\r
-               $sel .= "\n\t$agg as \"$sumlabel$aggfield\", ";         \r
-       }\r
-       \r
-       if ($showcount)\r
-               $sel .= "\n\tSUM(1) as Total";\r
-       else\r
-               $sel = substr($sel,0,strlen($sel)-2);\r
-       \r
-       $sql = "SELECT $sel \nFROM $tables $where \nGROUP BY $rowfields";\r
-       return $sql;\r
- }\r
-\r
-/* EXAMPLES USING MS NORTHWIND DATABASE */\r
-if (0) {\r
-\r
-# example1\r
-#\r
-# Query the main "product" table\r
-# Set the rows to CompanyName and QuantityPerUnit\r
-# and the columns to the Categories\r
-# and define the joins to link to lookup tables \r
-# "categories" and "suppliers"\r
-#\r
-\r
- $sql = PivotTableSQL(\r
-       $gDB,                                                                                   # adodb connection\r
-       'products p ,categories c ,suppliers s',                # tables\r
-       'CompanyName,QuantityPerUnit',                                  # row fields\r
-       'CategoryName',                                                                 # column fields \r
-       'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where\r
-);\r
- print "<pre>$sql";\r
- $rs = $gDB->Execute($sql);\r
- rs2html($rs);\r
\r
-/*\r
-Generated SQL:\r
-\r
-SELECT CompanyName,QuantityPerUnit, \r
-       SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages", \r
-       SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments", \r
-       SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections", \r
-       SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy Products", \r
-       SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals", \r
-       SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry", \r
-       SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce", \r
-       SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood", \r
-       SUM(1) as Total \r
-FROM products p ,categories c ,suppliers s  WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID \r
-GROUP BY CompanyName,QuantityPerUnit\r
-*/\r
-//=====================================================================\r
-\r
-# example2\r
-#\r
-# Query the main "product" table\r
-# Set the rows to CompanyName and QuantityPerUnit\r
-# and the columns to the UnitsInStock for different ranges\r
-# and define the joins to link to lookup tables \r
-# "categories" and "suppliers"\r
-#\r
- $sql = PivotTableSQL(\r
-       $gDB,                                                                           # adodb connection\r
-       'products p ,categories c ,suppliers s',        # tables\r
-       'CompanyName,QuantityPerUnit',                          # row fields\r
-                                                                                               # column ranges\r
-array(                                                                         \r
-' 0 ' => 'UnitsInStock <= 0',\r
-"1 to 5" => '0 < UnitsInStock and UnitsInStock <= 5',\r
-"6 to 10" => '5 < UnitsInStock and UnitsInStock <= 10',\r
-"11 to 15"  => '10 < UnitsInStock and UnitsInStock <= 15',\r
-"16+" =>'15 < UnitsInStock'\r
-),\r
-       ' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where\r
-       'UnitsInStock',                                                         # sum this field\r
-       'Sum'                                                                           # sum label prefix\r
-);\r
- print "<pre>$sql";\r
- $rs = $gDB->Execute($sql);\r
- rs2html($rs);\r
- /*\r
- Generated SQL:\r
\r
-SELECT CompanyName,QuantityPerUnit, \r
-       SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum  0 ", \r
-       SUM(CASE WHEN 0 < UnitsInStock and UnitsInStock <= 5 THEN UnitsInStock ELSE 0 END) AS "Sum 1 to 5", \r
-       SUM(CASE WHEN 5 < UnitsInStock and UnitsInStock <= 10 THEN UnitsInStock ELSE 0 END) AS "Sum 6 to 10", \r
-       SUM(CASE WHEN 10 < UnitsInStock and UnitsInStock <= 15 THEN UnitsInStock ELSE 0 END) AS "Sum 11 to 15", \r
-       SUM(CASE WHEN 15 < UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 16+",\r
-       SUM(UnitsInStock) AS "Sum UnitsInStock", \r
-       SUM(1) as Total \r
-FROM products p ,categories c ,suppliers s  WHERE  p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID \r
-GROUP BY CompanyName,QuantityPerUnit\r
- */\r
-}\r
+<?php
+/** 
+ * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com
+ *
+ * Requires PHP4.01pl2 or later because it uses include_once
+*/
+
+/*
+ * Concept from daniel.lucazeau@ajornet.com. 
+ *
+ * @param db           Adodb database connection
+ * @param tables       List of tables to join
+ * @rowfields          List of fields to display on each row
+ * @colfield           Pivot field to slice and display in columns, if we want to calculate
+ *                                             ranges, we pass in an array (see example2)
+ * @where                      Where clause. Optional.
+ * @aggfield           This is the field to sum. Optional. 
+ *                                             Since 2.3.1, if you can use your own aggregate function 
+ *                                             instead of SUM, eg. $sumfield = 'AVG(fieldname)';
+ * @sumlabel           Prefix to display in sum columns. Optional.
+ * @aggfn                      Aggregate function to use (could be AVG, SUM, COUNT)
+ * @showcount          Show count of records
+ *
+ * @returns                    Sql generated
+ */
+ function PivotTableSQL($db,$tables,$rowfields,$colfield, $where=false,
+       $aggfield = false,$sumlabel='Sum ',$aggfn ='SUM', $showcount = true)
+ {
+       if ($aggfield) $hidecnt = true;
+       else $hidecnt = false;
+       
+       
+       //$hidecnt = false;
+       
+       if ($where) $where = "\nWHERE $where";
+       if (!is_array($colfield)) $colarr = $db->GetCol("select distinct $colfield from $tables $where order by 1");
+       if (!$aggfield) $hidecnt = false;
+       
+       $sel = "$rowfields, ";
+       if (is_array($colfield)) {
+               foreach ($colfield as $k => $v) {
+                       if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", ";
+                       if ($aggfield)
+                               $sel .= "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", ";
+               } 
+       } else {
+               foreach ($colarr as $v) {
+                       if (!is_numeric($v)) $vq = $db->qstr($v);
+                       else $vq = $v;
+                       if (strlen($v) == 0     ) $v = 'null';
+                       if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", ";
+                       if ($aggfield) {
+                               if ($hidecnt) $label = $v;
+                               else $label = "{$v}_$aggfield";
+                               $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", ";
+                       }
+               }
+       }
+       if ($aggfield && $aggfield != '1'){
+               $agg = "$aggfn($aggfield)";
+               $sel .= "\n\t$agg as \"$sumlabel$aggfield\", ";         
+       }
+       
+       if ($showcount)
+               $sel .= "\n\tSUM(1) as Total";
+       else
+               $sel = substr($sel,0,strlen($sel)-2);
+       
+       $sql = "SELECT $sel \nFROM $tables $where \nGROUP BY $rowfields";
+       return $sql;
+ }
+
+/* EXAMPLES USING MS NORTHWIND DATABASE */
+if (0) {
+
+# example1
+#
+# Query the main "product" table
+# Set the rows to CompanyName and QuantityPerUnit
+# and the columns to the Categories
+# and define the joins to link to lookup tables 
+# "categories" and "suppliers"
+#
+
+ $sql = PivotTableSQL(
+       $gDB,                                                                                   # adodb connection
+       'products p ,categories c ,suppliers s',                # tables
+       'CompanyName,QuantityPerUnit',                                  # row fields
+       'CategoryName',                                                                 # column fields 
+       'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where
+);
+ print "<pre>$sql";
+ $rs = $gDB->Execute($sql);
+ rs2html($rs);
+/*
+Generated SQL:
+
+SELECT CompanyName,QuantityPerUnit, 
+       SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages", 
+       SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments", 
+       SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections", 
+       SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy Products", 
+       SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals", 
+       SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry", 
+       SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce", 
+       SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood", 
+       SUM(1) as Total 
+FROM products p ,categories c ,suppliers s  WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID 
+GROUP BY CompanyName,QuantityPerUnit
+*/
+//=====================================================================
+
+# example2
+#
+# Query the main "product" table
+# Set the rows to CompanyName and QuantityPerUnit
+# and the columns to the UnitsInStock for different ranges
+# and define the joins to link to lookup tables 
+# "categories" and "suppliers"
+#
+ $sql = PivotTableSQL(
+       $gDB,                                                                           # adodb connection
+       'products p ,categories c ,suppliers s',        # tables
+       'CompanyName,QuantityPerUnit',                          # row fields
+                                                                                               # column ranges
+array(                                                                         
+' 0 ' => 'UnitsInStock <= 0',
+"1 to 5" => '0 < UnitsInStock and UnitsInStock <= 5',
+"6 to 10" => '5 < UnitsInStock and UnitsInStock <= 10',
+"11 to 15"  => '10 < UnitsInStock and UnitsInStock <= 15',
+"16+" =>'15 < UnitsInStock'
+),
+       ' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where
+       'UnitsInStock',                                                         # sum this field
+       'Sum'                                                                           # sum label prefix
+);
+ print "<pre>$sql";
+ $rs = $gDB->Execute($sql);
+ rs2html($rs);
+ /*
+ Generated SQL:
+SELECT CompanyName,QuantityPerUnit, 
+       SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum  0 ", 
+       SUM(CASE WHEN 0 < UnitsInStock and UnitsInStock <= 5 THEN UnitsInStock ELSE 0 END) AS "Sum 1 to 5", 
+       SUM(CASE WHEN 5 < UnitsInStock and UnitsInStock <= 10 THEN UnitsInStock ELSE 0 END) AS "Sum 6 to 10", 
+       SUM(CASE WHEN 10 < UnitsInStock and UnitsInStock <= 15 THEN UnitsInStock ELSE 0 END) AS "Sum 11 to 15", 
+       SUM(CASE WHEN 15 < UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 16+",
+       SUM(UnitsInStock) AS "Sum UnitsInStock", 
+       SUM(1) as Total 
+FROM products p ,categories c ,suppliers s  WHERE  p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID 
+GROUP BY CompanyName,QuantityPerUnit
+ */
+}
 ?>
\ No newline at end of file
index 25ff1c71fa0b77b0fe47b185ac96d1a37acf385d..8f377cf1c90d4770054b8101c67a10b0b136e1bc 100644 (file)
@@ -1,54 +1,54 @@
-<?php\r
-/** \r
- * @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license. \r
- * Whenever there is any discrepancy between the two licenses, \r
- * the BSD license will take precedence. \r
- *\r
- * Set tabs to 4 for best viewing.\r
- * \r
- * Latest version is available at http://php.weblogs.com\r
- *\r
- * Requires PHP4.01pl2 or later because it uses include_once\r
-*/\r
-\r
-/*\r
-       Filter all fields and all rows in a recordset and returns the \r
-       processed recordset. We scroll to the beginning of the new recordset\r
-       after processing.\r
-       \r
-       We pass a recordset and function name to RSFilter($rs,'rowfunc');\r
-       and the function will be called multiple times, once\r
-       for each row in the recordset. The function will be passed\r
-       an array containing one row repeatedly.\r
-       \r
-       Example: \r
-       \r
-       // ucwords() every element in the recordset\r
-       function do_ucwords(&$arr,$rs)\r
-       {\r
-               foreach($arr as $k => $v) {\r
-                       $arr[$k] = ucwords($v);\r
-               }\r
-       }\r
-       $rs = RSFilter($rs,'do_ucwords');\r
- */\r
-function &RSFilter($rs,$fn)\r
-{\r
-       if ($rs->databaseType != 'array') {\r
-               if (!$rs->connection) return false;\r
-               \r
-               $rs = &$rs->connection->_rs2rs($rs);\r
-       }\r
-       $rows = $rs->RecordCount();\r
-       for ($i=0; $i < $rows; $i++) {\r
-               $fn($rs->_array[$i],$rs);\r
-       }\r
-       if (!$rs->EOF) {\r
-               $rs->_currentRow = 0;\r
-               $rs->fields = $rs->_array[0];\r
-       }\r
-       \r
-       return $rs;\r
-}\r
+<?php
+/** 
+ * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com
+ *
+ * Requires PHP4.01pl2 or later because it uses include_once
+*/
+
+/*
+       Filter all fields and all rows in a recordset and returns the 
+       processed recordset. We scroll to the beginning of the new recordset
+       after processing.
+       
+       We pass a recordset and function name to RSFilter($rs,'rowfunc');
+       and the function will be called multiple times, once
+       for each row in the recordset. The function will be passed
+       an array containing one row repeatedly.
+       
+       Example: 
+       
+       // ucwords() every element in the recordset
+       function do_ucwords(&$arr,$rs)
+       {
+               foreach($arr as $k => $v) {
+                       $arr[$k] = ucwords($v);
+               }
+       }
+       $rs = RSFilter($rs,'do_ucwords');
+ */
+function &RSFilter($rs,$fn)
+{
+       if ($rs->databaseType != 'array') {
+               if (!$rs->connection) return false;
+               
+               $rs = &$rs->connection->_rs2rs($rs);
+       }
+       $rows = $rs->RecordCount();
+       for ($i=0; $i < $rows; $i++) {
+               $fn($rs->_array[$i],$rs);
+       }
+       if (!$rs->EOF) {
+               $rs->_currentRow = 0;
+               $rs->fields = $rs->_array[0];
+       }
+       
+       return $rs;
+}
 ?>
\ No newline at end of file
index dc5c4ff89c8486330468505251f78adf0ed78c4b..57ee71cbf1903bd1f4c486b8e93e3d4e88969518 100644 (file)
@@ -1,98 +1,98 @@
-<?php\r
-\r
-/** \r
- * @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
- */\r
\r
-/* Documentation on usage is at http://php.weblogs.com/adodb_csv\r
- *\r
- * Legal query string parameters:\r
- * \r
- * sql = holds sql string\r
- * nrows = number of rows to return \r
- * offset = skip offset rows of data\r
- * fetch = $ADODB_FETCH_MODE\r
- * \r
- * example:\r
- *\r
- * http://localhost/php/server.php?select+*+from+table&nrows=10&offset=2\r
- */\r
-\r
-\r
-/* \r
- * Define the IP address you want to accept requests from \r
- * as a security measure. If blank we accept anyone promisciously!\r
- */\r
-$ACCEPTIP = '';\r
-\r
-/*\r
- * Connection parameters\r
- */\r
-$driver = 'mysql';\r
-$host = 'localhost'; // DSN for odbc\r
-$uid = 'root';\r
-$pwd = '';\r
-$database = 'test';\r
-\r
-/*============================ DO NOT MODIFY BELOW HERE =================================*/\r
-// $sep must match csv2rs() in adodb.inc.php\r
-$sep = ' :::: ';\r
-\r
-include('./adodb.inc.php');\r
-include_once(ADODB_DIR.'/adodb-csvlib.inc.php');\r
-\r
-function err($s)\r
-{\r
-       die('**** '.$s.' ');\r
-}\r
-\r
-// undo stupid magic quotes\r
-function undomq(&$m) \r
-{\r
-       if (get_magic_quotes_gpc()) {\r
-               // undo the damage\r
-               $m = str_replace('\\\\','\\',$m);\r
-               $m = str_replace('\"','"',$m);\r
-               $m = str_replace('\\\'','\'',$m);\r
-               \r
-       }\r
-       return $m;\r
-}\r
-\r
-///////////////////////////////////////// DEFINITIONS\r
-\r
-\r
-$remote = $HTTP_SERVER_VARS["REMOTE_ADDR"]; \r
\r
-if (empty($HTTP_GET_VARS['sql'])) err('No SQL');\r
-\r
-if (!empty($ACCEPTIP))\r
- if ($remote != '127.0.0.1' && $remote != $ACCEPTIP) \r
-       err("Unauthorised client: '$remote'");\r
-\r
-\r
-$conn = &ADONewConnection($driver);\r
-\r
-if (!$conn->Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());\r
-$sql = undomq($HTTP_GET_VARS['sql']);\r
-\r
-if (isset($HTTP_GET_VARS['fetch']))\r
-       $ADODB_FETCH_MODE = $HTTP_GET_VARS['fetch'];\r
-       \r
-if (isset($HTTP_GET_VARS['nrows'])) {\r
-       $nrows = $HTTP_GET_VARS['nrows'];\r
-       $offset = isset($HTTP_GET_VARS['offset']) ? $HTTP_GET_VARS['offset'] : -1;\r
-       $rs = $conn->SelectLimit($sql,$nrows,$offset);\r
-} else \r
-       $rs = $conn->Execute($sql);\r
-if ($rs){ \r
-       //$rs->timeToLive = 1;\r
-       echo _rs2serialize($rs,$conn,$sql);\r
-       $rs->Close();\r
-} else\r
-       err($conn->ErrorNo(). $sep .$conn->ErrorMsg());\r
-\r
+<?php
+
+/** 
+ * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+ */
+/* Documentation on usage is at http://php.weblogs.com/adodb_csv
+ *
+ * Legal query string parameters:
+ * 
+ * sql = holds sql string
+ * nrows = number of rows to return 
+ * offset = skip offset rows of data
+ * fetch = $ADODB_FETCH_MODE
+ * 
+ * example:
+ *
+ * http://localhost/php/server.php?select+*+from+table&nrows=10&offset=2
+ */
+
+
+/* 
+ * Define the IP address you want to accept requests from 
+ * as a security measure. If blank we accept anyone promisciously!
+ */
+$ACCEPTIP = '';
+
+/*
+ * Connection parameters
+ */
+$driver = 'mysql';
+$host = 'localhost'; // DSN for odbc
+$uid = 'root';
+$pwd = '';
+$database = 'test';
+
+/*============================ DO NOT MODIFY BELOW HERE =================================*/
+// $sep must match csv2rs() in adodb.inc.php
+$sep = ' :::: ';
+
+include('./adodb.inc.php');
+include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
+
+function err($s)
+{
+       die('**** '.$s.' ');
+}
+
+// undo stupid magic quotes
+function undomq(&$m) 
+{
+       if (get_magic_quotes_gpc()) {
+               // undo the damage
+               $m = str_replace('\\\\','\\',$m);
+               $m = str_replace('\"','"',$m);
+               $m = str_replace('\\\'','\'',$m);
+               
+       }
+       return $m;
+}
+
+///////////////////////////////////////// DEFINITIONS
+
+
+$remote = $HTTP_SERVER_VARS["REMOTE_ADDR"]; 
+if (empty($HTTP_GET_VARS['sql'])) err('No SQL');
+
+if (!empty($ACCEPTIP))
+ if ($remote != '127.0.0.1' && $remote != $ACCEPTIP) 
+       err("Unauthorised client: '$remote'");
+
+
+$conn = &ADONewConnection($driver);
+
+if (!$conn->Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());
+$sql = undomq($HTTP_GET_VARS['sql']);
+
+if (isset($HTTP_GET_VARS['fetch']))
+       $ADODB_FETCH_MODE = $HTTP_GET_VARS['fetch'];
+       
+if (isset($HTTP_GET_VARS['nrows'])) {
+       $nrows = $HTTP_GET_VARS['nrows'];
+       $offset = isset($HTTP_GET_VARS['offset']) ? $HTTP_GET_VARS['offset'] : -1;
+       $rs = $conn->SelectLimit($sql,$nrows,$offset);
+} else 
+       $rs = $conn->Execute($sql);
+if ($rs){ 
+       //$rs->timeToLive = 1;
+       echo _rs2serialize($rs,$conn,$sql);
+       $rs->Close();
+} else
+       err($conn->ErrorNo(). $sep .$conn->ErrorMsg());
+
 ?>
\ No newline at end of file
index 484b9cc78b965d7426b6a4fe341a835f7f9601b0..53636cbf45d43b0afcf78b7898029faa94cc9bf8 100644 (file)
@@ -1,84 +1,84 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
-\r
-<html>\r
-<head>\r
-       <title>ADODB Benchmarks</title>\r
-</head> \r
-\r
-<body>\r
-<?php \r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  \r
-  Benchmark code to test the speed to the ADODB library with different databases.\r
-  This is a simplistic benchmark to be used as the basis for further testing.\r
-  It should not be used as proof of the superiority of one database over the other.\r
-*/ \r
\r
-$testmssql = true;\r
-//$testvfp = true;\r
-$testoracle = true;\r
-$testado = true; \r
-$testibase = true;\r
-$testaccess = true;\r
-$testmysql = true;\r
-$testsqlite = true;;\r
-\r
-set_time_limit(240); // increase timeout\r
-\r
-include("../tohtml.inc.php");\r
-include("../adodb.inc.php");\r
-\r
-function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")\r
-{\r
-GLOBAL $ADODB_version,$ADODB_FETCH_MODE;\r
-\r
-       adodb_backtrace();\r
-       \r
-       $max = 100;\r
-       $sql = 'select * from ADOXYZ';\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-       \r
-       //print "<h3>ADODB Version: $ADODB_version Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i></h3>";\r
-       \r
-       // perform query once to cache results so we are only testing throughput \r
-       $rs = $db->Execute($sql);\r
-       if (!$rs){\r
-               print "Error in recordset<p>";\r
-               return;\r
-       }       \r
-       $arr = $rs->GetArray();\r
-       //$db->debug = true;\r
-       global $ADODB_COUNTRECS;\r
-       $ADODB_COUNTRECS = false;\r
-       $start = microtime();\r
-       for ($i=0; $i < $max; $i++) {\r
-               $rs =& $db->Execute($sql);      \r
-               $arr =& $rs->GetArray();\r
-          //            print $arr[0][1];\r
-       }\r
-       $end =  microtime();\r
-       $start = explode(' ',$start);\r
-       $end = explode(' ',$end);\r
-       \r
-       //print_r($start);\r
-       //print_r($end);\r
-       \r
-         //  print_r($arr);\r
-       $total = $end[0]+trim($end[1]) - $start[0]-trim($start[1]);\r
-       printf ("<p>seconds = %8.2f for %d iterations each with %d records</p>",$total,$max, sizeof($arr));\r
-       flush();\r
-\r
-\r
-               //$db->Close();\r
-}\r
-include("testdatabases.inc.php");\r
-\r
-?>\r
-\r
-\r
-</body>\r
-</html>\r
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+       <title>ADODB Benchmarks</title>
+</head> 
+
+<body>
+<?php 
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  
+  Benchmark code to test the speed to the ADODB library with different databases.
+  This is a simplistic benchmark to be used as the basis for further testing.
+  It should not be used as proof of the superiority of one database over the other.
+*/ 
+$testmssql = true;
+//$testvfp = true;
+$testoracle = true;
+$testado = true; 
+$testibase = true;
+$testaccess = true;
+$testmysql = true;
+$testsqlite = true;;
+
+set_time_limit(240); // increase timeout
+
+include("../tohtml.inc.php");
+include("../adodb.inc.php");
+
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
+{
+GLOBAL $ADODB_version,$ADODB_FETCH_MODE;
+
+       adodb_backtrace();
+       
+       $max = 100;
+       $sql = 'select * from ADOXYZ';
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+       
+       //print "<h3>ADODB Version: $ADODB_version Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i></h3>";
+       
+       // perform query once to cache results so we are only testing throughput 
+       $rs = $db->Execute($sql);
+       if (!$rs){
+               print "Error in recordset<p>";
+               return;
+       }       
+       $arr = $rs->GetArray();
+       //$db->debug = true;
+       global $ADODB_COUNTRECS;
+       $ADODB_COUNTRECS = false;
+       $start = microtime();
+       for ($i=0; $i < $max; $i++) {
+               $rs =& $db->Execute($sql);      
+               $arr =& $rs->GetArray();
+          //            print $arr[0][1];
+       }
+       $end =  microtime();
+       $start = explode(' ',$start);
+       $end = explode(' ',$end);
+       
+       //print_r($start);
+       //print_r($end);
+       
+         //  print_r($arr);
+       $total = $end[0]+trim($end[1]) - $start[0]-trim($start[1]);
+       printf ("<p>seconds = %8.2f for %d iterations each with %d records</p>",$total,$max, sizeof($arr));
+       flush();
+
+
+               //$db->Close();
+}
+include("testdatabases.inc.php");
+
+?>
+
+
+</body>
+</html>
index c89051ade3370926c3385c48cfa9e583a4163003..c7cca950351e6df2fa5fe08c11d09b0fef37e2c9 100644 (file)
-<html>\r
-<body bgcolor=white>\r
-<?php\r
-/** \r
- * V4.11 27 Jan 2004  (c) 2001-2002 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
- * \r
- * set tabs to 8\r
- */\r
\r
- // documentation on usage is at http://php.weblogs.com/adodb_csv\r
\r
-include('../adodb.inc.php');\r
-include('../tohtml.inc.php');\r
-\r
- function &send2server($url,$sql)\r
- {\r
-       $url .= '?sql='.urlencode($sql);\r
-       print "<p>$url</p>";\r
-       $rs = csv2rs($url,$err);\r
-       if ($err) print $err;\r
-       return $rs;\r
- }\r
\r
- function print_pre($s)\r
- {\r
-       print "<pre>";print_r($s);print "</pre>";\r
- }\r
-\r
-\r
-$serverURL = 'http://localhost/php/phplens/adodb/server.php';\r
-$testhttp = false;\r
-\r
-$sql1 = "insertz into products (productname) values ('testprod 1')";\r
-$sql2 = "insert into products (productname) values ('testprod 1')";\r
-$sql3 = "insert into products (productname) values ('testprod 2')";\r
-$sql4 = "delete from products where productid>80";\r
-$sql5 = 'select * from products';\r
-       \r
-if ($testhttp) {\r
-       print "<a href=#c>Client Driver Tests</a><p>";\r
-       print "<h3>Test Error</h3>";\r
-       $rs = send2server($serverURL,$sql1);\r
-       print_pre($rs);\r
-       print "<hr>";\r
-       \r
-       print "<h3>Test Insert</h3>";\r
-       \r
-       $rs = send2server($serverURL,$sql2);\r
-       print_pre($rs);\r
-       print "<hr>";\r
-       \r
-       print "<h3>Test Insert2</h3>";\r
-       \r
-       $rs = send2server($serverURL,$sql3);\r
-       print_pre($rs);\r
-       print "<hr>";\r
-       \r
-       print "<h3>Test Delete</h3>";\r
-       \r
-       $rs = send2server($serverURL,$sql4);\r
-       print_pre($rs);\r
-       print "<hr>";\r
-       \r
-       \r
-       print "<h3>Test Select</h3>";\r
-       $rs = send2server($serverURL,$sql5);\r
-       if ($rs) rs2html($rs);\r
-       \r
-       print "<hr>";\r
-}\r
-\r
-\r
-print "<a name=c><h1>CLIENT Driver Tests</h1>";\r
-$conn = ADONewConnection('csv');\r
-$conn->Connect($serverURL);\r
-$conn->debug = true;\r
-\r
-print "<h3>Bad SQL</h3>";\r
-\r
-$rs = $conn->Execute($sql1);\r
-\r
-print "<h3>Insert SQL 1</h3>";\r
-$rs = $conn->Execute($sql2);\r
-\r
-print "<h3>Insert SQL 2</h3>";\r
-$rs = $conn->Execute($sql3);\r
-\r
-print "<h3>Select SQL</h3>";\r
-$rs = $conn->Execute($sql5);\r
-if ($rs) rs2html($rs);\r
-\r
-print "<h3>Delete SQL</h3>";\r
-$rs = $conn->Execute($sql4);\r
-\r
-print "<h3>Select SQL</h3>";\r
-$rs = $conn->Execute($sql5);\r
-if ($rs) rs2html($rs);\r
-\r
-\r
-/* EXPECTED RESULTS FOR HTTP TEST:\r
-\r
-Test Insert\r
-http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29\r
-\r
-adorecordset Object\r
-(\r
-       [dataProvider] => native\r
-       [fields] => \r
-       [blobSize] => 64\r
-       [canSeek] => \r
-       [EOF] => 1\r
-       [emptyTimeStamp] =>  \r
-       [emptyDate] =>  \r
-       [debug] => \r
-       [timeToLive] => 0\r
-       [bind] => \r
-       [_numOfRows] => -1\r
-       [_numOfFields] => 0\r
-       [_queryID] => 1\r
-       [_currentRow] => -1\r
-       [_closed] => \r
-       [_inited] => \r
-       [sql] => insert into products (productname) values ('testprod')\r
-       [affectedrows] => 1\r
-       [insertid] => 81\r
-)\r
-\r
-\r
---------------------------------------------------------------------------------\r
-\r
-Test Insert2\r
-http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29\r
-\r
-adorecordset Object\r
-(\r
-       [dataProvider] => native\r
-       [fields] => \r
-       [blobSize] => 64\r
-       [canSeek] => \r
-       [EOF] => 1\r
-       [emptyTimeStamp] =>  \r
-       [emptyDate] =>  \r
-       [debug] => \r
-       [timeToLive] => 0\r
-       [bind] => \r
-       [_numOfRows] => -1\r
-       [_numOfFields] => 0\r
-       [_queryID] => 1\r
-       [_currentRow] => -1\r
-       [_closed] => \r
-       [_inited] => \r
-       [sql] => insert into products (productname) values ('testprod')\r
-       [affectedrows] => 1\r
-       [insertid] => 82\r
-)\r
-\r
-\r
---------------------------------------------------------------------------------\r
-\r
-Test Delete\r
-http://localhost/php/adodb/server.php?sql=delete+from+products+where+productid%3E80\r
-\r
-adorecordset Object\r
-(\r
-       [dataProvider] => native\r
-       [fields] => \r
-       [blobSize] => 64\r
-       [canSeek] => \r
-       [EOF] => 1\r
-       [emptyTimeStamp] =>  \r
-       [emptyDate] =>  \r
-       [debug] => \r
-       [timeToLive] => 0\r
-       [bind] => \r
-       [_numOfRows] => -1\r
-       [_numOfFields] => 0\r
-       [_queryID] => 1\r
-       [_currentRow] => -1\r
-       [_closed] => \r
-       [_inited] => \r
-       [sql] => delete from products where productid>80\r
-       [affectedrows] => 2\r
-       [insertid] => 0\r
-)\r
-\r
-[more stuff deleted]\r
- .\r
- . \r
- .\r
-*/\r
-?>\r
+<html>
+<body bgcolor=white>
+<?php
+/** 
+ * V4.20 22 Feb 2004  (c) 2001-2002 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+ * 
+ * set tabs to 8
+ */
+ // documentation on usage is at http://php.weblogs.com/adodb_csv
+include('../adodb.inc.php');
+include('../tohtml.inc.php');
+
+ function &send2server($url,$sql)
+ {
+       $url .= '?sql='.urlencode($sql);
+       print "<p>$url</p>";
+       $rs = csv2rs($url,$err);
+       if ($err) print $err;
+       return $rs;
+ }
+ function print_pre($s)
+ {
+       print "<pre>";print_r($s);print "</pre>";
+ }
+
+
+$serverURL = 'http://localhost/php/phplens/adodb/server.php';
+$testhttp = false;
+
+$sql1 = "insertz into products (productname) values ('testprod 1')";
+$sql2 = "insert into products (productname) values ('testprod 1')";
+$sql3 = "insert into products (productname) values ('testprod 2')";
+$sql4 = "delete from products where productid>80";
+$sql5 = 'select * from products';
+       
+if ($testhttp) {
+       print "<a href=#c>Client Driver Tests</a><p>";
+       print "<h3>Test Error</h3>";
+       $rs = send2server($serverURL,$sql1);
+       print_pre($rs);
+       print "<hr>";
+       
+       print "<h3>Test Insert</h3>";
+       
+       $rs = send2server($serverURL,$sql2);
+       print_pre($rs);
+       print "<hr>";
+       
+       print "<h3>Test Insert2</h3>";
+       
+       $rs = send2server($serverURL,$sql3);
+       print_pre($rs);
+       print "<hr>";
+       
+       print "<h3>Test Delete</h3>";
+       
+       $rs = send2server($serverURL,$sql4);
+       print_pre($rs);
+       print "<hr>";
+       
+       
+       print "<h3>Test Select</h3>";
+       $rs = send2server($serverURL,$sql5);
+       if ($rs) rs2html($rs);
+       
+       print "<hr>";
+}
+
+
+print "<a name=c><h1>CLIENT Driver Tests</h1>";
+$conn = ADONewConnection('csv');
+$conn->Connect($serverURL);
+$conn->debug = true;
+
+print "<h3>Bad SQL</h3>";
+
+$rs = $conn->Execute($sql1);
+
+print "<h3>Insert SQL 1</h3>";
+$rs = $conn->Execute($sql2);
+
+print "<h3>Insert SQL 2</h3>";
+$rs = $conn->Execute($sql3);
+
+print "<h3>Select SQL</h3>";
+$rs = $conn->Execute($sql5);
+if ($rs) rs2html($rs);
+
+print "<h3>Delete SQL</h3>";
+$rs = $conn->Execute($sql4);
+
+print "<h3>Select SQL</h3>";
+$rs = $conn->Execute($sql5);
+if ($rs) rs2html($rs);
+
+
+/* EXPECTED RESULTS FOR HTTP TEST:
+
+Test Insert
+http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29
+
+adorecordset Object
+(
+       [dataProvider] => native
+       [fields] => 
+       [blobSize] => 64
+       [canSeek] => 
+       [EOF] => 1
+       [emptyTimeStamp] =>  
+       [emptyDate] =>  
+       [debug] => 
+       [timeToLive] => 0
+       [bind] => 
+       [_numOfRows] => -1
+       [_numOfFields] => 0
+       [_queryID] => 1
+       [_currentRow] => -1
+       [_closed] => 
+       [_inited] => 
+       [sql] => insert into products (productname) values ('testprod')
+       [affectedrows] => 1
+       [insertid] => 81
+)
+
+
+--------------------------------------------------------------------------------
+
+Test Insert2
+http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29
+
+adorecordset Object
+(
+       [dataProvider] => native
+       [fields] => 
+       [blobSize] => 64
+       [canSeek] => 
+       [EOF] => 1
+       [emptyTimeStamp] =>  
+       [emptyDate] =>  
+       [debug] => 
+       [timeToLive] => 0
+       [bind] => 
+       [_numOfRows] => -1
+       [_numOfFields] => 0
+       [_queryID] => 1
+       [_currentRow] => -1
+       [_closed] => 
+       [_inited] => 
+       [sql] => insert into products (productname) values ('testprod')
+       [affectedrows] => 1
+       [insertid] => 82
+)
+
+
+--------------------------------------------------------------------------------
+
+Test Delete
+http://localhost/php/adodb/server.php?sql=delete+from+products+where+productid%3E80
+
+adorecordset Object
+(
+       [dataProvider] => native
+       [fields] => 
+       [blobSize] => 64
+       [canSeek] => 
+       [EOF] => 1
+       [emptyTimeStamp] =>  
+       [emptyDate] =>  
+       [debug] => 
+       [timeToLive] => 0
+       [bind] => 
+       [_numOfRows] => -1
+       [_numOfFields] => 0
+       [_queryID] => 1
+       [_currentRow] => -1
+       [_closed] => 
+       [_inited] => 
+       [sql] => delete from products where productid>80
+       [affectedrows] => 2
+       [insertid] => 0
+)
+
+[more stuff deleted]
+ .
+ . 
+ .
+*/
+?>
index 176a1f3fd308ecfdbebfec1014b27f791e83ceb9..8a6563de1ce1cd18d5603619798fc2701cc45ace 100644 (file)
-<?php\r
-/*\r
-\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-       \r
-  Set tabs to 4 for best viewing.\r
-\r
-*/\r
-\r
-error_reporting(E_ALL);\r
-include_once('../adodb.inc.php');\r
-\r
-foreach(array('sybase','mysql','access','oci8','postgres','odbc_mssql','odbc','sybase','firebird','informix','db2') as $dbType) {\r
-       echo "<h3>$dbType</h3><p>";\r
-       $db = NewADOConnection($dbType);\r
-       $dict = NewDataDictionary($db);\r
-\r
-       if (!$dict) continue;\r
-       $dict->debug = 1;\r
-       \r
-       $opts = array('REPLACE','mysql' => 'TYPE=ISAM', 'oci8' => 'TABLESPACE USERS');\r
-       \r
-/*     $flds = array(\r
-               array('id',     'I',                                                            \r
-                                                       'AUTO','KEY'),\r
-                                                       \r
-               array('name' => 'firstname', 'type' => 'varchar','size' => 30,\r
-                                                       'DEFAULT'=>'Joan'),\r
-                                                       \r
-               array('lastname','varchar',28,\r
-                                                       'DEFAULT'=>'Chen','key'),\r
-                                                       \r
-               array('averylonglongfieldname','X',1024,\r
-                                                       'NOTNULL','default' => 'test'),\r
-                                                       \r
-               array('price','N','7.2',\r
-                                                       'NOTNULL','default' => '0.00'),\r
-                                                       \r
-               array('MYDATE', 'D', \r
-                                                       'DEFDATE'),\r
-               array('TS','T',\r
-                                                       'DEFTIMESTAMP')\r
-       );*/\r
-       \r
-       $flds = "\r
-ID            I           AUTO KEY,\r
-FIRSTNAME     VARCHAR(30) DEFAULT 'Joan',\r
-LASTNAME      VARCHAR(28) DEFAULT 'Chen' key,\r
-averylonglongfieldname X(1024) DEFAULT 'test',\r
-price         N(7.2)  DEFAULT '0.00',\r
-MYDATE        D      DEFDATE,\r
-BIGFELLOW     X      NOTNULL,\r
-TS            T      DEFTIMESTAMP";\r
-\r
-\r
-       $sqla = $dict->CreateDatabase('KUTU',array('postgres'=>"LOCATION='/u01/postdata'"));\r
-       $dict->SetSchema('KUTU');\r
-       \r
-       $sqli = ($dict->CreateTableSQL('testtable',$flds, $opts));\r
-       $sqla =& array_merge($sqla,$sqli);\r
-       \r
-       $sqli = $dict->CreateIndexSQL('idx','testtable','firstname,lastname',array('BITMAP','FULLTEXT','CLUSTERED','HASH'));\r
-       $sqla =& array_merge($sqla,$sqli);\r
-       $sqli = $dict->CreateIndexSQL('idx2','testtable','price,lastname');//,array('BITMAP','FULLTEXT','CLUSTERED'));\r
-       $sqla =& array_merge($sqla,$sqli);\r
-       \r
-       $addflds = array(array('height', 'F'),array('weight','F'));\r
-       $sqli = $dict->AddColumnSQL('testtable',$addflds);\r
-       $sqla =& array_merge($sqla,$sqli);\r
-       $addflds = array(array('height', 'F','NOTNULL'),array('weight','F','NOTNULL'));\r
-       $sqli = $dict->AlterColumnSQL('testtable',$addflds);\r
-       $sqla =& array_merge($sqla,$sqli);\r
-       \r
-       \r
-       printsqla($dbType,$sqla);\r
-       \r
-       if ($dbType == 'mysql') {\r
-               $db->Connect('localhost', "root", "", "test");\r
-               $dict->SetSchema('');\r
-               $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);\r
-               if ($sqla2) printsqla($dbType,$sqla2);\r
-       }\r
-               if ($dbType == 'postgres') {\r
-               $db->Connect('localhost', "tester", "test", "test");\r
-               $dict->SetSchema('');\r
-               $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);\r
-               if ($sqla2) printsqla($dbType,$sqla2);\r
-       }\r
-       \r
-}\r
-\r
-function printsqla($dbType,$sqla)\r
-{\r
-       print "<pre>";\r
-       //print_r($dict->MetaTables());\r
-       foreach($sqla as $s) {\r
-               $s = htmlspecialchars($s);\r
-               print "$s;\n";\r
-               if ($dbType == 'oci8') print "/\n";\r
-       }\r
-       print "</pre><hr>";\r
-}\r
-\r
-/***\r
-\r
-Generated SQL:\r
-\r
-mysql\r
-\r
-CREATE DATABASE KUTU;\r
-DROP TABLE KUTU.testtable;\r
-CREATE TABLE KUTU.testtable (\r
-id               INTEGER NOT NULL AUTO_INCREMENT,\r
-firstname        VARCHAR(30) DEFAULT 'Joan',\r
-lastname         VARCHAR(28) NOT NULL DEFAULT 'Chen',\r
-averylonglongfieldname LONGTEXT NOT NULL,\r
-price            NUMERIC(7,2) NOT NULL DEFAULT 0.00,\r
-MYDATE           DATE DEFAULT CURDATE(),\r
-                 PRIMARY KEY (id, lastname)\r
-)TYPE=ISAM;\r
-CREATE FULLTEXT INDEX idx ON KUTU.testtable (firstname,lastname);\r
-CREATE INDEX idx2 ON KUTU.testtable (price,lastname);\r
-ALTER TABLE KUTU.testtable  ADD height           DOUBLE;\r
-ALTER TABLE KUTU.testtable  ADD weight           DOUBLE;\r
-ALTER TABLE KUTU.testtable  MODIFY COLUMN height           DOUBLE NOT NULL;\r
-ALTER TABLE KUTU.testtable  MODIFY COLUMN weight           DOUBLE NOT NULL;\r
-\r
-\r
---------------------------------------------------------------------------------\r
-\r
-oci8\r
-\r
-CREATE USER KUTU IDENTIFIED BY tiger;\r
-/\r
-GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO KUTU;\r
-/\r
-DROP TABLE KUTU.testtable CASCADE CONSTRAINTS;\r
-/\r
-CREATE TABLE KUTU.testtable (\r
-id               NUMBER(16) NOT NULL,\r
-firstname        VARCHAR(30) DEFAULT 'Joan',\r
-lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,\r
-averylonglongfieldname CLOB NOT NULL,\r
-price            NUMBER(7,2) DEFAULT 0.00 NOT NULL,\r
-MYDATE           DATE DEFAULT TRUNC(SYSDATE),\r
-                 PRIMARY KEY (id, lastname)\r
-)TABLESPACE USERS;\r
-/\r
-DROP SEQUENCE KUTU.SEQ_testtable;\r
-/\r
-CREATE SEQUENCE KUTU.SEQ_testtable;\r
-/\r
-CREATE OR REPLACE TRIGGER KUTU.TRIG_SEQ_testtable BEFORE insert ON KUTU.testtable \r
-               FOR EACH ROW\r
-               BEGIN\r
-                 select KUTU.SEQ_testtable.nextval into :new.id from dual;\r
-               END;\r
-/\r
-CREATE BITMAP INDEX idx ON KUTU.testtable (firstname,lastname);\r
-/\r
-CREATE INDEX idx2 ON KUTU.testtable (price,lastname);\r
-/\r
-ALTER TABLE testtable ADD (\r
- height           NUMBER,\r
- weight           NUMBER);\r
-/\r
-ALTER TABLE testtable MODIFY(\r
- height           NUMBER NOT NULL,\r
- weight           NUMBER NOT NULL);\r
-/\r
-\r
-\r
---------------------------------------------------------------------------------\r
-\r
-postgres\r
-AlterColumnSQL not supported for PostgreSQL\r
-\r
-\r
-CREATE DATABASE KUTU LOCATION='/u01/postdata';\r
-DROP TABLE KUTU.testtable;\r
-CREATE TABLE KUTU.testtable (\r
-id               SERIAL,\r
-firstname        VARCHAR(30) DEFAULT 'Joan',\r
-lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,\r
-averylonglongfieldname TEXT NOT NULL,\r
-price            NUMERIC(7,2) DEFAULT 0.00 NOT NULL,\r
-MYDATE           DATE DEFAULT CURRENT_DATE,\r
-                 PRIMARY KEY (id, lastname)\r
-);\r
-CREATE INDEX idx ON KUTU.testtable USING HASH (firstname,lastname);\r
-CREATE INDEX idx2 ON KUTU.testtable (price,lastname);\r
-ALTER TABLE KUTU.testtable  ADD height           FLOAT8;\r
-ALTER TABLE KUTU.testtable  ADD weight           FLOAT8;\r
-\r
-\r
---------------------------------------------------------------------------------\r
-\r
-odbc_mssql\r
-\r
-CREATE DATABASE KUTU;\r
-DROP TABLE KUTU.testtable;\r
-CREATE TABLE KUTU.testtable (\r
-id               INT IDENTITY(1,1) NOT NULL,\r
-firstname        VARCHAR(30) DEFAULT 'Joan',\r
-lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,\r
-averylonglongfieldname TEXT NOT NULL,\r
-price            NUMERIC(7,2) DEFAULT 0.00 NOT NULL,\r
-MYDATE           DATETIME DEFAULT GetDate(),\r
-                 PRIMARY KEY (id, lastname)\r
-);\r
-CREATE CLUSTERED INDEX idx ON KUTU.testtable (firstname,lastname);\r
-CREATE INDEX idx2 ON KUTU.testtable (price,lastname);\r
-ALTER TABLE KUTU.testtable  ADD\r
- height           REAL,\r
- weight           REAL;\r
-ALTER TABLE KUTU.testtable  ALTER COLUMN height           REAL NOT NULL;\r
-ALTER TABLE KUTU.testtable  ALTER COLUMN weight           REAL NOT NULL;\r
-\r
-\r
---------------------------------------------------------------------------------\r
-*/\r
+<?php
+/*
+
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+       
+  Set tabs to 4 for best viewing.
+
+*/
+
+error_reporting(E_ALL);
+include_once('../adodb.inc.php');
+
+foreach(array('sybase','mysql','access','oci8','postgres','odbc_mssql','odbc','sybase','firebird','informix','db2') as $dbType) {
+       echo "<h3>$dbType</h3><p>";
+       $db = NewADOConnection($dbType);
+       $dict = NewDataDictionary($db);
+
+       if (!$dict) continue;
+       $dict->debug = 1;
+       
+       $opts = array('REPLACE','mysql' => 'TYPE=ISAM', 'oci8' => 'TABLESPACE USERS');
+       
+/*     $flds = array(
+               array('id',     'I',                                                            
+                                                       'AUTO','KEY'),
+                                                       
+               array('name' => 'firstname', 'type' => 'varchar','size' => 30,
+                                                       'DEFAULT'=>'Joan'),
+                                                       
+               array('lastname','varchar',28,
+                                                       'DEFAULT'=>'Chen','key'),
+                                                       
+               array('averylonglongfieldname','X',1024,
+                                                       'NOTNULL','default' => 'test'),
+                                                       
+               array('price','N','7.2',
+                                                       'NOTNULL','default' => '0.00'),
+                                                       
+               array('MYDATE', 'D', 
+                                                       'DEFDATE'),
+               array('TS','T',
+                                                       'DEFTIMESTAMP')
+       );*/
+       
+       $flds = "
+ID            I           AUTO KEY,
+FIRSTNAME     VARCHAR(30) DEFAULT 'Joan',
+LASTNAME      VARCHAR(28) DEFAULT 'Chen' key,
+averylonglongfieldname X(1024) DEFAULT 'test',
+price         N(7.2)  DEFAULT '0.00',
+MYDATE        D      DEFDATE,
+BIGFELLOW     X      NOTNULL,
+TS            T      DEFTIMESTAMP";
+
+
+       $sqla = $dict->CreateDatabase('KUTU',array('postgres'=>"LOCATION='/u01/postdata'"));
+       $dict->SetSchema('KUTU');
+       
+       $sqli = ($dict->CreateTableSQL('testtable',$flds, $opts));
+       $sqla =& array_merge($sqla,$sqli);
+       
+       $sqli = $dict->CreateIndexSQL('idx','testtable','firstname,lastname',array('BITMAP','FULLTEXT','CLUSTERED','HASH'));
+       $sqla =& array_merge($sqla,$sqli);
+       $sqli = $dict->CreateIndexSQL('idx2','testtable','price,lastname');//,array('BITMAP','FULLTEXT','CLUSTERED'));
+       $sqla =& array_merge($sqla,$sqli);
+       
+       $addflds = array(array('height', 'F'),array('weight','F'));
+       $sqli = $dict->AddColumnSQL('testtable',$addflds);
+       $sqla =& array_merge($sqla,$sqli);
+       $addflds = array(array('height', 'F','NOTNULL'),array('weight','F','NOTNULL'));
+       $sqli = $dict->AlterColumnSQL('testtable',$addflds);
+       $sqla =& array_merge($sqla,$sqli);
+       
+       
+       printsqla($dbType,$sqla);
+       
+       if (file_exists('d:\inetpub\wwwroot\php\phplens\adodb\adodb.inc.php'))
+       if ($dbType == 'mysql') {
+               $db->Connect('localhost', "root", "", "test");
+               $dict->SetSchema('');
+               $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);
+               if ($sqla2) printsqla($dbType,$sqla2);
+       }
+               if ($dbType == 'postgres') {
+               $db->Connect('localhost', "tester", "test", "test");
+               $dict->SetSchema('');
+               $sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);
+               if ($sqla2) printsqla($dbType,$sqla2);
+       }
+       
+}
+
+function printsqla($dbType,$sqla)
+{
+       print "<pre>";
+       //print_r($dict->MetaTables());
+       foreach($sqla as $s) {
+               $s = htmlspecialchars($s);
+               print "$s;\n";
+               if ($dbType == 'oci8') print "/\n";
+       }
+       print "</pre><hr>";
+}
+
+/***
+
+Generated SQL:
+
+mysql
+
+CREATE DATABASE KUTU;
+DROP TABLE KUTU.testtable;
+CREATE TABLE KUTU.testtable (
+id               INTEGER NOT NULL AUTO_INCREMENT,
+firstname        VARCHAR(30) DEFAULT 'Joan',
+lastname         VARCHAR(28) NOT NULL DEFAULT 'Chen',
+averylonglongfieldname LONGTEXT NOT NULL,
+price            NUMERIC(7,2) NOT NULL DEFAULT 0.00,
+MYDATE           DATE DEFAULT CURDATE(),
+                 PRIMARY KEY (id, lastname)
+)TYPE=ISAM;
+CREATE FULLTEXT INDEX idx ON KUTU.testtable (firstname,lastname);
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
+ALTER TABLE KUTU.testtable  ADD height           DOUBLE;
+ALTER TABLE KUTU.testtable  ADD weight           DOUBLE;
+ALTER TABLE KUTU.testtable  MODIFY COLUMN height           DOUBLE NOT NULL;
+ALTER TABLE KUTU.testtable  MODIFY COLUMN weight           DOUBLE NOT NULL;
+
+
+--------------------------------------------------------------------------------
+
+oci8
+
+CREATE USER KUTU IDENTIFIED BY tiger;
+/
+GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO KUTU;
+/
+DROP TABLE KUTU.testtable CASCADE CONSTRAINTS;
+/
+CREATE TABLE KUTU.testtable (
+id               NUMBER(16) NOT NULL,
+firstname        VARCHAR(30) DEFAULT 'Joan',
+lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,
+averylonglongfieldname CLOB NOT NULL,
+price            NUMBER(7,2) DEFAULT 0.00 NOT NULL,
+MYDATE           DATE DEFAULT TRUNC(SYSDATE),
+                 PRIMARY KEY (id, lastname)
+)TABLESPACE USERS;
+/
+DROP SEQUENCE KUTU.SEQ_testtable;
+/
+CREATE SEQUENCE KUTU.SEQ_testtable;
+/
+CREATE OR REPLACE TRIGGER KUTU.TRIG_SEQ_testtable BEFORE insert ON KUTU.testtable 
+               FOR EACH ROW
+               BEGIN
+                 select KUTU.SEQ_testtable.nextval into :new.id from dual;
+               END;
+/
+CREATE BITMAP INDEX idx ON KUTU.testtable (firstname,lastname);
+/
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
+/
+ALTER TABLE testtable ADD (
+ height           NUMBER,
+ weight           NUMBER);
+/
+ALTER TABLE testtable MODIFY(
+ height           NUMBER NOT NULL,
+ weight           NUMBER NOT NULL);
+/
+
+
+--------------------------------------------------------------------------------
+
+postgres
+AlterColumnSQL not supported for PostgreSQL
+
+
+CREATE DATABASE KUTU LOCATION='/u01/postdata';
+DROP TABLE KUTU.testtable;
+CREATE TABLE KUTU.testtable (
+id               SERIAL,
+firstname        VARCHAR(30) DEFAULT 'Joan',
+lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,
+averylonglongfieldname TEXT NOT NULL,
+price            NUMERIC(7,2) DEFAULT 0.00 NOT NULL,
+MYDATE           DATE DEFAULT CURRENT_DATE,
+                 PRIMARY KEY (id, lastname)
+);
+CREATE INDEX idx ON KUTU.testtable USING HASH (firstname,lastname);
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
+ALTER TABLE KUTU.testtable  ADD height           FLOAT8;
+ALTER TABLE KUTU.testtable  ADD weight           FLOAT8;
+
+
+--------------------------------------------------------------------------------
+
+odbc_mssql
+
+CREATE DATABASE KUTU;
+DROP TABLE KUTU.testtable;
+CREATE TABLE KUTU.testtable (
+id               INT IDENTITY(1,1) NOT NULL,
+firstname        VARCHAR(30) DEFAULT 'Joan',
+lastname         VARCHAR(28) DEFAULT 'Chen' NOT NULL,
+averylonglongfieldname TEXT NOT NULL,
+price            NUMERIC(7,2) DEFAULT 0.00 NOT NULL,
+MYDATE           DATETIME DEFAULT GetDate(),
+                 PRIMARY KEY (id, lastname)
+);
+CREATE CLUSTERED INDEX idx ON KUTU.testtable (firstname,lastname);
+CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
+ALTER TABLE KUTU.testtable  ADD
+ height           REAL,
+ weight           REAL;
+ALTER TABLE KUTU.testtable  ALTER COLUMN height           REAL NOT NULL;
+ALTER TABLE KUTU.testtable  ALTER COLUMN weight           REAL NOT NULL;
+
+
+--------------------------------------------------------------------------------
+*/
+
+echo "<h1>Test XML Schema</h1>";
+$ff = file('xmlschema.xml');
+echo "<pre>";
+foreach($ff as $xml) echo htmlspecialchars($xml);
+echo "</pre>";
+include_once('test-xmlschema.php');
 ?>
\ No newline at end of file
index b592757ae292660fa5ea1c224ec1282c2521a1a2..029669f519185112dc31ebba0af6e75fa56af837 100644 (file)
@@ -1,10 +1,63 @@
 <?php\r
+\r
+function getmicrotime()\r
+{\r
+       $t = microtime();\r
+       $t = explode(' ',$t);\r
+       return (float)$t[1]+ (float)$t[0];\r
+}\r
+\r
+function doloop()\r
+{\r
+global $db,$MAX;\r
+       \r
+       $sql = "select id,firstname,lastname from adoxyz where \r
+               firstname not like ? and lastname not like ? and id=?";\r
+       $offset = 0;\r
+       /*$sql = "select * from juris9.employee join juris9.emp_perf_plan on epp_empkey = emp_id \r
+               where emp_name not like ? and emp_name not like ? and emp_id=28000+?";\r
+       $offset = 28000;*/\r
+       for ($i=1; $i <= $MAX; $i++) {\r
+               $db->Param(false);\r
+               $x = (rand() % 10) + 1;\r
+               $db->debug= ($i==1);\r
+               $id = $db->GetOne($sql,\r
+                       array('Z%','Z%',$x));\r
+               if($id != $offset+$x) {\r
+                       print "<p>Error at $x";\r
+                       break;\r
+               }\r
+       }\r
+}\r
+\r
 include_once('../adodb.inc.php');\r
 $db = NewADOConnection('postgres7');\r
-$db->Connect('localhost','tester','test','test') || die("failed connection");\r
+$db->PConnect('localhost','tester','test','test') || die("failed connection");\r
 \r
 $enc = "GIF89a%01%00%01%00%80%FF%00%C0%C0%C0%00%00%00%21%F9%04%01%00%00%00%00%2C%00%00%00%00%01%00%01%00%00%01%012%00%3Bt_clear.gif%0D";\r
 $val = rawurldecode($enc);\r
+\r
+$MAX = 1000;\r
+\r
+adodb_pr($db->ServerInfo());\r
+\r
+echo "<h4>Testing PREPARE/EXECUTE PLAN</h4>";\r
+\r
+\r
+$db->_bindInputArray = true; // requires postgresql 7.3+ and ability to modify database\r
+$t = getmicrotime();\r
+doloop();\r
+echo '<p>',$MAX,' times, with plan=',getmicrotime() - $t,'</p>';\r
+\r
+\r
+$db->_bindInputArray = false;\r
+$t = getmicrotime();\r
+doloop();\r
+echo '<p>',$MAX,' times, no plan=',getmicrotime() - $t,'</p>';\r
+\r
+\r
+\r
+echo "<h4>Testing UPDATEBLOB</h4>";\r
 $db->debug=1;\r
 \r
 ### TEST BEGINS\r
index 033f667a243b6a295e12fc0ec57c6ae0e0129b57..c735aa7386546ad8f76f0e33f3c117d969907335 100644 (file)
@@ -1,56 +1,58 @@
-<?php\r
-/*\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 8.\r
- */\r
-\r
-\r
-error_reporting(E_ALL);\r
-\r
-$path = dirname(__FILE__);\r
-\r
-include("$path/../adodb-exceptions.inc.php");\r
-include("$path/../adodb.inc.php");     \r
-\r
-try {\r
-\r
-$dbt = 'oci8';\r
-\r
-switch($dbt) {\r
-case 'oci8':\r
-       $db = NewADOConnection("oci8");\r
-       $db->Connect('','scott','natsoft');\r
-       break;\r
-default:\r
-case 'mysql':\r
-       $db = NewADOConnection("mysql");\r
-       $db->Connect('localhost','root','','test');\r
-       break;\r
-}\r
-\r
-$db->debug=1;\r
-\r
-$cnt = $db->GetOne("select count(*) from adoxyz");\r
-$rs = $db->Execute("select * from adoxyz order by id");\r
-\r
-$i = 0;\r
-foreach($rs as  $v) {\r
-       $i += 1;\r
-       echo "$i: "; adodb_pr($v); adodb_pr($rs->fields);\r
-       flush();\r
-}\r
-\r
-if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n");\r
-\r
-\r
-$rs = $db->Execute("select bad from badder");\r
-\r
-} catch (exception $e) {\r
-       adodb_pr($e);\r
-       $e = adodb_backtrace($e->trace);\r
-}\r
-\r
+<?php
+/*
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+ */
+
+
+error_reporting(E_ALL);
+
+$path = dirname(__FILE__);
+
+include("$path/../adodb-exceptions.inc.php");
+include("$path/../adodb.inc.php");     
+
+echo "<h3>PHP ".PHP_VERSION."</h3>\n";
+try {
+
+$dbt = 'oci8';
+
+switch($dbt) {
+case 'oci8':
+       $db = NewADOConnection("oci8");
+       $db->Connect('','scott','natsoft');
+       break;
+default:
+case 'mysql':
+       $db = NewADOConnection("mysql");
+       $db->Connect('localhost','root','','test');
+       break;
+}
+
+$db->debug=1;
+
+$cnt = $db->GetOne("select count(*) from adoxyz");
+$rs = $db->Execute("select * from adoxyz order by id");
+
+$i = 0;
+foreach($rs as  $v) {
+       $i += 1;
+       echo "$i: "; adodb_pr($v); adodb_pr($rs->fields);
+       flush();
+}
+
+if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n");
+
+
+$rs = $db->Execute("select bad from badder");
+
+} catch (exception $e) {
+       adodb_pr($e);
+       echo "<h3>adodb_backtrace:</h3>\n";
+       $e = adodb_backtrace($e->gettrace());
+}
+
 ?>
\ No newline at end of file
index aa3b4e8be9bbe544a28082a25a058cdab704ce30..cb3f1fb65f9914d900bc6e88d7d0990629e3bc65 100644 (file)
@@ -1,34 +1,34 @@
-<?PHP\r
-\r
-// V4.11 27 Jan 2004\r
-\r
-error_reporting(E_ALL);\r
-\r
-require( "../adodb-xmlschema.inc.php" );\r
-\r
-// To build the schema, start by creating a normal ADOdb connection:\r
-$db = ADONewConnection( 'mysql' );\r
-$db->Connect( 'localhost', 'root', '', 'schematest' );\r
-\r
-// To create a schema object and build the query array.\r
-$schema = new adoSchema( $db );\r
-\r
-// To upgrade an existing schema object, use the following \r
-// To upgrade an existing database to the provided schema,\r
-// uncomment the following line:\r
-#$schema->upgradeSchema();\r
-\r
-// Build the SQL array\r
-$sql = $schema->ParseSchema( "xmlschema.xml" );\r
-\r
-print "Here's the SQL to do the build:\n<pre>";\r
-print_r( $sql );\r
-print "</pre>\n";\r
-\r
-// Execute the SQL on the database\r
-//$result = $schema->ExecuteSchema( $sql );\r
-\r
-// Finally, clean up after the XML parser\r
-// (PHP won't do this for you!)\r
-//$schema->Destroy();\r
+<?PHP
+
+// V4.20 22 Feb 2004
+
+error_reporting(E_ALL);
+
+require( "../adodb-xmlschema.inc.php" );
+
+// To build the schema, start by creating a normal ADOdb connection:
+$db = ADONewConnection( 'mysql' );
+$db->Connect( 'localhost', 'root', '', 'schematest' );
+
+// To create a schema object and build the query array.
+$schema = new adoSchema( $db );
+
+// To upgrade an existing schema object, use the following 
+// To upgrade an existing database to the provided schema,
+// uncomment the following line:
+#$schema->upgradeSchema();
+
+// Build the SQL array
+$sql = $schema->ParseSchema( "xmlschema.xml" );
+
+print "Here's the SQL to do the build:\n<pre>";
+print_r( $sql );
+print "</pre>\n";
+
+// Execute the SQL on the database
+//$result = $schema->ExecuteSchema( $sql );
+
+// Finally, clean up after the XML parser
+// (PHP won't do this for you!)
+//$schema->Destroy();
 ?>
\ No newline at end of file
index d1d6fe3f58aa028c5462364e7da34c6a656d5ba1..fdcc8ad5da104fce5dd2224d795e288ec0ed4511 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-  Set tabs to 4 for best viewing.\r
-       \r
-  Latest version is available at http://php.weblogs.com/\r
-*/\r
-\r
-error_reporting(E_ALL);\r
-$ADODB_FLUSH = true;\r
-\r
-define('ADODB_ASSOC_CASE',0);\r
-\r
-include_once('../adodb-pear.inc.php');\r
-//--------------------------------------------------------------------------------------\r
-//define('ADODB_ASSOC_CASE',1);\r
-//\r
-function Err($msg)\r
-{\r
-       print "<b>$msg</b><br>";\r
-       flush();\r
-}\r
-\r
-function CheckWS($conn)\r
-{\r
-global $ADODB_EXTENSION;\r
-\r
-       include_once('../session/adodb-session.php');\r
-       \r
-       $saved = $ADODB_EXTENSION;\r
-       $db = ADONewConnection($conn);\r
-       $ADODB_EXTENSION = $saved;\r
-       if (headers_sent()) {\r
-               print "<p><b>White space detected in adodb-$conn.inc.php or include file...</b></p>";\r
-               die();\r
-       }\r
-}\r
-\r
-function do_strtolower(&$arr)\r
-{\r
-       foreach($arr as $k => $v) {\r
-               $arr[$k] = strtolower($v);\r
-       }\r
-}\r
-\r
-\r
-function CountExecs($db, $sql, $inputarray)\r
-{\r
-global $EXECS;  $EXECS++;\r
-}\r
-\r
-function CountCachedExecs($db, $secs2cache, $sql, $inputarray)\r
-{\r
-global $CACHED; $CACHED++;\r
-}\r
-\r
-// the table creation code is specific to the database, so we allow the user \r
-// to define their own table creation stuff\r
-\r
-function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")\r
-{\r
-GLOBAL $ADODB_vers,$ADODB_CACHE_DIR,$ADODB_FETCH_MODE, $HTTP_GET_VARS,$ADODB_COUNTRECS;\r
-\r
-?>     <form method=GET>\r
-       </p>\r
-       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>\r
-       </p>\r
-<?php  \r
-       $create =false;\r
-       /*$ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-       \r
-       $rs = $db->Execute('select lastname,firstname,lastname,id from adoxyz');\r
-       $arr = $rs->GetAssoc();\r
-       echo "<pre>";print_r($arr);\r
-       die();*/\r
-       \r
-       GLOBAL $EXECS, $CACHED;\r
-       \r
-       $EXECS = 0;\r
-       $CACHED = 0;\r
-       if ((rand()%3) == 0) @$db->Execute("delete from adodb_logsql");\r
-       $db->debug=1;\r
-       \r
-       $db->fnExecute = 'CountExecs';\r
-       $db->fnCacheExecute = 'CountCachedExecs';\r
-       \r
-       if (empty($_GET['nolog'])) {\r
-               echo "<h3>SQL Logging enabled</h3>";\r
-               $db->LogSQL();/*\r
-               $sql =\r
-"SELECT t1.sid, t1.sid, t1.title, t1.hometext, t1.notes, t1.aid, t1.informant, \r
-t2.url, t2.email, t1.catid, t3.title, t1.topic, t4.topicname, t4.topicimage, \r
-t4.topictext, t1.score, t1.ratings, t1.counter, t1.comments, t1.acomm \r
-FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_topics` `t4` \r
-       WHERE ((t2.aid=t1.aid) AND (t3.catid=t1.catid) AND (t4.topicid=t1.topic) \r
-       AND ((t1.alanguage='german') OR (t1.alanguage='')) AND (t1.ihome='0')) \r
-       ORDER BY t1.time DESC";\r
-               $db->SelectLimit($sql);\r
-               echo $db->ErrorMsg();*/\r
-       }\r
-       $ADODB_CACHE_DIR = dirname(TempNam('/tmp','testadodb'));\r
-       $db->debug = false;\r
-       \r
-       //print $db->UnixTimeStamp('2003-7-22 23:00:00');\r
-       \r
-       $phpv = phpversion();\r
-       if (defined('ADODB_EXTENSION')) $ext = ' &nbsp; Extension '.ADODB_EXTENSION.' installed';\r
-       else $ext = '';\r
-       print "<h3>ADODB Version: $ADODB_vers Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i> &nbsp; PHP: $phpv $ext</h3>";\r
-       flush();\r
-       $arr = $db->ServerInfo();\r
-       print_r($arr);\r
-       echo "<br>";\r
-       $e = error_reporting(E_ALL-E_WARNING);\r
-       flush();\r
-       print "<i>date1</i> (1969-02-20) = ".$db->DBDate('1969-2-20');\r
-       print "<br><i>date1</i> (1999-02-20) = ".$db->DBDate('1999-2-20');\r
-       print "<br><i>date1.1</i> 1999 = ".$db->DBDate("'1999'");\r
-       print "<br><i>date2</i> (1970-1-2) = ".$db->DBDate(24*3600)."<p>";\r
-       print "<i>ts1</i> (1999-02-20 13:40:50) = ".$db->DBTimeStamp('1999-2-20 1:40:50 pm');\r
-       print "<br><i>ts1.1</i> (1999-02-20 13:40:00) = ".$db->DBTimeStamp('1999-2-20 13:40');\r
-       print "<br><i>ts2</i> (1999-02-20) = ".$db->DBTimeStamp('1999-2-20');\r
-       print "<br><i>ts3</i> (1970-1-2 +/- timezone) = ".$db->DBTimeStamp(24*3600);\r
-       print "<br> Fractional TS (1999-2-20 13:40:50.91): ".$db->DBTimeStamp($db->UnixTimeStamp('1999-2-20 13:40:50.91+1'));\r
-        $dd = $db->UnixDate('1999-02-20');\r
-       print "<br>unixdate</i> 1999-02-20 = ".date('Y-m-d',$dd)."<p>";\r
-       print "<br><i>ts4</i> =".($db->UnixTimeStamp("19700101000101")+8*3600);\r
-       print "<br><i>ts5</i> =".$db->DBTimeStamp($db->UnixTimeStamp("20040110092123"));\r
-       print "<br><i>ts6</i> =".$db->UserTimeStamp("20040110092123");\r
-       print "<br><i>ts6</i> =".$db->DBTimeStamp("20040110092123");\r
-       flush();\r
-       // mssql too slow in failing bad connection\r
-       if (false && $db->databaseType != 'mssql') {\r
-               print "<p>Testing bad connection. Ignore following error msgs:<br>";\r
-               $db2 = ADONewConnection();\r
-               $rez = $db2->Connect("bad connection");\r
-               $err = $db2->ErrorMsg();\r
-               print "<i>Error='$err'</i></p>";\r
-               if ($rez) print "<b>Cannot check if connection failed.</b> The Connect() function returned true.</p>";\r
-       }\r
-       error_reporting($e);\r
-       flush();\r
-       \r
-       //$ADODB_COUNTRECS=false;\r
-       $rs=$db->Execute('select * from adoxyz order by id');\r
-\r
-       //print_r($rs);\r
-       //OCIFetchStatement($rs->_queryID,$rez,0,-1);//,OCI_ASSOC | OCI_FETCHSTATEMENT_BY_ROW);\r
-       //print_r($rez);\r
-       //die();\r
-       if($rs === false) $create = true;\r
-       else $rs->Close();\r
-               \r
-       //if ($db->databaseType !='vfp') $db->Execute("drop table ADOXYZ");\r
-       \r
-       if ($create) {\r
-               if (false && $db->databaseType == 'ibase') {\r
-                       print "<b>Please create the following table for testing:</b></p>$createtab</p>";\r
-                       return;\r
-               } else {\r
-                       $db->debug = 1;\r
-                       $e = error_reporting(E_ALL-E_WARNING);\r
-                       $db->Execute($createtab);\r
-                       error_reporting($e);\r
-               }\r
-       }\r
-       $rs = &$db->Execute("delete from ADOXYZ"); // some ODBC drivers will fail the drop so we delete\r
-       if ($rs) {\r
-               if(! $rs->EOF) print "<b>Error: </b>RecordSet returned by Execute('delete...') should show EOF</p>";\r
-               $rs->Close();\r
-       } else print "err=".$db->ErrorMsg();\r
-\r
-       print "<p>Test select on empty table</p>";\r
-       $rs = &$db->Execute("select * from ADOXYZ where id=9999");\r
-       if ($rs && !$rs->EOF) print "<b>Error: </b>RecordSet returned by Execute(select...') on empty table should show EOF</p>";\r
-       if ($rs) $rs->Close();\r
-       flush();\r
-       //$db->debug=true;      \r
-       print "<p>Testing Commit: ";\r
-       $time = $db->DBDate(time());\r
-       if (!$db->BeginTrans()) {\r
-               print '<b>Transactions not supported</b></p>';\r
-               if ($db->hasTransactions) Err("hasTransactions should be false");\r
-       } else { /* COMMIT */\r
-               if (!$db->hasTransactions) Err("hasTransactions should be true");\r
-               if ($db->transCnt != 1) Err("Invalid transCnt = $db->transCnt (should be 1)");\r
-               $rs = $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values (99,'Should Not','Exist (Commit)',$time)");\r
-               if ($rs && $db->CommitTrans()) {\r
-                       $rs->Close();\r
-                       $rs = &$db->Execute("select * from ADOXYZ where id=99");\r
-                       if ($rs === false || $rs->EOF) {\r
-                               print '<b>Data not saved</b></p>';\r
-                               $rs = &$db->Execute("select * from ADOXYZ where id=99");\r
-                               print_r($rs);\r
-                               die();\r
-                       } else print 'OK</p>';\r
-                       if ($rs) $rs->Close();\r
-               } else {\r
-                       if (!$rs) {\r
-                               print "<b>Insert failed</b></p>";\r
-                               $db->RollbackTrans();\r
-                       } else print "<b>Commit failed</b></p>";\r
-               }\r
-               if ($db->transCnt != 0) Err("Invalid transCnt = $db->transCnt (should be 0)");\r
-               \r
-               /* ROLLBACK */  \r
-               if (!$db->BeginTrans()) print "<p><b>Error in BeginTrans</b>()</p>";\r
-               print "<p>Testing Rollback: ";\r
-               $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values (100,'Should Not','Exist (Rollback)',$time)");\r
-               if ($db->RollbackTrans()) {\r
-                       $rs = $db->Execute("select * from ADOXYZ where id=100");\r
-                       if ($rs && !$rs->EOF) print '<b>Fail: Data should rollback</b></p>';\r
-                       else print 'OK</p>';\r
-                       if ($rs) $rs->Close();\r
-               } else\r
-                       print "<b>Commit failed</b></p>";\r
-                       \r
-               $rs = &$db->Execute('delete from ADOXYZ where id>50');\r
-               if ($rs) $rs->Close();\r
-               \r
-               if ($db->transCnt != 0) Err("Invalid transCnt = $db->transCnt (should be 0)");\r
-       }\r
-       \r
-       if (1) {\r
-               print "<p>Testing MetaDatabases()</p>";\r
-               print_r( $db->MetaDatabases());\r
-               \r
-               print "<p>Testing MetaTables() and MetaColumns()</p>";\r
-               $a = $db->MetaTables();\r
-               if ($a===false) print "<b>MetaTables not supported</b></p>";\r
-               else {\r
-                       print "Array of tables and views: "; \r
-                       foreach($a as $v) print " ($v) ";\r
-                       print '</p>';\r
-               }\r
-               \r
-               $a = $db->MetaTables('VIEW');\r
-               if ($a===false) print "<b>MetaTables not supported</b></p>";\r
-               else {\r
-                       print "Array of views: "; \r
-                       foreach($a as $v) print " ($v) ";\r
-                       print '</p>';\r
-               }\r
-               \r
-               $a = $db->MetaTables(false,false,'aDo%');\r
-               if ($a===false) print "<b>MetaTables not supported</b></p>";\r
-               else {\r
-                       print "Array of ado%: "; \r
-                       foreach($a as $v) print " ($v) ";\r
-                       print '</p>';\r
-               }\r
-               \r
-               $a = $db->MetaTables('TABLE');\r
-               if ($a===false) print "<b>MetaTables not supported</b></p>";\r
-               else {\r
-                       print "Array of tables: "; \r
-                       foreach($a as $v) print " ($v) ";\r
-                       print '</p>';\r
-               }\r
-               \r
-               $db->debug=1;\r
-               $a = $db->MetaColumns('ADOXYZ');\r
-               if ($a===false) print "<b>MetaColumns not supported</b></p>";\r
-               else {\r
-                       print "<p>Columns of ADOXYZ: <font size=1><br>";\r
-                       foreach($a as $v) {print_r($v); echo "<br>";}\r
-                       echo "</font>";\r
-               }\r
-               \r
-               print "<p>Testing MetaIndexes</p>";\r
-               $a = $db->MetaIndexes('ADOXYZ',true);\r
-               if ($a===false) print "<b>MetaIndexes not supported</b></p>";\r
-               else {\r
-                       print "<p>Indexes of ADOXYZ: <font size=1><br>";\r
-                       foreach($a as $v) {print_r($v); echo "<br>";}\r
-                       echo "</font>";\r
-               }\r
-               print "<p>Testing MetaPrimaryKeys</p>";\r
-               $a = $db->MetaPrimaryKeys('ADOXYZ');\r
-               var_dump($a);\r
-       }\r
-       $rs = &$db->Execute('delete from ADOXYZ');\r
-       if ($rs) $rs->Close();\r
-       \r
-       $db->debug = false;\r
-       \r
-       \r
-       switch ($db->databaseType) {\r
-       case 'postgres7':\r
-       case 'postgres64':\r
-       case 'postgres':\r
-       case 'ibase':\r
-               print "<p>Encode=".$db->BlobEncode("abc\0d\"'\r
-ef")."</p>";//'\r
-\r
-               print "<p>Testing Foreign Keys</p>";\r
-               $arr = $db->MetaForeignKeys('adoxyz',false,true);\r
-               print_r($arr);\r
-               if (!$arr) Err("Bad MetaForeignKeys");\r
-               break;\r
-       \r
-       case 'odbc_mssql':\r
-       case 'mssqlpo':\r
-               print "<p>Testing Foreign Keys</p>";\r
-               $arr = $db->MetaForeignKeys('Orders',false,true);\r
-               print_r($arr);\r
-               if (!$arr) Err("Bad MetaForeignKeys");\r
-               if ($db->databaseType == 'odbc_mssql') break;\r
-       \r
-       case 'mssql': \r
-       \r
-               \r
-/*\r
-ASSUME Northwind available...\r
-\r
-CREATE PROCEDURE SalesByCategory\r
-       @CategoryName nvarchar(15), @OrdYear nvarchar(4) = '1998'\r
-AS\r
-IF @OrdYear != '1996' AND @OrdYear != '1997' AND @OrdYear != '1998' \r
-BEGIN\r
-       SELECT @OrdYear = '1998'\r
-END\r
-\r
-SELECT ProductName,\r
-       TotalPurchase=ROUND(SUM(CONVERT(decimal(14,2), OD.Quantity * (1-OD.Discount) * OD.UnitPrice)), 0)\r
-FROM [Order Details] OD, Orders O, Products P, Categories C\r
-WHERE OD.OrderID = O.OrderID \r
-       AND OD.ProductID = P.ProductID \r
-       AND P.CategoryID = C.CategoryID\r
-       AND C.CategoryName = @CategoryName\r
-       AND SUBSTRING(CONVERT(nvarchar(22), O.OrderDate, 111), 1, 4) = @OrdYear\r
-GROUP BY ProductName\r
-ORDER BY ProductName\r
-GO\r
-*/\r
-               print "<h4>Testing Stored Procedures for mssql</h4>";\r
-               $saved = $db->debug;\r
-               $db->debug=true;\r
-               \r
-               $cat = 'Dairy Products';\r
-               $yr = '1998';\r
-               \r
-               $stmt = $db->PrepareSP('SalesByCategory');\r
-               $db->InParameter($stmt,$cat,'CategoryName');\r
-               $db->InParameter($stmt,$yr,'OrdYear');\r
-               $rs = $db->Execute($stmt);\r
-               rs2html($rs);\r
-               \r
-               $cat = 'Grains/Cereals';\r
-               $yr = 1998;\r
-               \r
-               $stmt = $db->PrepareSP('SalesByCategory');\r
-               $db->InParameter($stmt,$cat,'CategoryName');\r
-               $db->InParameter($stmt,$yr,'OrdYear');\r
-               $rs = $db->Execute($stmt);\r
-               rs2html($rs);\r
-               \r
-               /*\r
-               Test out params - works in 4.2.3 but not 4.3.0???:\r
-               \r
-                       CREATE PROCEDURE at_date_interval \r
-                               @days INTEGER, \r
-                               @start VARCHAR(20) OUT, \r
-                               @end VARCHAR(20) OUT    \r
-                       AS \r
-                       BEGIN \r
-                               set @start = CONVERT(VARCHAR(20), getdate(), 101) \r
-                               set @end =CONVERT(VARCHAR(20), dateadd(day, @days, getdate()), 101 ) \r
-                       END\r
-                       GO\r
-               */\r
-               $db->debug=1;\r
-               $stmt = $db->PrepareSP('at_date_interval');\r
-               $days = 10;\r
-               $begin_date = '';\r
-               $end_date = '';\r
-               $db->InParameter($stmt,$days,'days', 4, SQLINT4); \r
-               $db->OutParameter($stmt,$begin_date,'start', 20, SQLVARCHAR ); \r
-               $db->OutParameter($stmt,$end_date,'end', 20, SQLVARCHAR ); \r
-               $db->Execute($stmt);\r
-               if (empty($begin_date) or empty($end_date)) {\r
-                       Err("MSSQL SP Test for OUT Failed");\r
-                       print "begin=$begin_date end=$end_date<p>";\r
-               } else print "(Today +10days) = (begin=$begin_date end=$end_date)<p>";\r
-       \r
-               $db->debug = $saved;\r
-               break;\r
-       case 'oci8': \r
-       case 'oci8po':\r
-               $saved = $db->debug;\r
-               $db->debug=true;\r
-               \r
-               print "<h4>Testing Foreign Keys</h4>";\r
-               $arr = $db->MetaForeignKeys('emp');\r
-               print_r($arr);\r
-               if (!$arr) Err("Bad MetaForeignKeys");\r
-               print "<h4>Testing Cursor Variables</h4>";\r
-/*\r
--- TEST PACKAGE\r
-CREATE OR REPLACE PACKAGE adodb AS\r
-TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;\r
-PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);\r
-PROCEDURE data_out(input IN varchar, output OUT varchar); \r
-END adodb;\r
-/\r
-\r
-CREATE OR REPLACE PACKAGE BODY adodb AS\r
-PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS\r
-       BEGIN\r
-               OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;\r
-       END open_tab;\r
-       \r
-PROCEDURE data_out(input IN varchar, output OUT varchar) IS\r
-       BEGIN\r
-               output := 'Cinta Hati '||input;\r
-       END;\r
-END adodb;\r
-/\r
-*/\r
-               $stmt = $db->Prepare("BEGIN adodb.open_tab(:RS,'A%'); END;");\r
-               $db->InParameter($stmt, $cur, 'RS', -1, OCI_B_CURSOR);\r
-               $rs = $db->Execute($stmt);\r
-       \r
-               if ($rs && !$rs->EOF) {\r
-                       print "Test 1 RowCount: ".$rs->RecordCount()."<p>";\r
-               } else {\r
-                       print "<b>Error in using Cursor Variables 1</b><p>";\r
-               }\r
-               \r
-               \r
-               print "<h4>Testing Stored Procedures for oci8</h4>";\r
-               \r
-               $stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");\r
-               $a1 = 'Malaysia';\r
-               //$a2 = ''; # a2 doesn't even need to be defined!\r
-               $db->InParameter($stmt,$a1,'a1');\r
-               $db->OutParameter($stmt,$a2,'a2');\r
-               $rs = $db->Execute($stmt);\r
-               if ($rs) {\r
-                       if ($a2 !== 'Cinta Hati Malaysia') print "<b>Stored Procedure Error: a2 = $a2</b><p>";\r
-                       else echo  "OK: a2=$a2<p>";\r
-               } else {\r
-                       print "<b>Error in using Stored Procedure IN/Out Variables</b><p>";\r
-               }\r
-               \r
-               \r
-               $tname = 'A%';\r
-               \r
-               $stmt = $db->PrepareSP('select * from tab where tname like :tablename');\r
-               $db->Parameter($stmt,$tname,'tablename');\r
-               $rs = $db->Execute($stmt);\r
-               rs2html($rs);\r
-               \r
-               $db->debug = $saved;\r
-               break;\r
-       \r
-       default:\r
-               break;\r
-       }\r
-       $arr = array(\r
-               array(1,'Caroline','Miranda'),\r
-               array(2,'John','Lim'),\r
-               array(3,'Wai Hun','See')\r
-       );\r
-       $db->debug=1;\r
-       print "<p>Testing Bulk Insert of 3 rows</p>";\r
-\r
-       $sql = "insert into ADOXYZ (id,firstname,lastname) values (?,?,?)";\r
-       $db->StartTrans();\r
-       $db->Execute($sql,$arr);\r
-       $db->CompleteTrans();\r
-       $rs = $db->Execute('select * from ADOXYZ order by id');\r
-       if ($rs->RecordCount() != 3) Err("Bad bulk insert");\r
-       rs2html($rs);\r
-       \r
-       $db->Execute('delete from ADOXYZ');\r
-               \r
-       print "<p>Inserting 50 rows</p>";\r
-\r
-       for ($i = 0; $i < 5; $i++) {    \r
-\r
-       $time = $db->DBDate(time());\r
-       if (empty($HTTP_GET_VARS['hide'])) $db->debug = true;\r
-       switch($db->databaseType){\r
-       case 'mssqlpo':\r
-       case 'mssql':\r
-               $sqlt = "CREATE TABLE mytable (\r
-  row1 INT  IDENTITY(1,1) NOT NULL,\r
-  row2 varchar(16),\r
-  PRIMARY KEY  (row1))";\r
-               //$db->debug=1;\r
-               if (!$db->Execute("delete from mytable")) \r
-                       $db->Execute($sqlt);\r
-                       \r
-               $ok = $db->Execute("insert into mytable (row2) values ('test')");\r
-               $ins_id=$db->Insert_ID();\r
-               echo "Insert ID=";var_dump($ins_id);\r
-               if ($ins_id == 0) Err("Bad Insert_ID()");\r
-               $ins_id2 = $db->GetOne("select row1 from mytable");\r
-               if ($ins_id != $ins_id2) Err("Bad Insert_ID() 2");\r
-               \r
-               $arr = array(0=>'Caroline',1=>'Miranda');\r
-               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)";\r
-               break;\r
-               \r
-       case 'mysql':\r
-               $sqlt = "CREATE TABLE `mytable` (\r
-  `row1` int(11) NOT NULL auto_increment,\r
-  `row2` varchar(16) NOT NULL default '',\r
-  PRIMARY KEY  (`row1`),\r
-  KEY `myindex` (`row1`,`row2`)\r
-) ";\r
-               if (!$db->Execute("delete from mytable")) \r
-                       $db->Execute($sqlt);\r
-                       \r
-               $ok = $db->Execute("insert into mytable (row2) values ('test')");\r
-               $ins_id=$db->Insert_ID();\r
-               echo "Insert ID=";var_dump($ins_id);\r
-               if ($ins_id == 0) Err("Bad Insert_ID()");\r
-               $ins_id2 = $db->GetOne("select row1 from mytable");\r
-               if ($ins_id != $ins_id2) Err("Bad Insert_ID() 2");\r
-               \r
-       default:\r
-               $arr = array(0=>'Caroline',1=>'Miranda');\r
-               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)";\r
-               break;\r
-       \r
-       case 'oci8':\r
-       case 'oci805':\r
-               $arr = array('first'=>'Caroline','last'=>'Miranda');\r
-               $amt = rand() % 100;\r
-               $sql = "insert into ADOXYZ (id,firstname,lastname,created,amount) values ($i*10+0,:first,:last,$time,$amt)";            \r
-               break;\r
-       }\r
-       if ($i & 1) {\r
-               $sql = $db->Prepare($sql);\r
-       }\r
-       $rs = $db->Execute($sql,$arr);\r
-               \r
-       if ($rs === false) Err( 'Error inserting with parameters');\r
-       else $rs->Close();\r
-       $db->debug = false;\r
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+1,'John','Lim',$time)");\r
-       /*$ins_id=$db->Insert_ID();\r
-       echo "Insert ID=";var_dump($ins_id);*/\r
-       if ($db->databaseType == 'mysql') if ($ins_id == 0) Err('Bad Insert_ID');\r
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+2,'Mary','Lamb',$time )");\r
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+3,'George','Washington',$time )");\r
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+4,'Mr. Alan','Tam',$time )");\r
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+5,'Alan',".$db->quote("Turing'ton").",$time )");\r
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created)values ($i*10+6,'Serena','Williams',$time )");\r
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+7,'Yat Sun','Sun',$time )");\r
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+8,'Wai Hun','See',$time )");\r
-       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+9,'Steven','Oey',$time )");\r
-       } // for\r
-       if (1) {\r
-       $db->debug=1;\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-       $cnt = $db->GetOne("select count(*) from ADOXYZ");\r
-       $rs = $db->Execute('update ADOXYZ set id=id+1');        \r
-       if (!is_object($rs)) {\r
-               print_r($rs);\r
-               err("Update should return object");\r
-       }\r
-       if (!$rs) err("Update generated error");\r
-       \r
-       $nrows = $db->Affected_Rows();   \r
-       if ($nrows === false) print "<p><b>Affected_Rows() not supported</b></p>";\r
-       else if ($nrows != $cnt)  print "<p><b>Affected_Rows() Error: $nrows returned (should be 50) </b></p>";\r
-       else print "<p>Affected_Rows() passed</p>";\r
-       }\r
-       $db->debug = false;\r
-       \r
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
- //////////////////////////////////////////////////////////////////////////////////////////\r
-       \r
-       $rs = $db->Execute("select * from ADOXYZ where firstname = 'not known'");\r
-       if (!$rs ||  !$rs->EOF) print "<p><b>Error on empty recordset</b></p>";\r
-       else if ($rs->RecordCount() != 0) {\r
-               print "<p><b>Error on RecordCount. Should be 0. Was ".$rs->RecordCount()."</b></p>"; \r
-               print_r($rs->fields);\r
-       }\r
-       if ($db->databaseType !== 'odbc') {\r
-               $rs = &$db->Execute("select id,firstname,lastname,created,".$db->random." from ADOXYZ order by id");\r
-               if ($rs) {\r
-                       if ($rs->RecordCount() != 50) {\r
-                               print "<p><b>RecordCount returns ".$rs->RecordCount()."</b></p>";\r
-                               $poc = $rs->PO_RecordCount('ADOXYZ');\r
-                               if ($poc == 50) print "<p> &nbsp; &nbsp; PO_RecordCount passed</p>";\r
-                               else print "<p><b>PO_RecordCount returns wrong value: $poc</b></p>";\r
-                       } else print "<p>RecordCount() passed</p>";\r
-                       if (isset($rs->fields['firstname'])) print '<p>The fields columns can be indexed by column name.</p>';\r
-                       else {\r
-                               Err( '<p>The fields columns <i>cannot</i> be indexed by column name.</p>');\r
-                               print_r($rs->fields);\r
-                       }\r
-                       if (empty($HTTP_GET_VARS['hide'])) rs2html($rs);\r
-               }\r
-               else print "<b>Error in Execute of SELECT with random</b></p>";\r
-       }\r
-       $val = $db->GetOne("select count(*) from ADOXYZ");\r
-        if ($val == 50) print "<p>GetOne returns ok</p>";\r
-        else print "<p><b>Fail: GetOne returns $val</b></p>";\r
-\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-       $val = $db->GetRow("select count(*) from ADOXYZ");\r
-        if ($val[0] == 50 and sizeof($val) == 1) print "<p>GetRow returns ok</p>";\r
-        else {\r
-               print_r($val);\r
-               print "<p><b>Fail: GetRow returns {$val[0]}</b></p>";\r
-       }\r
-\r
-       print "<p>FetchObject/FetchNextObject Test</p>";\r
-       $rs = &$db->Execute('select * from ADOXYZ');\r
-       \r
-       if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";\r
-       \r
-       while ($o = $rs->FetchNextObject()) { // calls FetchObject internally\r
-               if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {\r
-                       print_r($o);\r
-                       print "<p><b>Firstname is not string</b></p>";\r
-                       break;\r
-               }\r
-       }\r
-       \r
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-       print "<p>FetchObject/FetchNextObject Test 2</p>";\r
-       \r
-       $rs = &$db->Execute('select * from ADOXYZ');\r
-       if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";\r
-       print_r($rs->fields);\r
-       while ($o = $rs->FetchNextObject()) { // calls FetchObject internally\r
-               if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {\r
-                       print_r($o);\r
-                       print "<p><b>Firstname is not string</b></p>";\r
-                       break;\r
-               }\r
-       }\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-       \r
-       $savefetch = $ADODB_FETCH_MODE;\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-       \r
-       print "<p>CacheSelectLimit  Test</p>";\r
-       $db->debug=1;\r
-       $rs = $db->CacheSelectLimit('  select  id, firstname from  ADOXYZ order by id',2);\r
-       if ($rs && !$rs->EOF) {\r
-               if (isset($rs->fields[0])) {\r
-                       Err("ASSOC has numeric fields");\r
-                       print_r($rs->fields);\r
-               }\r
-               if ($rs->fields['id'] != 1)  {Err("Error"); print_r($rs->fields);};\r
-               if (trim($rs->fields['firstname']) != 'Caroline')  {print Err("Error 2"); print_r($rs->fields);};\r
-               $rs->MoveNext();\r
-               if ($rs->fields['id'] != 2)  {Err("Error 3"); print_r($rs->fields);};\r
-               $rs->MoveNext();\r
-               if (!$rs->EOF) {\r
-                       Err("Error EOF");\r
-                       print_r($rs);\r
-               }\r
-       }\r
-       \r
-       print "<p>FETCH_MODE = ASSOC: Should get 1, Caroline</p>";\r
-       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',2);\r
-       if ($rs && !$rs->EOF) {\r
-               if ($rs->fields['id'] != 1)  {Err("Error 1"); print_r($rs->fields);};\r
-               if (trim($rs->fields['firstname']) != 'Caroline')  {Err("Error 2"); print_r($rs->fields);};\r
-               $rs->MoveNext();\r
-               if ($rs->fields['id'] != 2)  {Err("Error 3"); print_r($rs->fields);};\r
-               $rs->MoveNext();\r
-               if (!$rs->EOF) Err("Error EOF");\r
-               else if (is_array($rs->fields) || $rs->fields) {\r
-                       Err("Error: ## fields should be set to false on EOF");\r
-                       print_r($rs->fields);\r
-               }\r
-       }\r
-       \r
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-       print "<p>FETCH_MODE = NUM: Should get 1, Caroline</p>";\r
-       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);\r
-       if ($rs && !$rs->EOF) {\r
-               if (isset($rs->fields['id'])) Err("FETCH_NUM has ASSOC fields");\r
-               if ($rs->fields[0] != 1)  {Err("Error 1"); print_r($rs->fields);};\r
-               if (trim($rs->fields[1]) != 'Caroline')  {Err("Error 2");print_r($rs->fields);};\r
-               $rs->MoveNext();\r
-               if (!$rs->EOF) Err("Error EOF");\r
-\r
-       }\r
-       $ADODB_FETCH_MODE = $savefetch;\r
-       \r
-       $db->debug = false;\r
-       print "<p>GetRowAssoc Upper: Should get 1, Caroline</p>";\r
-       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);\r
-       if ($rs && !$rs->EOF) {\r
-               $arr = &$rs->GetRowAssoc();\r
-               if ($arr['ID'] != 1) {Err("Error 1");print_r($arr);};\r
-               if (trim($arr['FIRSTNAME']) != 'Caroline') {Err("Error 2"); print_r($arr);};\r
-               $rs->MoveNext();\r
-               if (!$rs->EOF) Err("Error EOF");\r
-\r
-       }\r
-       print "<p>GetRowAssoc Lower: Should get 1, Caroline</p>";\r
-       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);\r
-       if ($rs && !$rs->EOF) {\r
-               $arr = &$rs->GetRowAssoc(false);\r
-               if ($arr['id'] != 1) {Err("Error 1"); print_r($arr);};\r
-               if (trim($arr['firstname']) != 'Caroline') {Err("Error 2"); print_r($arr);};\r
-\r
-       }\r
-       \r
-       print "<p>GetCol Test</p>";\r
-       $col = $db->GetCol('select distinct firstname from adoxyz order by 1');\r
-       if (!is_array($col)) Err("Col size is wrong");\r
-       if (trim($col[0]) != 'Alan' or trim($col[9]) != 'Yat Sun') Err("Col elements wrong");\r
-\r
-       $db->debug = true;\r
-       print "<p>SelectLimit Distinct Test 1: Should see Caroline, John and Mary</p>";\r
-       $rs = &$db->SelectLimit('select distinct * from ADOXYZ order by id',3);\r
-       $db->debug=false;\r
-\r
-       if ($rs && !$rs->EOF) {\r
-               if (trim($rs->fields[1]) != 'Caroline') Err("Error 1");\r
-               $rs->MoveNext();\r
-               if (trim($rs->fields[1]) != 'John') Err("Error 2");\r
-               $rs->MoveNext();\r
-               if (trim($rs->fields[1]) != 'Mary') Err("Error 3");\r
-               $rs->MoveNext();\r
-               if (! $rs->EOF) Err("Error EOF");\r
-               //rs2html($rs);\r
-       } else Err("Failed SelectLimit Test 1");\r
-       \r
-       print "<p>SelectLimit Test 2: Should see Mary, George and Mr. Alan</p>";\r
-       $rs = &$db->SelectLimit('select * from ADOXYZ order by id',3,2);\r
-       if ($rs && !$rs->EOF) {\r
-               if (trim($rs->fields[1]) != 'Mary') Err("Error 1");\r
-               $rs->MoveNext();\r
-               if (trim($rs->fields[1]) != 'George')Err("Error 2");\r
-               $rs->MoveNext();\r
-               if (trim($rs->fields[1]) != 'Mr. Alan') Err("Error 3");\r
-               $rs->MoveNext();\r
-               if (! $rs->EOF) Err("Error EOF");\r
-       //      rs2html($rs);\r
-       }\r
-        else Err("Failed SelectLimit Test 2");\r
-       \r
-       print "<p>SelectLimit Test 3: Should see Wai Hun and Steven</p>";\r
-       $db->debug=1;\r
-       global $A; $A=1;\r
-       $rs = &$db->SelectLimit('select * from ADOXYZ order by id',-1,48);\r
-       $A=0;\r
-       if ($rs && !$rs->EOF) {\r
-               if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";\r
-               if (trim($rs->fields[1]) != 'Wai Hun') Err("Error 1 ".$rs->fields[1]);\r
-               $rs->MoveNext();\r
-               if (trim($rs->fields[1]) != 'Steven') Err("Error 2 ".$rs->fields[1]);\r
-               $rs->MoveNext();\r
-               if (! $rs->EOF) {\r
-                       Err("Error EOF");\r
-               }\r
-               //rs2html($rs);\r
-       }\r
-        else Err("Failed SelectLimit Test 3");\r
-               $db->debug = false;\r
-       \r
-       \r
-       $rs = &$db->Execute("select * from ADOXYZ order by id");\r
-       print "<p>Testing Move()</p>";  \r
-       if (!$rs)Err( "Failed Move SELECT");\r
-       else {\r
-               if (!$rs->Move(2)) {\r
-                       if (!$rs->canSeek) print "<p>$db->databaseType: <b>Move(), MoveFirst() nor MoveLast() not supported.</b></p>";\r
-                       else print '<p><b>RecordSet->canSeek property should be set to false</b></p>';\r
-               } else {\r
-                       $rs->MoveFirst();\r
-                       if (trim($rs->Fields("firstname")) != 'Caroline') {\r
-                               print "<p><b>$db->databaseType: MoveFirst failed -- probably cannot scroll backwards</b></p>";\r
-                       }\r
-                       else print "MoveFirst() OK<BR>";\r
-                                               \r
-                                               // Move(3) tests error handling -- MoveFirst should not move cursor\r
-                       $rs->Move(3);\r
-                       if (trim($rs->Fields("firstname")) != 'George') {\r
-                               print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) failed</b></p>";\r
-                       } else print "Move(3) OK<BR>";\r
-                                               \r
-                       $rs->Move(7);\r
-                       if (trim($rs->Fields("firstname")) != 'Yat Sun') {\r
-                               print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(7) failed</b></p>";\r
-                               print_r($rs);\r
-                       } else print "Move(7) OK<BR>";\r
-                       if ($rs->EOF) Err("Move(7) is EOF already");\r
-                       $rs->MoveLast();\r
-                       if (trim($rs->Fields("firstname")) != 'Steven'){\r
-                                print '<p>'.$rs->Fields("id")."<b>$db->databaseType: MoveLast() failed</b></p>";\r
-                                print_r($rs);\r
-                       }else print "MoveLast() OK<BR>";\r
-                       $rs->MoveNext();\r
-                       if (!$rs->EOF) err("Bad MoveNext");\r
-                       if ($rs->canSeek) {\r
-                               $rs->Move(3);\r
-                               if (trim($rs->Fields("firstname")) != 'George') {\r
-                                       print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) after MoveLast failed</b></p>";\r
-                                       \r
-                               } else print "Move(3) after MoveLast() OK<BR>";\r
-                       }\r
-                       \r
-                       print "<p>Empty Move Test";\r
-                       $rs = $db->Execute("select * from ADOXYZ where id > 0 and id < 0");\r
-                       $rs->MoveFirst();\r
-                       if (!$rs->EOF || $rs->fields) Err("Error in empty move first");\r
-               }\r
-       }\r
-       \r
-       $rs = $db->Execute('select * from ADOXYZ where id = 2');\r
-       if ($rs->EOF || !is_array($rs->fields)) Err("Error in select");\r
-       $rs->MoveNext();\r
-       if (!$rs->EOF) Err("Error in EOF (xx) ");\r
- //    $db->debug=true;\r
-       print "<p>Testing ADODB_FETCH_ASSOC and concat: concat firstname and lastname</p>";\r
-\r
-       $save = $ADODB_FETCH_MODE;\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-       if ($db->dataProvider == 'postgres') {\r
-               $sql = "select ".$db->Concat('cast(firstname as varchar)',$db->qstr(' '),'lastname')." as fullname,id from ADOXYZ";\r
-               $rs = &$db->Execute($sql);\r
-       } else {\r
-               $sql = "select distinct ".$db->Concat('firstname',$db->qstr(' '),'lastname')." as fullname,id from ADOXYZ";\r
-               $rs = &$db->Execute($sql);\r
-       }\r
-       if ($rs) {\r
-               if (empty($HTTP_GET_VARS['hide'])) rs2html($rs);\r
-       } else {\r
-               Err( "Failed Concat:".$sql);\r
-       }\r
-       $ADODB_FETCH_MODE = $save;\r
-       print "<hr>Testing GetArray() ";\r
-       //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-       \r
-       $rs = &$db->Execute("select * from ADOXYZ order by id");\r
-       if ($rs) {\r
-               $arr = &$rs->GetArray(10);\r
-               if (sizeof($arr) != 10 || trim($arr[1][1]) != 'John' || trim($arr[1][2]) != 'Lim') print $arr[1][1].' '.$arr[1][2]."<b> &nbsp; ERROR</b><br>";\r
-               else print " OK<BR>";\r
-       }\r
-       \r
-       $arr = $db->GetArray("select x from ADOXYZ");\r
-       $e = $db->ErrorMsg(); $e2 = $db->ErrorNo();\r
-       echo "Testing error handling, should see illegal column 'x' error=<i>$e ($e2) </i><br>";\r
-       if (!$e || !$e2) Err("Error handling did not work");\r
-       print "Testing FetchNextObject for 1 object ";\r
-       $rs = &$db->Execute("select distinct lastname,firstname from ADOXYZ where firstname='Caroline'");\r
-       $fcnt = 0;\r
-       if ($rs)\r
-       while ($o = $rs->FetchNextObject()) {\r
-               $fcnt += 1;     \r
-       }\r
-       if ($fcnt == 1) print " OK<BR>";\r
-       else print "<b>FAILED</b><BR>";\r
-       \r
-       $stmt = $db->Prepare("select * from ADOXYZ where id < 3");\r
-       $rs = $db->Execute($stmt);\r
-       if (!$rs) Err("Prepare failed");\r
-       else {\r
-               $arr = $rs->GetArray();\r
-               if (!$arr) Err("Prepare failed 2");\r
-               if (sizeof($arr) != 2) Err("Prepare failed 3");\r
-       }\r
-       print "Testing GetAssoc() ";\r
-       $savecrecs = $ADODB_COUNTRECS;\r
-       $ADODB_COUNTRECS = false;\r
-       $rs = &$db->Execute("select distinct lastname,firstname from ADOXYZ");\r
-       if ($rs) {\r
-               $arr = $rs->GetAssoc();\r
-               //print_r($arr);\r
-               if (trim($arr['See']) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";\r
-               else print " OK 1";\r
-       }\r
-       \r
-       $arr = &$db->GetAssoc("select distinct lastname,firstname from ADOXYZ");\r
-       if ($arr) {\r
-               //print_r($arr);\r
-               if (trim($arr['See']) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";\r
-               else print " OK 2<BR>";\r
-       }\r
-       // Comment this out to test countrecs = false\r
-       $ADODB_COUNTRECS = $savecrecs;\r
-       \r
-       for ($loop=0; $loop < 1; $loop++) {\r
-       print "Testing GetMenu() and CacheExecute<BR>";\r
-       $db->debug = true;\r
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
-       \r
-       if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu('menu','Steven').'<BR>'; \r
-       else print " Fail<BR>";\r
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
-       \r
-       if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu('menu','Steven',false).'<BR>';\r
-       else print " Fail<BR>";\r
-       \r
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
-       if ($rs) print ' Multiple, Alan selected: '. $rs->GetMenu('menu','Alan',false,true).'<BR>';\r
-       else print " Fail<BR>";\r
-       print '</p><hr>';\r
-       \r
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
-       if ($rs) {\r
-               print ' Multiple, Alan and George selected: '. $rs->GetMenu('menu',array('Alan','George'),false,true);\r
-               if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";\r
-       } else print " Fail<BR>";\r
-       print '</p><hr>';\r
-       \r
-       print "Testing GetMenu2() <BR>";\r
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
-       if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu2('menu',('Oey')).'<BR>'; \r
-       else print " Fail<BR>";\r
-       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");\r
-       if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu2('menu',('Oey'),false).'<BR>';\r
-       else print " Fail<BR>";\r
-       }\r
-       \r
-       $db->debug = false;\r
-       \r
-       // phplens\r
-       \r
-       $sql = 'select * from ADOXYZ where 0=1';\r
-       echo "<p>**Testing '$sql' (phplens compat 1)</p>";\r
-       $rs = &$db->Execute($sql);\r
-       if (!$rs) err( "<b>No recordset returned for '$sql'</b>");\r
-       if (!$rs->FieldCount()) err( "<b>No fields returned for $sql</b>");\r
-       if (!$rs->FetchField(1)) err( "<b>FetchField failed for $sql</b>");\r
-       \r
-       $sql = 'select * from ADOXYZ order by 1';\r
-       echo "<p>**Testing '$sql' (phplens compat 2)</p>";\r
-       $rs = &$db->Execute($sql);\r
-       if (!$rs) err( "<b>No recordset returned for '$sql'<br>".$db->ErrorMsg()."</b>");\r
-       \r
-       \r
-       $sql = 'select * from ADOXYZ order by 1,1';\r
-       echo "<p>**Testing '$sql' (phplens compat 3)</p>";\r
-       $rs = &$db->Execute($sql);\r
-       if (!$rs) err( "<b>No recordset returned for '$sql'<br>".$db->ErrorMsg()."</b>");\r
-       \r
-       \r
-       // Move\r
-       $rs1 = &$db->Execute("select id from ADOXYZ where id <= 2 order by 1");\r
-       $rs2 = &$db->Execute("select id from ADOXYZ where id = 3 or id = 4 order by 1");\r
-\r
-       if ($rs1) $rs1->MoveLast();\r
-       if ($rs2) $rs2->MoveLast();\r
-       \r
-       if (empty($rs1) || empty($rs2) || $rs1->fields[0] != 2 || $rs2->fields[0] != 4) {\r
-               $a = $rs1->fields[0];\r
-               $b = $rs2->fields[0];\r
-               print "<p><b>Error in multiple recordset test rs1=$a rs2=$b (should be rs1=2 rs2=4)</b></p>";\r
-       } else\r
-               print "<p>Testing multiple recordsets OK</p>";\r
-               \r
-       \r
-       echo "<p> GenID test: ";\r
-       for ($i=1; $i <= 10; $i++) \r
-               echo  "($i: ",$val = $db->GenID($db->databaseType.'abcseq6' ,5), ") ";\r
-       if ($val == 0) Err("GenID not supported");\r
-       \r
-       if ($val) {\r
-               $db->DropSequence('abc_seq2');\r
-               $db->CreateSequence('abc_seq2');\r
-               $val = $db->GenID('abc_seq2');\r
-               $db->DropSequence('abc_seq2');\r
-               $db->CreateSequence('abc_seq2');\r
-               $val = $db->GenID('abc_seq2');\r
-               if ($val != 1) Err("Drop and Create Sequence not supported ($val)");\r
-       }\r
-       echo "<p>";\r
-       \r
-       if (substr($db->dataProvider,0,3) != 'notused') { // used to crash ado\r
-               $sql = "select firstnames from adoxyz";\r
-               print "<p>Testing execution of illegal statement: <i>$sql</i></p>";\r
-               if ($db->Execute($sql) === false) {\r
-                       print "<p>This returns the following ErrorMsg(): <i>".$db->ErrorMsg()."</i> and ErrorNo(): ".$db->ErrorNo().'</p>';\r
-               } else \r
-                       print "<p><b>Error in error handling -- Execute() should return false</b></p>";\r
-       } else \r
-               print "<p><b>ADO skipped error handling of bad select statement</b></p>";\r
-       \r
-       print "<p>ASSOC TEST 2<br>";\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-       $rs = $db->query('select * from adoxyz order by id');\r
-       if ($ee = $db->ErrorMsg()) {\r
-               Err("Error message=$ee");\r
-       }\r
-       if ($ee = $db->ErrorNo()) {\r
-               Err("Error No = $ee");\r
-       }\r
-       print_r($rs->fields);\r
-       for($i=0;$i<$rs->FieldCount();$i++) \r
-       { \r
-               $fld=$rs->FetchField($i); \r
-               print "<br> Field name is ".$fld->name; \r
-               print " ".$rs->Fields($fld->name); \r
-       } \r
-\r
-               \r
-       print "<p>BOTH TEST 2<br>";\r
-       if ($db->dataProvider == 'ado') {\r
-               print "<b>ADODB_FETCH_BOTH not supported</b> for dataProvider=".$db->dataProvider."<br>";\r
-       } else {\r
-               $ADODB_FETCH_MODE = ADODB_FETCH_BOTH;\r
-               $rs = $db->query('select * from adoxyz order by id');\r
-               for($i=0;$i<$rs->FieldCount();$i++) \r
-               { \r
-                       $fld=$rs->FetchField($i); \r
-                       print "<br> Field name is ".$fld->name; \r
-                       print " ".$rs->Fields($fld->name); \r
-               } \r
-       }\r
-       \r
-       print "<p>NUM TEST 2<br>";\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-       $rs = $db->query('select * from adoxyz order by id');\r
-       for($i=0;$i<$rs->FieldCount();$i++) \r
-       { \r
-               $fld=$rs->FetchField($i); \r
-               print "<br> Field name is ".$fld->name; \r
-               print " ".$rs->Fields($fld->name); \r
-       } \r
-       \r
-       print "<p>ASSOC Test of SelectLimit<br>";\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-       $rs = $db->selectlimit('select * from adoxyz order by id',3,4);\r
-       $cnt = 0;\r
-       while ($rs && !$rs->EOF) {\r
-               $cnt += 1;\r
-               if (!isset($rs->fields['firstname'])) {\r
-                       print "<br><b>ASSOC returned numeric field</b></p>";\r
-                       break;\r
-               }\r
-               $rs->MoveNext();\r
-       }\r
-       if ($cnt != 3) print "<br><b>Count should be 3, instead it was $cnt</b></p>";\r
-       \r
-       \r
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-       if ($db->sysDate) {\r
-               $saved = $db->debug;\r
-               $db->debug = 1;\r
-               $rs = $db->Execute("select {$db->sysDate} from adoxyz where id=1");\r
-               if (ADORecordSet::UnixDate(date('Y-m-d')) != $rs->UnixDate($rs->fields[0])) {\r
-                       print "<p><b>Invalid date {$rs->fields[0]}</b></p>";\r
-               } else\r
-                       print "<p>Passed \$sysDate test ({$rs->fields[0]})</p>";\r
-               \r
-               print_r($rs->FetchField(0));\r
-               print time();\r
-               $db->debug=$saved;\r
-       } else {\r
-               print "<p><b>\$db->sysDate not defined</b></p>";\r
-       }\r
-\r
-       print "<p>Test CSV</p>";\r
-       include_once('../toexport.inc.php');\r
-       //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-       $rs = $db->SelectLimit('select id,firstname,lastname,created,\'He, he\' he,\'"\' q  from adoxyz',10);   \r
-       \r
-       print "<pre>";\r
-       print rs2csv($rs);\r
-       print "</pre>";\r
-       \r
-       $rs = $db->SelectLimit('select id,firstname,lastname,created,\'The      "young man", he said\' from adoxyz',10);        \r
-       \r
-       print "<pre>";\r
-       rs2tabout($rs);\r
-       print "</pre>";\r
-       \r
-       //print " CacheFlush ";\r
-       //$db->CacheFlush();\r
-       \r
-       $date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A');\r
-       $sql = "SELECT $date from ADOXYZ";\r
-       print "<p>Test SQLDate: ".htmlspecialchars($sql)."</p>";\r
-       $rs = $db->SelectLimit($sql,1);\r
-       $d = date('d-m-M-Y-').'Q'.(ceil(date('m')/3.0)).date(' h:i:s A');\r
-       if (!$rs) Err("SQLDate query returned no recordset");\r
-       else if ($d != $rs->fields[0]) Err("SQLDate 1 failed expected: <br>act:$d <br>sql:".$rs->fields[0]);\r
-       \r
-       $date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A',$db->DBDate("1974-02-25"));\r
-       $sql = "SELECT $date from ADOXYZ";\r
-       print "<p>Test SQLDate: ".htmlspecialchars($sql)."</p>";\r
-       $rs = $db->SelectLimit($sql,1);\r
-       $ts = ADOConnection::UnixDate('1974-02-25');\r
-       $d = date('d-m-M-Y-',$ts).'Q'.(ceil(date('m',$ts)/3.0)).date(' h:i:s A',$ts);\r
-       if (!$rs) Err("SQLDate query returned no recordset");\r
-       else if ($d != $rs->fields[0]) Err("SQLDate 2 failed expected: <br>act:$d <br>sql:".$rs->fields[0]);\r
-       \r
-       \r
-       print "<p>Test Filter</p>";\r
-       $db->debug = 1;\r
-       \r
-       $rs = $db->SelectLimit('select * from ADOXYZ where id < 3 order by id');\r
-       \r
-       $rs = RSFilter($rs,'do_strtolower');\r
-       if (trim($rs->fields[1]) != 'caroline'  && trim($rs->fields[2]) != 'miranda') {\r
-               err('**** RSFilter failed');\r
-               print_r($rs->fields);\r
-       }\r
-       \r
-       rs2html($rs);\r
-               \r
-       $db->debug=1;\r
-       \r
-       \r
-       print "<p>Test Replace</p>";\r
-       \r
-       $ret = $db->Replace('adoxyz', \r
-               array('id'=>1,'firstname'=>'Caroline','lastname'=>'Miranda'),\r
-               array('id'),\r
-               $autoq = true);\r
-       if (!$ret) echo "<p>Error in replacing existing record</p>";\r
-       else {\r
-               $saved = $db->debug;\r
-               $db->debug = 0;\r
-               $savec = $ADODB_COUNTRECS;\r
-               $ADODB_COUNTRECS = true;\r
-               $rs = $db->Execute('select * FROM ADOXYZ where id=1');\r
-               $db->debug = $saved;\r
-               if ($rs->RecordCount() != 1) {\r
-                       $cnt = $rs->RecordCount();\r
-                       rs2html($rs);\r
-                       print "<b>Error - Replace failed, count=$cnt</b><p>";\r
-               }\r
-               $ADODB_COUNTRECS = $savec;\r
-       }\r
-       $ret = $db->Replace('adoxyz', \r
-               array('id'=>1000,'firstname'=>'Harun','lastname'=>'Al-Rashid'),\r
-               array('id','firstname'),\r
-               $autoq = true);\r
-       if ($ret != 2) print "<b>Replace failed: </b>";\r
-       print "test A return value=$ret (2 expected) <p>";\r
-       \r
-       $ret = $db->Replace('adoxyz', \r
-               array('id'=>1000,'firstname'=>'Sherazade','lastname'=>'Al-Rashid'),\r
-               'id',\r
-               $autoq = true);\r
-       if ($ret != 1) \r
-               if ($db->dataProvider == 'ibase' && $ret == 2);\r
-               else print "<b>Replace failed: </b>";\r
-       print "test B return value=$ret (1 or if ibase then 2 expected) <p>";\r
-       \r
-       print "<h3>rs2rs Test</h3>";\r
-       \r
-       $rs = $db->Execute('select * from adoxyz order by id');\r
-       $rs = $db->_rs2rs($rs);\r
-       $rs->valueX = 'X';\r
-       $rs->MoveNext();\r
-       $rs = $db->_rs2rs($rs);\r
-       if (!isset($rs->valueX)) err("rs2rs does not preserve array recordsets");\r
-       if (reset($rs->fields) != 1) err("rs2rs does not move to first row");\r
-\r
-       /////////////////////////////////////////////////////////////\r
-       include_once('../pivottable.inc.php');\r
-       print "<h3>Pivot Test</h3>";\r
-       $db->debug=true;\r
-       $sql = PivotTableSQL(\r
-               $db,                    # adodb connection\r
-               'adoxyz',               # tables\r
-               'firstname',    # row fields\r
-               'lastname',             # column fields \r
-               false,                  # join\r
-               'ID',                   # sum\r
-               'Sum ',                 # label for sum\r
-               'sum',                  # aggregate function\r
-               true\r
-       );\r
-       $rs = $db->Execute($sql);\r
-       if ($rs) rs2html($rs);\r
-       else Err("Pivot sql error");\r
-       \r
-       $db->debug=false;\r
-       include_once "PEAR.php";\r
-       \r
-       // PEAR TESTS BELOW\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;\r
-       $pear = true;\r
-       $rs = $db->query('select * from adoxyz where id>0 and id<10 order by id');\r
-       \r
-       $i = 0;\r
-       if ($rs && !$rs->EOF) {\r
-               while ($arr = $rs->fetchRow()) {\r
-                       $i++;\r
-                       //print "$i ";\r
-                       if ($arr[0] != $i) {\r
-                               print_r($arr);\r
-                               print "<p><b>PEAR DB emulation error 1.</b></p>";\r
-                               $pear = false;\r
-                               break;\r
-                       }\r
-               }\r
-               $rs->Close();\r
-       }\r
-       \r
-       \r
-       if ($i != $db->GetOne('select count(*) from adoxyz where id>0 and id<10')) {\r
-               print "<p><b>PEAR DB emulation error 1.1 EOF ($i)</b></p>";\r
-               $pear = false;\r
-       }\r
-       \r
-       $rs = $db->limitQuery('select * from adoxyz where id>0 order by id',$i=3,$top=3);\r
-       $i2 = $i;\r
-       if ($rs && !$rs->EOF) {\r
-\r
-               while (!is_object($rs->fetchInto($arr))) {\r
-                       $i2++;\r
-                       \r
-       //                      print_r($arr);\r
-       //              print "$i ";print_r($arr);\r
-                       if ($arr[0] != $i2) {\r
-                               print "<p><b>PEAR DB emulation error 2.</b></p>";\r
-                               $pear = false;\r
-                               break;\r
-                       }\r
-               }\r
-               $rs->Close();\r
-       }\r
-       if ($i2 != $i+$top) {\r
-               print "<p><b>PEAR DB emulation error 2.1 EOF (correct=$i+$top, actual=$i2)</b></p>";\r
-               $pear = false;\r
-       }\r
-       \r
-       if ($pear) print "<p>PEAR DB emulation passed.</p>";\r
-       \r
-       $rs = $db->SelectLimit("select ".$db->sysDate." from adoxyz",1);\r
-       $date = $rs->fields[0];\r
-       if (!$date) Err("Bad sysDate");\r
-       else {\r
-               $ds = $db->UserDate($date,"d m Y");\r
-               if ($ds != date("d m Y")) Err("Bad UserDate: ".$ds);\r
-               else echo "Passed UserDate: $ds<p>";\r
-       }\r
-       $db->debug=1;\r
-       if ($db->dataProvider == 'oci8') \r
-               $rs = $db->SelectLimit("select to_char(".$db->sysTimeStamp.",'YYYY-MM-DD HH24:MI:SS') from adoxyz",1);\r
-       else \r
-               $rs = $db->SelectLimit("select ".$db->sysTimeStamp." from adoxyz",1);\r
-       $date = $rs->fields[0];\r
-       if (!$date) Err("Bad sysTimeStamp");\r
-       else {\r
-               $ds = $db->UserTimeStamp($date,"H \\h\\r\\s-d m Y");\r
-               if ($ds != date("H \\h\\r\\s-d m Y")) Err("Bad UserTimeStamp: ".$ds.", correct is ".date("H \\h\\r\\s-d m Y"));\r
-               else echo "Passed UserTimeStamp: $ds<p>";\r
-               \r
-               $date = 100;\r
-               $ds = $db->UserTimeStamp($date,"H \\h\\r\\s-d m Y");\r
-               $ds2 = date("H \\h\\r\\s-d m Y",$date);\r
-               if ($ds != $ds2) Err("Bad UserTimeStamp 2: $ds: $ds2");\r
-               else echo "Passed UserTimeStamp 2: $ds<p>";\r
-       }\r
-       if ($db->hasTransactions) {\r
-               //$db->debug=1;\r
-               echo "<p>Testing StartTrans CompleteTrans</p>";\r
-               $db->raiseErrorFn = false;\r
-               $db->StartTrans();\r
-               $rs = $db->Execute('select * from notable');\r
-                       $db->StartTrans();\r
-                               $db->BeginTrans();\r
-                       $db->Execute("update ADOXYZ set firstname='Carolx' where id=1");\r
-                               $db->CommitTrans();\r
-                       $db->CompleteTrans();\r
-               $rez = $db->CompleteTrans();\r
-               if ($rez !== false) {\r
-                       if (is_null($rez)) Err("Error: _transOK not modified");\r
-                       else Err("Error: CompleteTrans (1) should have failed");\r
-               } else {\r
-                       $name = $db->GetOne("Select firstname from ADOXYZ where id=1");\r
-                       if ($name == "Carolx") Err("Error: CompleteTrans (2) should have failed");\r
-                       else echo "<p> -- Passed StartTrans test1 - rolling back</p>";\r
-               }\r
-               \r
-               $db->StartTrans();\r
-                       $db->BeginTrans();\r
-               $db->Execute("update ADOXYZ set firstname='Carolx' where id=1");\r
-                       $db->RollbackTrans();\r
-               $rez = $db->CompleteTrans();\r
-               if ($rez !== true) Err("Error: CompleteTrans (1) should have succeeded");\r
-               else {\r
-                       $name = $db->GetOne("Select firstname from ADOXYZ where id=1");\r
-                       if (trim($name) != "Carolx") Err("Error: CompleteTrans (2) should have succeeded, returned name=$name");\r
-                       else echo "<p> -- Passed StartTrans test2 - commiting</p>";\r
-               }\r
-       }\r
-       \r
-       \r
-       global $TESTERRS;\r
-       $debugerr = true;\r
-       \r
-       global $ADODB_LANG;$ADODB_LANG = 'fr';\r
-       $db->debug = false;\r
-       $TESTERRS = 0;\r
-       $db->raiseErrorFn = 'adodb_test_err';\r
-       global $ERRNO; // from adodb_test_err\r
-       $db->Execute('select * from nowhere');\r
-       $metae = $db->MetaError($ERRNO);\r
-       if ($metae !== DB_ERROR_NOSUCHTABLE) print "<p><b>MetaError=".$metae." wrong</b>, should be ".DB_ERROR_NOSUCHTABLE."</p>";\r
-       else print "<p>MetaError ok (".DB_ERROR_NOSUCHTABLE."): ".$db->MetaErrorMsg($metae)."</p>";\r
-       if ($TESTERRS != 1) print "<b>raiseErrorFn select nowhere failed</b><br>";\r
-       $rs = $db->Execute('select * from adoxyz');\r
-       if ($debugerr) print " Move";\r
-       $rs->Move(100);\r
-       $rs->_queryID = false;\r
-       if ($debugerr) print " MoveNext";\r
-       $rs->MoveNext();\r
-       if ($debugerr) print " $rs=false";\r
-       $rs = false;\r
-\r
-       print "<p>SetFetchMode() tests</p>";\r
-       $db->SetFetchMode(ADODB_FETCH_ASSOC);\r
-       $rs = $db->SelectLimit('select firstname from adoxyz',1);\r
-       //      var_dump($rs->fields);\r
-       if (!isset($rs->fields['firstname'])) Err("BAD FETCH ASSOC");\r
-       \r
-       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;    \r
-       $rs = $db->SelectLimit('select firstname from adoxyz',1);\r
-       //var_dump($rs->fields);\r
-       if (!isset($rs->fields['firstname'])) Err("BAD FETCH ASSOC");\r
-       \r
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;  \r
-       $db->SetFetchMode(ADODB_FETCH_NUM);\r
-       $rs = $db->SelectLimit('select firstname from adoxyz',1);\r
-       if (!isset($rs->fields[0])) Err("BAD FETCH NUM");\r
-       \r
-       print "<p>Test MetaTables again with SetFetchMode()</p>";\r
-       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;\r
-       $db->SetFetchMode(ADODB_FETCH_ASSOC);\r
-       print_r($db->MetaTables());\r
-       print "<p>";\r
-       ////////////////////////////////////////////////////////////////////\r
-       \r
-       $conn = NewADOConnection($db->databaseType);\r
-       $conn->raiseErrorFn = 'adodb_test_err';\r
-       @$conn->Connect('abc');\r
-       if ($TESTERRS == 2) print "raiseErrorFn tests passed<br>";\r
-       else print "<b>raiseErrorFn tests failed ($TESTERRS)</b><br>";\r
-       \r
-       \r
-       ////////////////////////////////////////////////////////////////////\r
-       \r
-       global $nocountrecs;\r
-       \r
-       if (isset($nocountrecs) && $ADODB_COUNTRECS) err("Error: \$ADODB_COUNTRECS is set");\r
-       if (empty($nocountrecs) && $ADODB_COUNTRECS==false) err("Error: \$ADODB_COUNTRECS is not set");\r
-\r
-       \r
-?>\r
-       </p>\r
-       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>\r
-       </p></form>\r
-<?php\r
-\r
-       if ($rs1) $rs1->Close();\r
-       if ($rs2) $rs2->Close();\r
-       if ($rs) $rs->Close();\r
-       $db->Close();\r
-       \r
-       if ($db->transCnt != 0) Err("Error in transCnt=$db->transCnt (should be 0)");\r
-       \r
-       \r
-       printf("<p>Total queries=%d; total cached=%d</p>",$EXECS+$CACHED, $CACHED);\r
-}\r
-\r
-function adodb_test_err($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)\r
-{\r
-global $TESTERRS,$ERRNO;\r
-\r
-       $ERRNO = $errno;\r
-       $TESTERRS += 1;\r
-       print "<i>** $dbms ($fn): errno=$errno &nbsp; errmsg=$errmsg ($p1,$p2)</i><br>";\r
-}\r
-\r
-//--------------------------------------------------------------------------------------\r
-\r
-\r
-set_time_limit(240); // increase timeout\r
-\r
-include("../tohtml.inc.php");\r
-include("../adodb.inc.php");\r
-include("../rsfilter.inc.php");\r
-\r
-/* White Space Check */\r
-if (@$HTTP_SERVER_VARS['COMPUTERNAME'] == 'TIGRESS') {\r
-       CheckWS('mysqlt');\r
-       CheckWS('postgres');\r
-       CheckWS('oci8po');\r
-       CheckWS('firebird');\r
-       CheckWS('sybase');\r
-       CheckWS('informix');\r
-       CheckWS('ado_mssql');\r
-       CheckWS('ado_access');\r
-       CheckWS('mssql');\r
-       //\r
-       CheckWS('vfp');\r
-       CheckWS('sqlanywhere');\r
-       CheckWS('db2');\r
-       CheckWS('access');\r
-       CheckWS('odbc_mssql');\r
-       //\r
-       CheckWS('oracle');\r
-       CheckWS('proxy');\r
-       CheckWS('fbsql');\r
-       print "White Space Check complete<p>";\r
-}\r
-if (sizeof($HTTP_GET_VARS) == 0) $testmysql = true;\r
-\r
-\r
-foreach($HTTP_GET_VARS as $k=>$v)  {\r
-       //global $$k;\r
-       $$k = $v;\r
-}      \r
-if (strpos(PHP_VERSION,'5') === 0) {\r
-       //$testaccess=1;\r
-       //$testmssql = 1;\r
-       //$testsqlite=1;\r
-}\r
-?>\r
-<html>\r
-<title>ADODB Testing</title>\r
-<body bgcolor=white>\r
-<H1>ADODB Test</H1>\r
-\r
-This script tests the following databases: Interbase, Oracle, Visual FoxPro, Microsoft Access (ODBC and ADO), MySQL, MSSQL (ODBC, native, ADO). \r
-There is also support for Sybase, PostgreSQL.</p>\r
-For the latest version of ADODB, visit <a href=http://php.weblogs.com/ADODB>php.weblogs.com</a>.</p>\r
-\r
-Test <a href=test4.php>GetInsertSQL/GetUpdateSQL</a> &nbsp; \r
-       <a href=testsessions.php>Sessions</a> &nbsp;\r
-       <a href=testpaging.php>Paging</a> &nbsp;\r
-       <a href=test-perf.php>Perf Monitor</a><p>\r
-<?php\r
-include('./testdatabases.inc.php');\r
-?>\r
-       \r
-<?php\r
-\r
-include_once('../adodb-time.inc.php');\r
-adodb_date_test();\r
-?>\r
-<p><i>ADODB Database Library  (c) 2000-2004 John Lim. All rights reserved. Released under BSD and LGPL.</i></p>\r
-</body>\r
-</html>\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+       
+  Latest version is available at http://php.weblogs.com/
+*/
+
+error_reporting(E_ALL);
+$ADODB_FLUSH = true;
+
+define('ADODB_ASSOC_CASE',0);
+
+if (PHP_VERSION < 5) include_once('../adodb-pear.inc.php');
+//--------------------------------------------------------------------------------------
+//define('ADODB_ASSOC_CASE',1);
+//
+function Err($msg)
+{
+       print "<b>$msg</b><br>";
+       flush();
+}
+
+function CheckWS($conn)
+{
+global $ADODB_EXTENSION;
+
+       include_once('../session/adodb-session.php');
+       
+       $saved = $ADODB_EXTENSION;
+       $db = ADONewConnection($conn);
+       $ADODB_EXTENSION = $saved;
+       if (headers_sent()) {
+               print "<p><b>White space detected in adodb-$conn.inc.php or include file...</b></p>";
+               die();
+       }
+}
+
+function do_strtolower(&$arr)
+{
+       foreach($arr as $k => $v) {
+               $arr[$k] = strtolower($v);
+       }
+}
+
+
+function CountExecs($db, $sql, $inputarray)
+{
+global $EXECS;  $EXECS++;
+}
+
+function CountCachedExecs($db, $secs2cache, $sql, $inputarray)
+{
+global $CACHED; $CACHED++;
+}
+
+// the table creation code is specific to the database, so we allow the user 
+// to define their own table creation stuff
+
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
+{
+GLOBAL $ADODB_vers,$ADODB_CACHE_DIR,$ADODB_FETCH_MODE, $HTTP_GET_VARS,$ADODB_COUNTRECS;
+
+?>     <form method=GET>
+       </p>
+       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>
+       </p>
+<?php  
+       $create =false;
+       /*$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+       
+       $rs = $db->Execute('select lastname,firstname,lastname,id from adoxyz');
+       $arr = $rs->GetAssoc();
+       echo "<pre>";print_r($arr);
+       die();*/
+       
+       GLOBAL $EXECS, $CACHED;
+       
+       $EXECS = 0;
+       $CACHED = 0;
+       if ((rand()%3) == 0) @$db->Execute("delete from adodb_logsql");
+       $db->debug=1;
+       
+       $db->fnExecute = 'CountExecs';
+       $db->fnCacheExecute = 'CountCachedExecs';
+       
+       if (empty($_GET['nolog'])) {
+               echo "<h3>SQL Logging enabled</h3>";
+               $db->LogSQL();/*
+               $sql =
+"SELECT t1.sid, t1.sid, t1.title, t1.hometext, t1.notes, t1.aid, t1.informant, 
+t2.url, t2.email, t1.catid, t3.title, t1.topic, t4.topicname, t4.topicimage, 
+t4.topictext, t1.score, t1.ratings, t1.counter, t1.comments, t1.acomm 
+FROM `nuke_stories` `t1`, `nuke_authors` `t2`, `nuke_stories_cat` `t3`, `nuke_topics` `t4` 
+       WHERE ((t2.aid=t1.aid) AND (t3.catid=t1.catid) AND (t4.topicid=t1.topic) 
+       AND ((t1.alanguage='german') OR (t1.alanguage='')) AND (t1.ihome='0')) 
+       ORDER BY t1.time DESC";
+               $db->SelectLimit($sql);
+               echo $db->ErrorMsg();*/
+       }
+       $ADODB_CACHE_DIR = dirname(TempNam('/tmp','testadodb'));
+       $db->debug = false;
+       
+       //print $db->UnixTimeStamp('2003-7-22 23:00:00');
+       
+       $phpv = phpversion();
+       if (defined('ADODB_EXTENSION')) $ext = ' &nbsp; Extension '.ADODB_EXTENSION.' installed';
+       else $ext = '';
+       print "<h3>ADODB Version: $ADODB_vers Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i> &nbsp; PHP: $phpv $ext</h3>";
+       flush();
+       $arr = $db->ServerInfo();
+       print_r($arr);
+       echo "<br>";
+       $e = error_reporting(E_ALL-E_WARNING);
+       flush();
+       print "<i>date1</i> (1969-02-20) = ".$db->DBDate('1969-2-20');
+       print "<br><i>date1</i> (1999-02-20) = ".$db->DBDate('1999-2-20');
+       print "<br><i>date1.1</i> 1999 = ".$db->DBDate("'1999'");
+       print "<br><i>date2</i> (1970-1-2) = ".$db->DBDate(24*3600)."<p>";
+       print "<i>ts1</i> (1999-02-20 13:40:50) = ".$db->DBTimeStamp('1999-2-20 1:40:50 pm');
+       print "<br><i>ts1.1</i> (1999-02-20 13:40:00) = ".$db->DBTimeStamp('1999-2-20 13:40');
+       print "<br><i>ts2</i> (1999-02-20) = ".$db->DBTimeStamp('1999-2-20');
+       print "<br><i>ts3</i> (1970-1-2 +/- timezone) = ".$db->DBTimeStamp(24*3600);
+       print "<br> Fractional TS (1999-2-20 13:40:50.91): ".$db->DBTimeStamp($db->UnixTimeStamp('1999-2-20 13:40:50.91+1'));
+        $dd = $db->UnixDate('1999-02-20');
+       print "<br>unixdate</i> 1999-02-20 = ".date('Y-m-d',$dd)."<p>";
+       print "<br><i>ts4</i> =".($db->UnixTimeStamp("19700101000101")+8*3600);
+       print "<br><i>ts5</i> =".$db->DBTimeStamp($db->UnixTimeStamp("20040110092123"));
+       print "<br><i>ts6</i> =".$db->UserTimeStamp("20040110092123");
+       print "<br><i>ts6</i> =".$db->DBTimeStamp("20040110092123");
+       flush();
+       // mssql too slow in failing bad connection
+       if (false && $db->databaseType != 'mssql') {
+               print "<p>Testing bad connection. Ignore following error msgs:<br>";
+               $db2 = ADONewConnection();
+               $rez = $db2->Connect("bad connection");
+               $err = $db2->ErrorMsg();
+               print "<i>Error='$err'</i></p>";
+               if ($rez) print "<b>Cannot check if connection failed.</b> The Connect() function returned true.</p>";
+       }
+       error_reporting($e);
+       flush();
+       
+       //$ADODB_COUNTRECS=false;
+       $rs=$db->Execute('select * from adoxyz order by id');
+
+       //print_r($rs);
+       //OCIFetchStatement($rs->_queryID,$rez,0,-1);//,OCI_ASSOC | OCI_FETCHSTATEMENT_BY_ROW);
+       //print_r($rez);
+       //die();
+       if($rs === false) $create = true;
+       else $rs->Close();
+               
+       //if ($db->databaseType !='vfp') $db->Execute("drop table ADOXYZ");
+       
+       if ($create) {
+               if (false && $db->databaseType == 'ibase') {
+                       print "<b>Please create the following table for testing:</b></p>$createtab</p>";
+                       return;
+               } else {
+                       $db->debug = 1;
+                       $e = error_reporting(E_ALL-E_WARNING);
+                       $db->Execute($createtab);
+                       error_reporting($e);
+               }
+       }
+       $rs = &$db->Execute("delete from ADOXYZ"); // some ODBC drivers will fail the drop so we delete
+       if ($rs) {
+               if(! $rs->EOF) print "<b>Error: </b>RecordSet returned by Execute('delete...') should show EOF</p>";
+               $rs->Close();
+       } else print "err=".$db->ErrorMsg();
+
+       print "<p>Test select on empty table, FetchField when EOF, and GetInsertSQL</p>";
+       $rs = &$db->Execute("select id,firstname from ADOXYZ where id=9999");
+       if ($rs && !$rs->EOF) print "<b>Error: </b>RecordSet returned by Execute(select...') on empty table should show EOF</p>";
+       if ($rs->EOF && ($o = $rs->FetchField(0))) {
+               $record['id'] = 99;
+               $record['firstname'] = 'John';
+               $sql =  $db->GetInsertSQL($rs, $record);
+               if ($sql != "INSERT INTO ADOXYZ ( id, firstname ) VALUES ( 99, 'John' )") Err("GetInsertSQL does not work on empty table");
+       } else {
+               Err("FetchField does not work on empty recordset, meaning GetInsertSQL will fail...");
+       }
+       if ($rs) $rs->Close();
+       flush();
+       //$db->debug=true;      
+       print "<p>Testing Commit: ";
+       $time = $db->DBDate(time());
+       if (!$db->BeginTrans()) {
+               print '<b>Transactions not supported</b></p>';
+               if ($db->hasTransactions) Err("hasTransactions should be false");
+       } else { /* COMMIT */
+               if (!$db->hasTransactions) Err("hasTransactions should be true");
+               if ($db->transCnt != 1) Err("Invalid transCnt = $db->transCnt (should be 1)");
+               $rs = $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values (99,'Should Not','Exist (Commit)',$time)");
+               if ($rs && $db->CommitTrans()) {
+                       $rs->Close();
+                       $rs = &$db->Execute("select * from ADOXYZ where id=99");
+                       if ($rs === false || $rs->EOF) {
+                               print '<b>Data not saved</b></p>';
+                               $rs = &$db->Execute("select * from ADOXYZ where id=99");
+                               print_r($rs);
+                               die();
+                       } else print 'OK</p>';
+                       if ($rs) $rs->Close();
+               } else {
+                       if (!$rs) {
+                               print "<b>Insert failed</b></p>";
+                               $db->RollbackTrans();
+                       } else print "<b>Commit failed</b></p>";
+               }
+               if ($db->transCnt != 0) Err("Invalid transCnt = $db->transCnt (should be 0)");
+               
+               /* ROLLBACK */  
+               if (!$db->BeginTrans()) print "<p><b>Error in BeginTrans</b>()</p>";
+               print "<p>Testing Rollback: ";
+               $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values (100,'Should Not','Exist (Rollback)',$time)");
+               if ($db->RollbackTrans()) {
+                       $rs = $db->Execute("select * from ADOXYZ where id=100");
+                       if ($rs && !$rs->EOF) print '<b>Fail: Data should rollback</b></p>';
+                       else print 'OK</p>';
+                       if ($rs) $rs->Close();
+               } else
+                       print "<b>Commit failed</b></p>";
+                       
+               $rs = &$db->Execute('delete from ADOXYZ where id>50');
+               if ($rs) $rs->Close();
+               
+               if ($db->transCnt != 0) Err("Invalid transCnt = $db->transCnt (should be 0)");
+       }
+       
+       if (1) {
+               print "<p>Testing MetaDatabases()</p>";
+               print_r( $db->MetaDatabases());
+               
+               print "<p>Testing MetaTables() and MetaColumns()</p>";
+               $a = $db->MetaTables();
+               if ($a===false) print "<b>MetaTables not supported</b></p>";
+               else {
+                       print "Array of tables and views: "; 
+                       foreach($a as $v) print " ($v) ";
+                       print '</p>';
+               }
+               
+               $a = $db->MetaTables('VIEW');
+               if ($a===false) print "<b>MetaTables not supported</b></p>";
+               else {
+                       print "Array of views: "; 
+                       foreach($a as $v) print " ($v) ";
+                       print '</p>';
+               }
+               
+               $a = $db->MetaTables(false,false,'aDo%');
+               if ($a===false) print "<b>MetaTables not supported</b></p>";
+               else {
+                       print "Array of ado%: "; 
+                       foreach($a as $v) print " ($v) ";
+                       print '</p>';
+               }
+               
+               $a = $db->MetaTables('TABLE');
+               if ($a===false) print "<b>MetaTables not supported</b></p>";
+               else {
+                       print "Array of tables: "; 
+                       foreach($a as $v) print " ($v) ";
+                       print '</p>';
+               }
+               
+               $db->debug=1;
+               $a = $db->MetaColumns('ADOXYZ');
+               if ($a===false) print "<b>MetaColumns not supported</b></p>";
+               else {
+                       print "<p>Columns of ADOXYZ: <font size=1><br>";
+                       foreach($a as $v) {print_r($v); echo "<br>";}
+                       echo "</font>";
+               }
+               
+               print "<p>Testing MetaIndexes</p>";
+               $a = $db->MetaIndexes('ADOXYZ',true);
+               if ($a===false) print "<b>MetaIndexes not supported</b></p>";
+               else {
+                       print "<p>Indexes of ADOXYZ: <font size=1><br>";
+                       foreach($a as $v) {print_r($v); echo "<br>";}
+                       echo "</font>";
+               }
+               print "<p>Testing MetaPrimaryKeys</p>";
+               $a = $db->MetaPrimaryKeys('ADOXYZ');
+               var_dump($a);
+       }
+       $rs = &$db->Execute('delete from ADOXYZ');
+       if ($rs) $rs->Close();
+       
+       $db->debug = false;
+       
+       
+       switch ($db->databaseType) {
+       case 'postgres7':
+       case 'postgres64':
+       case 'postgres':
+       case 'ibase':
+               print "<p>Encode=".$db->BlobEncode("abc\0d\"'
+ef")."</p>";//'
+
+               print "<p>Testing Foreign Keys</p>";
+               $arr = $db->MetaForeignKeys('adoxyz',false,true);
+               print_r($arr);
+               if (!$arr) Err("Bad MetaForeignKeys");
+               break;
+       
+       case 'odbc_mssql':
+       case 'mssqlpo':
+               print "<p>Testing Foreign Keys</p>";
+               $arr = $db->MetaForeignKeys('Orders',false,true);
+               print_r($arr);
+               if (!$arr) Err("Bad MetaForeignKeys");
+               if ($db->databaseType == 'odbc_mssql') break;
+       
+       case 'mssql': 
+       
+               
+/*
+ASSUME Northwind available...
+
+CREATE PROCEDURE SalesByCategory
+       @CategoryName nvarchar(15), @OrdYear nvarchar(4) = '1998'
+AS
+IF @OrdYear != '1996' AND @OrdYear != '1997' AND @OrdYear != '1998' 
+BEGIN
+       SELECT @OrdYear = '1998'
+END
+
+SELECT ProductName,
+       TotalPurchase=ROUND(SUM(CONVERT(decimal(14,2), OD.Quantity * (1-OD.Discount) * OD.UnitPrice)), 0)
+FROM [Order Details] OD, Orders O, Products P, Categories C
+WHERE OD.OrderID = O.OrderID 
+       AND OD.ProductID = P.ProductID 
+       AND P.CategoryID = C.CategoryID
+       AND C.CategoryName = @CategoryName
+       AND SUBSTRING(CONVERT(nvarchar(22), O.OrderDate, 111), 1, 4) = @OrdYear
+GROUP BY ProductName
+ORDER BY ProductName
+GO
+*/
+               print "<h4>Testing Stored Procedures for mssql</h4>";
+               $saved = $db->debug;
+               $db->debug=true;
+               
+               $cat = 'Dairy Products';
+               $yr = '1998';
+               
+               $stmt = $db->PrepareSP('SalesByCategory');
+               $db->InParameter($stmt,$cat,'CategoryName');
+               $db->InParameter($stmt,$yr,'OrdYear');
+               $rs = $db->Execute($stmt);
+               rs2html($rs);
+               
+               $cat = 'Grains/Cereals';
+               $yr = 1998;
+               
+               $stmt = $db->PrepareSP('SalesByCategory');
+               $db->InParameter($stmt,$cat,'CategoryName');
+               $db->InParameter($stmt,$yr,'OrdYear');
+               $rs = $db->Execute($stmt);
+               rs2html($rs);
+               
+               /*
+               Test out params - works in 4.2.3 but not 4.3.0???:
+               
+                       CREATE PROCEDURE at_date_interval 
+                               @days INTEGER, 
+                               @start VARCHAR(20) OUT, 
+                               @end VARCHAR(20) OUT    
+                       AS 
+                       BEGIN 
+                               set @start = CONVERT(VARCHAR(20), getdate(), 101) 
+                               set @end =CONVERT(VARCHAR(20), dateadd(day, @days, getdate()), 101 ) 
+                       END
+                       GO
+               */
+               $db->debug=1;
+               $stmt = $db->PrepareSP('at_date_interval');
+               $days = 10;
+               $begin_date = '';
+               $end_date = '';
+               $db->InParameter($stmt,$days,'days', 4, SQLINT4); 
+               $db->OutParameter($stmt,$begin_date,'start', 20, SQLVARCHAR ); 
+               $db->OutParameter($stmt,$end_date,'end', 20, SQLVARCHAR ); 
+               $db->Execute($stmt);
+               if (empty($begin_date) or empty($end_date)) {
+                       Err("MSSQL SP Test for OUT Failed");
+                       print "begin=$begin_date end=$end_date<p>";
+               } else print "(Today +10days) = (begin=$begin_date end=$end_date)<p>";
+       
+               $db->debug = $saved;
+               break;
+       case 'oci8': 
+       case 'oci8po':
+               $saved = $db->debug;
+               $db->debug=true;
+               
+               print "<h4>Testing Foreign Keys</h4>";
+               $arr = $db->MetaForeignKeys('emp');
+               print_r($arr);
+               if (!$arr) Err("Bad MetaForeignKeys");
+               print "<h4>Testing Cursor Variables</h4>";
+/*
+-- TEST PACKAGE
+CREATE OR REPLACE PACKAGE adodb AS
+TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);
+PROCEDURE data_out(input IN varchar, output OUT varchar); 
+END adodb;
+/
+
+CREATE OR REPLACE PACKAGE BODY adodb AS
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS
+       BEGIN
+               OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;
+       END open_tab;
+       
+PROCEDURE data_out(input IN varchar, output OUT varchar) IS
+       BEGIN
+               output := 'Cinta Hati '||input;
+       END;
+END adodb;
+/
+*/
+               $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS,'A%'); END;");
+       
+               if ($rs && !$rs->EOF) {
+                       print "Test 1 RowCount: ".$rs->RecordCount()."<p>";
+               } else {
+                       print "<b>Error in using Cursor Variables 1</b><p>";
+               }
+               
+               
+               print "<h4>Testing Stored Procedures for oci8</h4>";
+               
+               $stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");
+               $a1 = 'Malaysia';
+               //$a2 = ''; # a2 doesn't even need to be defined!
+               $db->InParameter($stmt,$a1,'a1');
+               $db->OutParameter($stmt,$a2,'a2');
+               $rs = $db->Execute($stmt);
+               if ($rs) {
+                       if ($a2 !== 'Cinta Hati Malaysia') print "<b>Stored Procedure Error: a2 = $a2</b><p>";
+                       else echo  "OK: a2=$a2<p>";
+               } else {
+                       print "<b>Error in using Stored Procedure IN/Out Variables</b><p>";
+               }
+               
+               
+               $tname = 'A%';
+               
+               $stmt = $db->PrepareSP('select * from tab where tname like :tablename');
+               $db->Parameter($stmt,$tname,'tablename');
+               $rs = $db->Execute($stmt);
+               rs2html($rs);
+               
+               $db->debug = $saved;
+               break;
+       
+       default:
+               break;
+       }
+       $arr = array(
+               array(1,'Caroline','Miranda'),
+               array(2,'John','Lim'),
+               array(3,'Wai Hun','See')
+       );
+       $db->debug=1;
+       print "<p>Testing Bulk Insert of 3 rows</p>";
+
+       $sql = "insert into ADOXYZ (id,firstname,lastname) values (".$db->Param('0').",".$db->Param('1').",".$db->Param('2').")";
+       $db->StartTrans();
+       $db->Execute($sql,$arr);
+       $db->CompleteTrans();
+       $rs = $db->Execute('select * from ADOXYZ order by id');
+       if ($rs->RecordCount() != 3) Err("Bad bulk insert");
+       rs2html($rs);
+       
+       $db->Execute('delete from ADOXYZ');
+               
+       print "<p>Inserting 50 rows</p>";
+
+       for ($i = 0; $i < 5; $i++) {    
+
+       $time = $db->DBDate(time());
+       if (empty($HTTP_GET_VARS['hide'])) $db->debug = true;
+       switch($db->databaseType){
+       case 'mssqlpo':
+       case 'mssql':
+               $sqlt = "CREATE TABLE mytable (
+  row1 INT  IDENTITY(1,1) NOT NULL,
+  row2 varchar(16),
+  PRIMARY KEY  (row1))";
+               //$db->debug=1;
+               if (!$db->Execute("delete from mytable")) 
+                       $db->Execute($sqlt);
+                       
+               $ok = $db->Execute("insert into mytable (row2) values ('test')");
+               $ins_id=$db->Insert_ID();
+               echo "Insert ID=";var_dump($ins_id);
+               if ($ins_id == 0) Err("Bad Insert_ID()");
+               $ins_id2 = $db->GetOne("select row1 from mytable");
+               if ($ins_id != $ins_id2) Err("Bad Insert_ID() 2");
+               
+               $arr = array(0=>'Caroline',1=>'Miranda');
+               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)";
+               break;
+               
+       case 'mysql':
+               $sqlt = "CREATE TABLE `mytable` (
+  `row1` int(11) NOT NULL auto_increment,
+  `row2` varchar(16) NOT NULL default '',
+  PRIMARY KEY  (`row1`),
+  KEY `myindex` (`row1`,`row2`)
+) ";
+               if (!$db->Execute("delete from mytable")) 
+                       $db->Execute($sqlt);
+                       
+               $ok = $db->Execute("insert into mytable (row2) values ('test')");
+               $ins_id=$db->Insert_ID();
+               echo "Insert ID=";var_dump($ins_id);
+               if ($ins_id == 0) Err("Bad Insert_ID()");
+               $ins_id2 = $db->GetOne("select row1 from mytable");
+               if ($ins_id != $ins_id2) Err("Bad Insert_ID() 2");
+               
+       default:
+               $arr = array(0=>'Caroline',1=>'Miranda');
+               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,?,?,$time)";
+               break;
+       
+       case 'oci8':
+       case 'oci805':
+               $arr = array('first'=>'Caroline','last'=>'Miranda');
+               $amt = rand() % 100;
+               $sql = "insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+0,:first,:last,$time)";                
+               break;
+       }
+       if ($i & 1) {
+               $sql = $db->Prepare($sql);
+       }
+       $rs = $db->Execute($sql,$arr);
+               
+       if ($rs === false) Err( 'Error inserting with parameters');
+       else $rs->Close();
+       $db->debug = false;
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+1,'John','Lim',$time)");
+       /*$ins_id=$db->Insert_ID();
+       echo "Insert ID=";var_dump($ins_id);*/
+       if ($db->databaseType == 'mysql') if ($ins_id == 0) Err('Bad Insert_ID');
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+2,'Mary','Lamb',$time )");
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+3,'George','Washington',$time )");
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+4,'Mr. Alan','Tam',$time )");
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+5,'Alan',".$db->quote("Turing'ton").",$time )");
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created)values ($i*10+6,'Serena','Williams',$time )");
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+7,'Yat Sun','Sun',$time )");
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+8,'Wai Hun','See',$time )");
+       $db->Execute("insert into ADOXYZ (id,firstname,lastname,created) values ($i*10+9,'Steven','Oey',$time )");
+       } // for
+       if (1) {
+       $db->debug=1;
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+       $cnt = $db->GetOne("select count(*) from ADOXYZ");
+       $rs = $db->Execute('update ADOXYZ set id=id+1');        
+       if (!is_object($rs)) {
+               print_r($rs);
+               err("Update should return object");
+       }
+       if (!$rs) err("Update generated error");
+       
+       $nrows = $db->Affected_Rows();   
+       if ($nrows === false) print "<p><b>Affected_Rows() not supported</b></p>";
+       else if ($nrows != $cnt)  print "<p><b>Affected_Rows() Error: $nrows returned (should be 50) </b></p>";
+       else print "<p>Affected_Rows() passed</p>";
+       }
+       $db->debug = false;
+       
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+ //////////////////////////////////////////////////////////////////////////////////////////
+       
+       $rs = $db->Execute("select * from ADOXYZ where firstname = 'not known'");
+       if (!$rs ||  !$rs->EOF) print "<p><b>Error on empty recordset</b></p>";
+       else if ($rs->RecordCount() != 0) {
+               print "<p><b>Error on RecordCount. Should be 0. Was ".$rs->RecordCount()."</b></p>"; 
+               print_r($rs->fields);
+       }
+       if ($db->databaseType !== 'odbc') {
+               $rs = &$db->Execute("select id,firstname,lastname,created,".$db->random." from ADOXYZ order by id");
+               if ($rs) {
+                       if ($rs->RecordCount() != 50) {
+                               print "<p><b>RecordCount returns ".$rs->RecordCount()."</b></p>";
+                               $poc = $rs->PO_RecordCount('ADOXYZ');
+                               if ($poc == 50) print "<p> &nbsp; &nbsp; PO_RecordCount passed</p>";
+                               else print "<p><b>PO_RecordCount returns wrong value: $poc</b></p>";
+                       } else print "<p>RecordCount() passed</p>";
+                       if (isset($rs->fields['firstname'])) print '<p>The fields columns can be indexed by column name.</p>';
+                       else {
+                               Err( '<p>The fields columns <i>cannot</i> be indexed by column name.</p>');
+                               print_r($rs->fields);
+                       }
+                       if (empty($HTTP_GET_VARS['hide'])) rs2html($rs);
+               }
+               else print "<b>Error in Execute of SELECT with random</b></p>";
+       }
+       $val = $db->GetOne("select count(*) from ADOXYZ");
+        if ($val == 50) print "<p>GetOne returns ok</p>";
+        else print "<p><b>Fail: GetOne returns $val</b></p>";
+
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+       $val = $db->GetRow("select count(*) from ADOXYZ");
+        if ($val[0] == 50 and sizeof($val) == 1) print "<p>GetRow returns ok</p>";
+        else {
+               print_r($val);
+               print "<p><b>Fail: GetRow returns {$val[0]}</b></p>";
+       }
+
+       print "<p>FetchObject/FetchNextObject Test</p>";
+       $rs = &$db->Execute('select * from ADOXYZ');
+       
+       if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
+       
+       while ($o = $rs->FetchNextObject()) { // calls FetchObject internally
+               if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {
+                       print_r($o);
+                       print "<p><b>Firstname is not string</b></p>";
+                       break;
+               }
+       }
+       
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+       print "<p>FetchObject/FetchNextObject Test 2</p>";
+       
+       $rs = &$db->Execute('select * from ADOXYZ');
+       if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
+       print_r($rs->fields);
+       while ($o = $rs->FetchNextObject()) { // calls FetchObject internally
+               if (!is_string($o->FIRSTNAME) || !is_string($o->LASTNAME)) {
+                       print_r($o);
+                       print "<p><b>Firstname is not string</b></p>";
+                       break;
+               }
+       }
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+       
+       $savefetch = $ADODB_FETCH_MODE;
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+       
+       print "<p>CacheSelectLimit  Test</p>";
+       $db->debug=1;
+       $rs = $db->CacheSelectLimit('  select  id, firstname from  ADOXYZ order by id',2);
+       if ($rs && !$rs->EOF) {
+               if (isset($rs->fields[0])) {
+                       Err("ASSOC has numeric fields");
+                       print_r($rs->fields);
+               }
+               if ($rs->fields['id'] != 1)  {Err("Error"); print_r($rs->fields);};
+               if (trim($rs->fields['firstname']) != 'Caroline')  {print Err("Error 2"); print_r($rs->fields);};
+               $rs->MoveNext();
+               if ($rs->fields['id'] != 2)  {Err("Error 3"); print_r($rs->fields);};
+               $rs->MoveNext();
+               if (!$rs->EOF) {
+                       Err("Error EOF");
+                       print_r($rs);
+               }
+       }
+       
+       print "<p>FETCH_MODE = ASSOC: Should get 1, Caroline</p>";
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',2);
+       if ($rs && !$rs->EOF) {
+               if ($rs->fields['id'] != 1)  {Err("Error 1"); print_r($rs->fields);};
+               if (trim($rs->fields['firstname']) != 'Caroline')  {Err("Error 2"); print_r($rs->fields);};
+               $rs->MoveNext();
+               if ($rs->fields['id'] != 2)  {Err("Error 3"); print_r($rs->fields);};
+               $rs->MoveNext();
+               if (!$rs->EOF) Err("Error EOF");
+               else if (is_array($rs->fields) || $rs->fields) {
+                       Err("Error: ## fields should be set to false on EOF");
+                       print_r($rs->fields);
+               }
+       }
+       
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+       print "<p>FETCH_MODE = NUM: Should get 1, Caroline</p>";
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);
+       if ($rs && !$rs->EOF) {
+               if (isset($rs->fields['id'])) Err("FETCH_NUM has ASSOC fields");
+               if ($rs->fields[0] != 1)  {Err("Error 1"); print_r($rs->fields);};
+               if (trim($rs->fields[1]) != 'Caroline')  {Err("Error 2");print_r($rs->fields);};
+               $rs->MoveNext();
+               if (!$rs->EOF) Err("Error EOF");
+
+       }
+       $ADODB_FETCH_MODE = $savefetch;
+       
+       $db->debug = false;
+       print "<p>GetRowAssoc Upper: Should get 1, Caroline</p>";
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);
+       if ($rs && !$rs->EOF) {
+               $arr = &$rs->GetRowAssoc();
+               if ($arr['ID'] != 1) {Err("Error 1");print_r($arr);};
+               if (trim($arr['FIRSTNAME']) != 'Caroline') {Err("Error 2"); print_r($arr);};
+               $rs->MoveNext();
+               if (!$rs->EOF) Err("Error EOF");
+
+       }
+       print "<p>GetRowAssoc Lower: Should get 1, Caroline</p>";
+       $rs = &$db->SelectLimit('select id,firstname from ADOXYZ order by id',1);
+       if ($rs && !$rs->EOF) {
+               $arr = &$rs->GetRowAssoc(false);
+               if ($arr['id'] != 1) {Err("Error 1"); print_r($arr);};
+               if (trim($arr['firstname']) != 'Caroline') {Err("Error 2"); print_r($arr);};
+
+       }
+       
+       print "<p>GetCol Test</p>";
+       $col = $db->GetCol('select distinct firstname from adoxyz order by 1');
+       if (!is_array($col)) Err("Col size is wrong");
+       if (trim($col[0]) != 'Alan' or trim($col[9]) != 'Yat Sun') Err("Col elements wrong");
+
+       $db->debug = true;
+       print "<p>SelectLimit Distinct Test 1: Should see Caroline, John and Mary</p>";
+       $rs = &$db->SelectLimit('select distinct * from ADOXYZ order by id',3);
+       $db->debug=false;
+
+       if ($rs && !$rs->EOF) {
+               if (trim($rs->fields[1]) != 'Caroline') Err("Error 1");
+               $rs->MoveNext();
+               if (trim($rs->fields[1]) != 'John') Err("Error 2");
+               $rs->MoveNext();
+               if (trim($rs->fields[1]) != 'Mary') Err("Error 3");
+               $rs->MoveNext();
+               if (! $rs->EOF) Err("Error EOF");
+               //rs2html($rs);
+       } else Err("Failed SelectLimit Test 1");
+       
+       print "<p>SelectLimit Test 2: Should see Mary, George and Mr. Alan</p>";
+       $rs = &$db->SelectLimit('select * from ADOXYZ order by id',3,2);
+       if ($rs && !$rs->EOF) {
+               if (trim($rs->fields[1]) != 'Mary') Err("Error 1");
+               $rs->MoveNext();
+               if (trim($rs->fields[1]) != 'George')Err("Error 2");
+               $rs->MoveNext();
+               if (trim($rs->fields[1]) != 'Mr. Alan') Err("Error 3");
+               $rs->MoveNext();
+               if (! $rs->EOF) Err("Error EOF");
+       //      rs2html($rs);
+       }
+        else Err("Failed SelectLimit Test 2");
+       
+       print "<p>SelectLimit Test 3: Should see Wai Hun and Steven</p>";
+       $db->debug=1;
+       global $A; $A=1;
+       $rs = &$db->SelectLimit('select * from ADOXYZ order by id',-1,48);
+       $A=0;
+       if ($rs && !$rs->EOF) {
+               if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
+               if (trim($rs->fields[1]) != 'Wai Hun') Err("Error 1 ".$rs->fields[1]);
+               $rs->MoveNext();
+               if (trim($rs->fields[1]) != 'Steven') Err("Error 2 ".$rs->fields[1]);
+               $rs->MoveNext();
+               if (! $rs->EOF) {
+                       Err("Error EOF");
+               }
+               //rs2html($rs);
+       }
+        else Err("Failed SelectLimit Test 3");
+               $db->debug = false;
+       
+       
+       $rs = &$db->Execute("select * from ADOXYZ order by id");
+       print "<p>Testing Move()</p>";  
+       if (!$rs)Err( "Failed Move SELECT");
+       else {
+               if (!$rs->Move(2)) {
+                       if (!$rs->canSeek) print "<p>$db->databaseType: <b>Move(), MoveFirst() nor MoveLast() not supported.</b></p>";
+                       else print '<p><b>RecordSet->canSeek property should be set to false</b></p>';
+               } else {
+                       $rs->MoveFirst();
+                       if (trim($rs->Fields("firstname")) != 'Caroline') {
+                               print "<p><b>$db->databaseType: MoveFirst failed -- probably cannot scroll backwards</b></p>";
+                       }
+                       else print "MoveFirst() OK<BR>";
+                                               
+                                               // Move(3) tests error handling -- MoveFirst should not move cursor
+                       $rs->Move(3);
+                       if (trim($rs->Fields("firstname")) != 'George') {
+                               print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) failed</b></p>";
+                       } else print "Move(3) OK<BR>";
+                                               
+                       $rs->Move(7);
+                       if (trim($rs->Fields("firstname")) != 'Yat Sun') {
+                               print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(7) failed</b></p>";
+                               print_r($rs);
+                       } else print "Move(7) OK<BR>";
+                       if ($rs->EOF) Err("Move(7) is EOF already");
+                       $rs->MoveLast();
+                       if (trim($rs->Fields("firstname")) != 'Steven'){
+                                print '<p>'.$rs->Fields("id")."<b>$db->databaseType: MoveLast() failed</b></p>";
+                                print_r($rs);
+                       }else print "MoveLast() OK<BR>";
+                       $rs->MoveNext();
+                       if (!$rs->EOF) err("Bad MoveNext");
+                       if ($rs->canSeek) {
+                               $rs->Move(3);
+                               if (trim($rs->Fields("firstname")) != 'George') {
+                                       print '<p>'.$rs->Fields("id")."<b>$db->databaseType: Move(3) after MoveLast failed</b></p>";
+                                       
+                               } else print "Move(3) after MoveLast() OK<BR>";
+                       }
+                       
+                       print "<p>Empty Move Test";
+                       $rs = $db->Execute("select * from ADOXYZ where id > 0 and id < 0");
+                       $rs->MoveFirst();
+                       if (!$rs->EOF || $rs->fields) Err("Error in empty move first");
+               }
+       }
+       
+       $rs = $db->Execute('select * from ADOXYZ where id = 2');
+       if ($rs->EOF || !is_array($rs->fields)) Err("Error in select");
+       $rs->MoveNext();
+       if (!$rs->EOF) Err("Error in EOF (xx) ");
+ //    $db->debug=true;
+       print "<p>Testing ADODB_FETCH_ASSOC and concat: concat firstname and lastname</p>";
+
+       $save = $ADODB_FETCH_MODE;
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+       if ($db->dataProvider == 'postgres') {
+               $sql = "select ".$db->Concat('cast(firstname as varchar)',$db->qstr(' '),'lastname')." as fullname,id from ADOXYZ";
+               $rs = &$db->Execute($sql);
+       } else {
+               $sql = "select distinct ".$db->Concat('firstname',$db->qstr(' '),'lastname')." as fullname,id from ADOXYZ";
+               $rs = &$db->Execute($sql);
+       }
+       if ($rs) {
+               if (empty($HTTP_GET_VARS['hide'])) rs2html($rs);
+       } else {
+               Err( "Failed Concat:".$sql);
+       }
+       $ADODB_FETCH_MODE = $save;
+       print "<hr>Testing GetArray() ";
+       //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+       
+       $rs = &$db->Execute("select * from ADOXYZ order by id");
+       if ($rs) {
+               $arr = &$rs->GetArray(10);
+               if (sizeof($arr) != 10 || trim($arr[1][1]) != 'John' || trim($arr[1][2]) != 'Lim') print $arr[1][1].' '.$arr[1][2]."<b> &nbsp; ERROR</b><br>";
+               else print " OK<BR>";
+       }
+       
+       $arr = $db->GetArray("select x from ADOXYZ");
+       $e = $db->ErrorMsg(); $e2 = $db->ErrorNo();
+       echo "Testing error handling, should see illegal column 'x' error=<i>$e ($e2) </i><br>";
+       if (!$e || !$e2) Err("Error handling did not work");
+       print "Testing FetchNextObject for 1 object ";
+       $rs = &$db->Execute("select distinct lastname,firstname from ADOXYZ where firstname='Caroline'");
+       $fcnt = 0;
+       if ($rs)
+       while ($o = $rs->FetchNextObject()) {
+               $fcnt += 1;     
+       }
+       if ($fcnt == 1) print " OK<BR>";
+       else print "<b>FAILED</b><BR>";
+       
+       $stmt = $db->Prepare("select * from ADOXYZ where id < 3");
+       $rs = $db->Execute($stmt);
+       if (!$rs) Err("Prepare failed");
+       else {
+               $arr = $rs->GetArray();
+               if (!$arr) Err("Prepare failed 2");
+               if (sizeof($arr) != 2) Err("Prepare failed 3");
+       }
+       print "Testing GetAssoc() ";
+       $savecrecs = $ADODB_COUNTRECS;
+       $ADODB_COUNTRECS = false;
+       $rs = &$db->Execute("select distinct lastname,firstname from ADOXYZ");
+       if ($rs) {
+               $arr = $rs->GetAssoc();
+               //print_r($arr);
+               if (trim($arr['See']) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";
+               else print " OK 1";
+       }
+       
+       $arr = &$db->GetAssoc("select distinct lastname,firstname from ADOXYZ");
+       if ($arr) {
+               //print_r($arr);
+               if (trim($arr['See']) != 'Wai Hun') print $arr['See']." &nbsp; <b>ERROR</b><br>";
+               else print " OK 2<BR>";
+       }
+       // Comment this out to test countrecs = false
+       $ADODB_COUNTRECS = $savecrecs;
+       
+       for ($loop=0; $loop < 1; $loop++) {
+       print "Testing GetMenu() and CacheExecute<BR>";
+       $db->debug = true;
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+       
+       if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu('menu','Steven').'<BR>'; 
+       else print " Fail<BR>";
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+       
+       if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu('menu','Steven',false).'<BR>';
+       else print " Fail<BR>";
+       
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+       if ($rs) print ' Multiple, Alan selected: '. $rs->GetMenu('menu','Alan',false,true).'<BR>';
+       else print " Fail<BR>";
+       print '</p><hr>';
+       
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+       if ($rs) {
+               print ' Multiple, Alan and George selected: '. $rs->GetMenu('menu',array('Alan','George'),false,true);
+               if (empty($rs->connection)) print "<b>Connection object missing from recordset</b></br>";
+       } else print " Fail<BR>";
+       print '</p><hr>';
+       
+       print "Testing GetMenu2() <BR>";
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+       if ($rs) print 'With blanks, Steven selected:'. $rs->GetMenu2('menu',('Oey')).'<BR>'; 
+       else print " Fail<BR>";
+       $rs = &$db->CacheExecute(4,"select distinct firstname,lastname from ADOXYZ");
+       if ($rs) print ' No blanks, Steven selected: '. $rs->GetMenu2('menu',('Oey'),false).'<BR>';
+       else print " Fail<BR>";
+       }
+       
+       $db->debug = false;
+       
+       // phplens
+       
+       $sql = 'select * from ADOXYZ where 0=1';
+       echo "<p>**Testing '$sql' (phplens compat 1)</p>";
+       $rs = &$db->Execute($sql);
+       if (!$rs) err( "<b>No recordset returned for '$sql'</b>");
+       if (!$rs->FieldCount()) err( "<b>No fields returned for $sql</b>");
+       if (!$rs->FetchField(1)) err( "<b>FetchField failed for $sql</b>");
+       
+       $sql = 'select * from ADOXYZ order by 1';
+       echo "<p>**Testing '$sql' (phplens compat 2)</p>";
+       $rs = &$db->Execute($sql);
+       if (!$rs) err( "<b>No recordset returned for '$sql'<br>".$db->ErrorMsg()."</b>");
+       
+       
+       $sql = 'select * from ADOXYZ order by 1,1';
+       echo "<p>**Testing '$sql' (phplens compat 3)</p>";
+       $rs = &$db->Execute($sql);
+       if (!$rs) err( "<b>No recordset returned for '$sql'<br>".$db->ErrorMsg()."</b>");
+       
+       
+       // Move
+       $rs1 = &$db->Execute("select id from ADOXYZ where id <= 2 order by 1");
+       $rs2 = &$db->Execute("select id from ADOXYZ where id = 3 or id = 4 order by 1");
+
+       if ($rs1) $rs1->MoveLast();
+       if ($rs2) $rs2->MoveLast();
+       
+       if (empty($rs1) || empty($rs2) || $rs1->fields[0] != 2 || $rs2->fields[0] != 4) {
+               $a = $rs1->fields[0];
+               $b = $rs2->fields[0];
+               print "<p><b>Error in multiple recordset test rs1=$a rs2=$b (should be rs1=2 rs2=4)</b></p>";
+       } else
+               print "<p>Testing multiple recordsets OK</p>";
+               
+       
+       echo "<p> GenID test: ";
+       for ($i=1; $i <= 10; $i++) 
+               echo  "($i: ",$val = $db->GenID($db->databaseType.'abcseq6' ,5), ") ";
+       if ($val == 0) Err("GenID not supported");
+       
+       if ($val) {
+               $db->DropSequence('abc_seq2');
+               $db->CreateSequence('abc_seq2');
+               $val = $db->GenID('abc_seq2');
+               $db->DropSequence('abc_seq2');
+               $db->CreateSequence('abc_seq2');
+               $val = $db->GenID('abc_seq2');
+               if ($val != 1) Err("Drop and Create Sequence not supported ($val)");
+       }
+       echo "<p>";
+       
+       if (substr($db->dataProvider,0,3) != 'notused') { // used to crash ado
+               $sql = "select firstnames from adoxyz";
+               print "<p>Testing execution of illegal statement: <i>$sql</i></p>";
+               if ($db->Execute($sql) === false) {
+                       print "<p>This returns the following ErrorMsg(): <i>".$db->ErrorMsg()."</i> and ErrorNo(): ".$db->ErrorNo().'</p>';
+               } else 
+                       print "<p><b>Error in error handling -- Execute() should return false</b></p>";
+       } else 
+               print "<p><b>ADO skipped error handling of bad select statement</b></p>";
+       
+       print "<p>ASSOC TEST 2<br>";
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+       $rs = $db->query('select * from adoxyz order by id');
+       if ($ee = $db->ErrorMsg()) {
+               Err("Error message=$ee");
+       }
+       if ($ee = $db->ErrorNo()) {
+               Err("Error No = $ee");
+       }
+       print_r($rs->fields);
+       for($i=0;$i<$rs->FieldCount();$i++) 
+       { 
+               $fld=$rs->FetchField($i); 
+               print "<br> Field name is ".$fld->name; 
+               print " ".$rs->Fields($fld->name); 
+       } 
+
+               
+       print "<p>BOTH TEST 2<br>";
+       if ($db->dataProvider == 'ado') {
+               print "<b>ADODB_FETCH_BOTH not supported</b> for dataProvider=".$db->dataProvider."<br>";
+       } else {
+               $ADODB_FETCH_MODE = ADODB_FETCH_BOTH;
+               $rs = $db->query('select * from adoxyz order by id');
+               for($i=0;$i<$rs->FieldCount();$i++) 
+               { 
+                       $fld=$rs->FetchField($i); 
+                       print "<br> Field name is ".$fld->name; 
+                       print " ".$rs->Fields($fld->name); 
+               } 
+       }
+       
+       print "<p>NUM TEST 2<br>";
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+       $rs = $db->query('select * from adoxyz order by id');
+       for($i=0;$i<$rs->FieldCount();$i++) 
+       { 
+               $fld=$rs->FetchField($i); 
+               print "<br> Field name is ".$fld->name; 
+               print " ".$rs->Fields($fld->name); 
+       } 
+       
+       print "<p>ASSOC Test of SelectLimit<br>";
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+       $rs = $db->selectlimit('select * from adoxyz order by id',3,4);
+       $cnt = 0;
+       while ($rs && !$rs->EOF) {
+               $cnt += 1;
+               if (!isset($rs->fields['firstname'])) {
+                       print "<br><b>ASSOC returned numeric field</b></p>";
+                       break;
+               }
+               $rs->MoveNext();
+       }
+       if ($cnt != 3) print "<br><b>Count should be 3, instead it was $cnt</b></p>";
+       
+       
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+       if ($db->sysDate) {
+               $saved = $db->debug;
+               $db->debug = 1;
+               $rs = $db->Execute("select {$db->sysDate} from adoxyz where id=1");
+               if (ADORecordSet::UnixDate(date('Y-m-d')) != $rs->UnixDate($rs->fields[0])) {
+                       print "<p><b>Invalid date {$rs->fields[0]}</b></p>";
+               } else
+                       print "<p>Passed \$sysDate test ({$rs->fields[0]})</p>";
+               
+               print_r($rs->FetchField(0));
+               print time();
+               $db->debug=$saved;
+       } else {
+               print "<p><b>\$db->sysDate not defined</b></p>";
+       }
+
+       print "<p>Test CSV</p>";
+       include_once('../toexport.inc.php');
+       //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+       $rs = $db->SelectLimit('select id,firstname,lastname,created,\'He, he\' he,\'"\' q  from adoxyz',10);   
+       
+       print "<pre>";
+       print rs2csv($rs);
+       print "</pre>";
+       
+       $rs = $db->SelectLimit('select id,firstname,lastname,created,\'The      "young man", he said\' from adoxyz',10);        
+       
+       print "<pre>";
+       rs2tabout($rs);
+       print "</pre>";
+       
+       //print " CacheFlush ";
+       //$db->CacheFlush();
+       
+       $date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A');
+       $sql = "SELECT $date from ADOXYZ";
+       print "<p>Test SQLDate: ".htmlspecialchars($sql)."</p>";
+       $rs = $db->SelectLimit($sql,1);
+       $d = date('d-m-M-Y-').'Q'.(ceil(date('m')/3.0)).date(' h:i:s A');
+       if (!$rs) Err("SQLDate query returned no recordset");
+       else if ($d != $rs->fields[0]) Err("SQLDate 1 failed expected: <br>act:$d <br>sql:".$rs->fields[0]);
+       
+       $date = $db->SQLDate('d-m-M-Y-\QQ h:i:s A',$db->DBDate("1974-02-25"));
+       $sql = "SELECT $date from ADOXYZ";
+       print "<p>Test SQLDate: ".htmlspecialchars($sql)."</p>";
+       $rs = $db->SelectLimit($sql,1);
+       $ts = ADOConnection::UnixDate('1974-02-25');
+       $d = date('d-m-M-Y-',$ts).'Q'.(ceil(date('m',$ts)/3.0)).date(' h:i:s A',$ts);
+       if (!$rs) Err("SQLDate query returned no recordset");
+       else if ($d != $rs->fields[0]) Err("SQLDate 2 failed expected: <br>act:$d <br>sql:".$rs->fields[0]);
+       
+       
+       print "<p>Test Filter</p>";
+       $db->debug = 1;
+       
+       $rs = $db->SelectLimit('select * from ADOXYZ where id < 3 order by id');
+       
+       $rs = RSFilter($rs,'do_strtolower');
+       if (trim($rs->fields[1]) != 'caroline'  && trim($rs->fields[2]) != 'miranda') {
+               err('**** RSFilter failed');
+               print_r($rs->fields);
+       }
+       
+       rs2html($rs);
+               
+       $db->debug=1;
+       
+       
+       print "<p>Test Replace</p>";
+       
+       $ret = $db->Replace('adoxyz', 
+               array('id'=>1,'firstname'=>'Caroline','lastname'=>'Miranda'),
+               array('id'),
+               $autoq = true);
+       if (!$ret) echo "<p>Error in replacing existing record</p>";
+       else {
+               $saved = $db->debug;
+               $db->debug = 0;
+               $savec = $ADODB_COUNTRECS;
+               $ADODB_COUNTRECS = true;
+               $rs = $db->Execute('select * FROM ADOXYZ where id=1');
+               $db->debug = $saved;
+               if ($rs->RecordCount() != 1) {
+                       $cnt = $rs->RecordCount();
+                       rs2html($rs);
+                       print "<b>Error - Replace failed, count=$cnt</b><p>";
+               }
+               $ADODB_COUNTRECS = $savec;
+       }
+       $ret = $db->Replace('adoxyz', 
+               array('id'=>1000,'firstname'=>'Harun','lastname'=>'Al-Rashid'),
+               array('id','firstname'),
+               $autoq = true);
+       if ($ret != 2) print "<b>Replace failed: </b>";
+       print "test A return value=$ret (2 expected) <p>";
+       
+       $ret = $db->Replace('adoxyz', 
+               array('id'=>1000,'firstname'=>'Sherazade','lastname'=>'Al-Rashid'),
+               'id',
+               $autoq = true);
+       if ($ret != 1) 
+               if ($db->dataProvider == 'ibase' && $ret == 2);
+               else print "<b>Replace failed: </b>";
+       print "test B return value=$ret (1 or if ibase then 2 expected) <p>";
+       
+       print "<h3>rs2rs Test</h3>";
+       
+       $rs = $db->Execute('select * from adoxyz order by id');
+       $rs = $db->_rs2rs($rs);
+       $rs->valueX = 'X';
+       $rs->MoveNext();
+       $rs = $db->_rs2rs($rs);
+       if (!isset($rs->valueX)) err("rs2rs does not preserve array recordsets");
+       if (reset($rs->fields) != 1) err("rs2rs does not move to first row");
+
+       /////////////////////////////////////////////////////////////
+       include_once('../pivottable.inc.php');
+       print "<h3>Pivot Test</h3>";
+       $db->debug=true;
+       $sql = PivotTableSQL(
+               $db,                    # adodb connection
+               'adoxyz',               # tables
+               'firstname',    # row fields
+               'lastname',             # column fields 
+               false,                  # join
+               'ID',                   # sum
+               'Sum ',                 # label for sum
+               'sum',                  # aggregate function
+               true
+       );
+       $rs = $db->Execute($sql);
+       if ($rs) rs2html($rs);
+       else Err("Pivot sql error");
+       
+       $db->debug=false;
+       include_once "PEAR.php";
+       
+       // PEAR TESTS BELOW
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+       $pear = true;
+       $rs = $db->query('select * from adoxyz where id>0 and id<10 order by id');
+       
+       $i = 0;
+       if ($rs && !$rs->EOF) {
+               while ($arr = $rs->fetchRow()) {
+                       $i++;
+                       //print "$i ";
+                       if ($arr[0] != $i) {
+                               print_r($arr);
+                               print "<p><b>PEAR DB emulation error 1.</b></p>";
+                               $pear = false;
+                               break;
+                       }
+               }
+               $rs->Close();
+       }
+       
+       
+       if ($i != $db->GetOne('select count(*) from adoxyz where id>0 and id<10')) {
+               print "<p><b>PEAR DB emulation error 1.1 EOF ($i)</b></p>";
+               $pear = false;
+       }
+       
+       $rs = $db->limitQuery('select * from adoxyz where id>0 order by id',$i=3,$top=3);
+       $i2 = $i;
+       if ($rs && !$rs->EOF) {
+
+               while (!is_object($rs->fetchInto($arr))) {
+                       $i2++;
+                       
+       //                      print_r($arr);
+       //              print "$i ";print_r($arr);
+                       if ($arr[0] != $i2) {
+                               print "<p><b>PEAR DB emulation error 2.</b></p>";
+                               $pear = false;
+                               break;
+                       }
+               }
+               $rs->Close();
+       }
+       if ($i2 != $i+$top) {
+               print "<p><b>PEAR DB emulation error 2.1 EOF (correct=$i+$top, actual=$i2)</b></p>";
+               $pear = false;
+       }
+       
+       if ($pear) print "<p>PEAR DB emulation passed.</p>";
+       
+       $rs = $db->SelectLimit("select ".$db->sysDate." from adoxyz",1);
+       $date = $rs->fields[0];
+       if (!$date) Err("Bad sysDate");
+       else {
+               $ds = $db->UserDate($date,"d m Y");
+               if ($ds != date("d m Y")) Err("Bad UserDate: ".$ds);
+               else echo "Passed UserDate: $ds<p>";
+       }
+       $db->debug=1;
+       if ($db->dataProvider == 'oci8') 
+               $rs = $db->SelectLimit("select to_char(".$db->sysTimeStamp.",'YYYY-MM-DD HH24:MI:SS') from adoxyz",1);
+       else 
+               $rs = $db->SelectLimit("select ".$db->sysTimeStamp." from adoxyz",1);
+       $date = $rs->fields[0];
+       if (!$date) Err("Bad sysTimeStamp");
+       else {
+               $ds = $db->UserTimeStamp($date,"H \\h\\r\\s-d m Y");
+               if ($ds != date("H \\h\\r\\s-d m Y")) Err("Bad UserTimeStamp: ".$ds.", correct is ".date("H \\h\\r\\s-d m Y"));
+               else echo "Passed UserTimeStamp: $ds<p>";
+               
+               $date = 100;
+               $ds = $db->UserTimeStamp($date,"H \\h\\r\\s-d m Y");
+               $ds2 = date("H \\h\\r\\s-d m Y",$date);
+               if ($ds != $ds2) Err("Bad UserTimeStamp 2: $ds: $ds2");
+               else echo "Passed UserTimeStamp 2: $ds<p>";
+       }
+       if ($db->hasTransactions) {
+               //$db->debug=1;
+               echo "<p>Testing StartTrans CompleteTrans</p>";
+               $db->raiseErrorFn = false;
+               $db->StartTrans();
+               $rs = $db->Execute('select * from notable');
+                       $db->StartTrans();
+                               $db->BeginTrans();
+                       $db->Execute("update ADOXYZ set firstname='Carolx' where id=1");
+                               $db->CommitTrans();
+                       $db->CompleteTrans();
+               $rez = $db->CompleteTrans();
+               if ($rez !== false) {
+                       if (is_null($rez)) Err("Error: _transOK not modified");
+                       else Err("Error: CompleteTrans (1) should have failed");
+               } else {
+                       $name = $db->GetOne("Select firstname from ADOXYZ where id=1");
+                       if ($name == "Carolx") Err("Error: CompleteTrans (2) should have failed");
+                       else echo "<p> -- Passed StartTrans test1 - rolling back</p>";
+               }
+               
+               $db->StartTrans();
+                       $db->BeginTrans();
+               $db->Execute("update ADOXYZ set firstname='Carolx' where id=1");
+                       $db->RollbackTrans();
+               $rez = $db->CompleteTrans();
+               if ($rez !== true) Err("Error: CompleteTrans (1) should have succeeded");
+               else {
+                       $name = $db->GetOne("Select firstname from ADOXYZ where id=1");
+                       if (trim($name) != "Carolx") Err("Error: CompleteTrans (2) should have succeeded, returned name=$name");
+                       else echo "<p> -- Passed StartTrans test2 - commiting</p>";
+               }
+       }
+       
+       
+       global $TESTERRS;
+       $debugerr = true;
+       
+       global $ADODB_LANG;$ADODB_LANG = 'fr';
+       $db->debug = false;
+       $TESTERRS = 0;
+       $db->raiseErrorFn = 'adodb_test_err';
+       global $ERRNO; // from adodb_test_err
+       $db->Execute('select * from nowhere');
+       $metae = $db->MetaError($ERRNO);
+       if ($metae !== DB_ERROR_NOSUCHTABLE) print "<p><b>MetaError=".$metae." wrong</b>, should be ".DB_ERROR_NOSUCHTABLE."</p>";
+       else print "<p>MetaError ok (".DB_ERROR_NOSUCHTABLE."): ".$db->MetaErrorMsg($metae)."</p>";
+       if ($TESTERRS != 1) print "<b>raiseErrorFn select nowhere failed</b><br>";
+       $rs = $db->Execute('select * from adoxyz');
+       if ($debugerr) print " Move";
+       $rs->Move(100);
+       $rs->_queryID = false;
+       if ($debugerr) print " MoveNext";
+       $rs->MoveNext();
+       if ($debugerr) print " $rs=false";
+       $rs = false;
+
+       print "<p>SetFetchMode() tests</p>";
+       $db->SetFetchMode(ADODB_FETCH_ASSOC);
+       $rs = $db->SelectLimit('select firstname from adoxyz',1);
+       //      var_dump($rs->fields);
+       if (!isset($rs->fields['firstname'])) Err("BAD FETCH ASSOC");
+       
+       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;    
+       $rs = $db->SelectLimit('select firstname from adoxyz',1);
+       //var_dump($rs->fields);
+       if (!isset($rs->fields['firstname'])) Err("BAD FETCH ASSOC");
+       
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;  
+       $db->SetFetchMode(ADODB_FETCH_NUM);
+       $rs = $db->SelectLimit('select firstname from adoxyz',1);
+       if (!isset($rs->fields[0])) Err("BAD FETCH NUM");
+       
+       print "<p>Test MetaTables again with SetFetchMode()</p>";
+       $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
+       $db->SetFetchMode(ADODB_FETCH_ASSOC);
+       print_r($db->MetaTables());
+       print "<p>";
+       ////////////////////////////////////////////////////////////////////
+       
+       $conn = NewADOConnection($db->databaseType);
+       $conn->raiseErrorFn = 'adodb_test_err';
+       @$conn->Connect('abc');
+       if ($TESTERRS == 2) print "raiseErrorFn tests passed<br>";
+       else print "<b>raiseErrorFn tests failed ($TESTERRS)</b><br>";
+       
+       
+       ////////////////////////////////////////////////////////////////////
+       
+       global $nocountrecs;
+       
+       if (isset($nocountrecs) && $ADODB_COUNTRECS) err("Error: \$ADODB_COUNTRECS is set");
+       if (empty($nocountrecs) && $ADODB_COUNTRECS==false) err("Error: \$ADODB_COUNTRECS is not set");
+
+       
+?>
+       </p>
+       <table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>
+       </p></form>
+<?php
+
+       if ($rs1) $rs1->Close();
+       if ($rs2) $rs2->Close();
+       if ($rs) $rs->Close();
+       $db->Close();
+       
+       if ($db->transCnt != 0) Err("Error in transCnt=$db->transCnt (should be 0)");
+       
+       
+       printf("<p>Total queries=%d; total cached=%d</p>",$EXECS+$CACHED, $CACHED);
+}
+
+function adodb_test_err($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)
+{
+global $TESTERRS,$ERRNO;
+
+       $ERRNO = $errno;
+       $TESTERRS += 1;
+       print "<i>** $dbms ($fn): errno=$errno &nbsp; errmsg=$errmsg ($p1,$p2)</i><br>";
+}
+
+//--------------------------------------------------------------------------------------
+
+
+set_time_limit(240); // increase timeout
+
+include("../tohtml.inc.php");
+include("../adodb.inc.php");
+include("../rsfilter.inc.php");
+
+/* White Space Check */
+
+if (isset($_SERVER['argv'][1])) {
+       //print_r($_SERVER['argv']);
+       $HTTP_GET_VARS[$_SERVER['argv'][1]] = 1;
+}
+
+if (@$HTTP_SERVER_VARS['COMPUTERNAME'] == 'TIGRESS') {
+       CheckWS('mysqlt');
+       CheckWS('postgres');
+       CheckWS('oci8po');
+       
+       CheckWS('firebird');
+       CheckWS('sybase');
+       CheckWS('informix');
+
+       CheckWS('ado_mssql');
+       CheckWS('ado_access');
+       CheckWS('mssql');
+       
+       CheckWS('vfp');
+       CheckWS('sqlanywhere');
+       CheckWS('db2');
+       CheckWS('access');
+       CheckWS('odbc_mssql');
+       //
+       CheckWS('oracle');
+       CheckWS('proxy');
+       CheckWS('fbsql');
+       print "White Space Check complete<p>";
+}
+if (sizeof($HTTP_GET_VARS) == 0) $testmysql = true;
+
+
+foreach($HTTP_GET_VARS as $k=>$v)  {
+       //global $$k;
+       $$k = $v;
+}      
+if (strpos(PHP_VERSION,'5') === 0) {
+       //$testaccess=1;
+       //$testmssql = 1;
+       //$testsqlite=1;
+}
+?>
+<html>
+<title>ADODB Testing</title>
+<body bgcolor=white>
+<H1>ADODB Test</H1>
+
+This script tests the following databases: Interbase, Oracle, Visual FoxPro, Microsoft Access (ODBC and ADO), MySQL, MSSQL (ODBC, native, ADO). 
+There is also support for Sybase, PostgreSQL.</p>
+For the latest version of ADODB, visit <a href=http://php.weblogs.com/ADODB>php.weblogs.com</a>.</p>
+
+Test <a href=test4.php>GetInsertSQL/GetUpdateSQL</a> &nbsp; 
+       <a href=testsessions.php>Sessions</a> &nbsp;
+       <a href=testpaging.php>Paging</a> &nbsp;
+       <a href=test-perf.php>Perf Monitor</a><p>
+<?php
+include('./testdatabases.inc.php');
+?>
+       
+<?php
+
+include_once('../adodb-time.inc.php');
+adodb_date_test();
+?>
+<p><i>ADODB Database Library  (c) 2000-2004 John Lim. All rights reserved. Released under BSD and LGPL.</i></p>
+</body>
+</html>
index 177aa8e94e9d81a4a3c3af3b619aca1b4375cb0e..14474666499c7a3488fe72dafcac4e790e13e85e 100644 (file)
@@ -1,41 +1,41 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
-\r
-<html>\r
-<head>\r
-       <title>Untitled</title>\r
-</head>\r
-\r
-<body>\r
-<?php\r
-/*\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 8.\r
- */\r
-#\r
-# test connecting to 2 MySQL databases simultaneously and ensure that each connection\r
-# is independant.\r
-#\r
-include("../tohtml.inc.php");\r
-include("../adodb.inc.php");   \r
-\r
-ADOLoadCode('mysql');\r
-\r
-$c1 = ADONewConnection('oci8');\r
-\r
-if (!$c1->PConnect('','scott','tiger')) \r
-       die("Cannot connect to server");\r
-$c1->debug=1;\r
-$rs = $c1->Execute('select rownum, p1.firstname,p2.lastname,p2.firstname,p1.lastname from adoxyz p1, adoxyz p2');\r
-print "Records=".$rs->RecordCount()."<br><pre>";\r
-//$rs->_array = false;\r
-//$rs->connection = false;\r
-//print_r($rs);\r
-rs2html($rs);\r
-?>\r
-\r
-\r
-</body>\r
-</html>\r
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+       <title>Untitled</title>
+</head>
+
+<body>
+<?php
+/*
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+ */
+#
+# test connecting to 2 MySQL databases simultaneously and ensure that each connection
+# is independant.
+#
+include("../tohtml.inc.php");
+include("../adodb.inc.php");   
+
+ADOLoadCode('mysql');
+
+$c1 = ADONewConnection('oci8');
+
+if (!$c1->PConnect('','scott','tiger')) 
+       die("Cannot connect to server");
+$c1->debug=1;
+$rs = $c1->Execute('select rownum, p1.firstname,p2.lastname,p2.firstname,p1.lastname from adoxyz p1, adoxyz p2');
+print "Records=".$rs->RecordCount()."<br><pre>";
+//$rs->_array = false;
+//$rs->connection = false;
+//print_r($rs);
+rs2html($rs);
+?>
+
+
+</body>
+</html>
index 36754ed8558fe31a64eb22214a44cdad8547038e..207dda27732d97e1a10f5f85cb54ebdc7a4d728c 100644 (file)
@@ -1,44 +1,44 @@
-<?php\r
-/*\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-  Set tabs to 8.\r
- */\r
-\r
-\r
-error_reporting(E_ALL);\r
-\r
-$path = dirname(__FILE__);\r
-\r
-include("$path/../adodb-exceptions.inc.php");\r
-include("$path/../adodb.inc.php");     \r
-\r
-try {\r
-$db = NewADOConnection("oci8");\r
-$db->Connect('','scott','natsoft');\r
-$db->debug=1;\r
-\r
-$cnt = $db->GetOne("select count(*) from adoxyz");\r
-$rs = $db->Execute("select * from adoxyz order by id");\r
-\r
-$i = 0;\r
-foreach($rs as $k => $v) {\r
-       $i += 1;\r
-       echo $k; adodb_pr($v);\r
-       flush();\r
-}\r
-\r
-if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n");\r
-\r
-\r
-\r
-$rs = $db->Execute("select bad from badder");\r
-\r
-} catch (exception $e) {\r
-       adodb_pr($e);\r
-       $e = adodb_backtrace($e->trace);\r
-}\r
-\r
+<?php
+/*
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+  Set tabs to 8.
+ */
+
+
+error_reporting(E_ALL);
+
+$path = dirname(__FILE__);
+
+include("$path/../adodb-exceptions.inc.php");
+include("$path/../adodb.inc.php");     
+
+try {
+$db = NewADOConnection("oci8");
+$db->Connect('','scott','natsoft');
+$db->debug=1;
+
+$cnt = $db->GetOne("select count(*) from adoxyz");
+$rs = $db->Execute("select * from adoxyz order by id");
+
+$i = 0;
+foreach($rs as $k => $v) {
+       $i += 1;
+       echo $k; adodb_pr($v);
+       flush();
+}
+
+if ($i != $cnt) die("actual cnt is $i, cnt should be $cnt\n");
+
+
+
+$rs = $db->Execute("select bad from badder");
+
+} catch (exception $e) {
+       adodb_pr($e);
+       $e = adodb_backtrace($e->trace);
+}
+
 ?>
\ No newline at end of file
index 9a261b13a108dfb31232e42189d0bc6f86e669af..64fb8b01a07867ca4dcf1ff7f500fedab79fc2d1 100644 (file)
@@ -1,7 +1,7 @@
 <?php\r
 \r
 /** \r
- * @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+ * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
  * Released under both BSD license and Lesser GPL library license. \r
  * Whenever there is any discrepancy between the two licenses, \r
  * the BSD license will take precedence. \r
@@ -70,7 +70,7 @@ $record = array(); // Initialize an array to hold the record data to update
 $record["firstName"] = "Caroline".rand();\r
 $record["lasTname"] = "Smithy Jones"; // Update Caroline's lastname from Miranda to Smith\r
 $record["creAted"] = '2002-12-'.(rand()%30+1);\r
-\r
+$record['num'] = 3921;\r
 // Pass the single record recordset and the array containing the data to update\r
 // into the GetUpdateSQL function. The function will process the data and return\r
 // a fully formatted update sql statement.\r
@@ -80,7 +80,9 @@ $updateSQL = $conn->GetUpdateSQL($rs, $record);
 $conn->Execute($updateSQL); // Update the record in the database\r
 print "<p>Rows Affected=".$conn->Affected_Rows()."</p>";\r
 \r
-rs2html($conn->Execute("select * from adoxyz where lastname like 'Smith%'"));\r
+$rs = $conn->Execute("select * from adoxyz where lastname like 'Smith%'");\r
+adodb_pr($rs);\r
+rs2html($rs);\r
 }\r
 \r
 \r
index 5308f2b1386493fed5da50c41b770698c49bbc3d..ba02aeed085a35700bb55f7cbd12f17951b6efa7 100644 (file)
@@ -1,47 +1,47 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-  Set tabs to 4 for best viewing.\r
-       \r
-  Latest version is available at http://php.weblogs.com/\r
-*/\r
-\r
-\r
-// Select an empty record from the database \r
-\r
-include('../adodb.inc.php');\r
-include('../tohtml.inc.php');\r
-\r
-include('../adodb-errorpear.inc.php');\r
-\r
-if (0) {\r
-       $conn = &ADONewConnection('mysql');\r
-       $conn->debug=1;\r
-       $conn->PConnect("localhost","root","","xphplens");\r
-       print $conn->databaseType.':'.$conn->GenID().'<br>';\r
-}\r
-\r
-if (0) {\r
-       $conn = &ADONewConnection("oci8");  // create a connection\r
-       $conn->debug=1;\r
-       $conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); // connect to MySQL, testdb\r
-       print $conn->databaseType.':'.$conn->GenID();\r
-}\r
-\r
-if (0) {\r
-       $conn = &ADONewConnection("ibase");  // create a connection\r
-       $conn->debug=1;\r
-       $conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); // connect to MySQL, testdb\r
-       print $conn->databaseType.':'.$conn->GenID().'<br>';\r
-}\r
-\r
-if (0) {\r
-       $conn = &ADONewConnection('postgres');\r
-       $conn->debug=1;\r
-       @$conn->PConnect("susetikus","tester","test","test");\r
-       print $conn->databaseType.':'.$conn->GenID().'<br>';\r
-}\r
-?>\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+       
+  Latest version is available at http://php.weblogs.com/
+*/
+
+
+// Select an empty record from the database 
+
+include('../adodb.inc.php');
+include('../tohtml.inc.php');
+
+include('../adodb-errorpear.inc.php');
+
+if (0) {
+       $conn = &ADONewConnection('mysql');
+       $conn->debug=1;
+       $conn->PConnect("localhost","root","","xphplens");
+       print $conn->databaseType.':'.$conn->GenID().'<br>';
+}
+
+if (0) {
+       $conn = &ADONewConnection("oci8");  // create a connection
+       $conn->debug=1;
+       $conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); // connect to MySQL, testdb
+       print $conn->databaseType.':'.$conn->GenID();
+}
+
+if (0) {
+       $conn = &ADONewConnection("ibase");  // create a connection
+       $conn->debug=1;
+       $conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); // connect to MySQL, testdb
+       print $conn->databaseType.':'.$conn->GenID().'<br>';
+}
+
+if (0) {
+       $conn = &ADONewConnection('postgres');
+       $conn->debug=1;
+       @$conn->PConnect("susetikus","tester","test","test");
+       print $conn->databaseType.':'.$conn->GenID().'<br>';
+}
+?>
index c926a2a32ed371e1c5849ac88fdfe1ce2b3a0885..b4516d5e854350260186d00fb874b0f2d42390f0 100644 (file)
@@ -1,29 +1,29 @@
-<html>\r
-<body>\r
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-  Set tabs to 4 for best viewing.\r
-       \r
-  Latest version is available at http://php.weblogs.com/\r
-*/\r
-\r
-$ADODB_CACHE_DIR = dirname(tempnam('/tmp',''));\r
-include("../adodb.inc.php");\r
-\r
-if (isset($access)) {\r
-       $db=ADONewConnection('access');\r
-       $db->PConnect('nwind');\r
-} else {\r
-       $db = ADONewConnection('mysql');\r
-       $db->PConnect('mangrove','root','','xphplens');\r
-}\r
-if (isset($cache)) $rs = $db->CacheExecute(120,'select * from products');\r
-else $rs = $db->Execute('select * from products');\r
-\r
-$arr = $rs->GetArray();\r
-print sizeof($arr);\r
+<html>
+<body>
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+       
+  Latest version is available at http://php.weblogs.com/
+*/
+
+$ADODB_CACHE_DIR = dirname(tempnam('/tmp',''));
+include("../adodb.inc.php");
+
+if (isset($access)) {
+       $db=ADONewConnection('access');
+       $db->PConnect('nwind');
+} else {
+       $db = ADONewConnection('mysql');
+       $db->PConnect('mangrove','root','','xphplens');
+}
+if (isset($cache)) $rs = $db->CacheExecute(120,'select * from products');
+else $rs = $db->Execute('select * from products');
+
+$arr = $rs->GetArray();
+print sizeof($arr);
 ?>
\ No newline at end of file
index 7357e87de8ec00b7f667c4e58ab7ab61b9c39c62..871ec8d2729df2714b49439ccfbb57991c3dd6fb 100644 (file)
-<?php\r
-  \r
-/*\r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence.\r
-*/ \r
\r
- /* this file is used by the ADODB test program: test.php */\r
- ?>\r
-\r
-<table><tr valign=top><td>\r
-<form method=get>\r
-<input type=checkbox name="testaccess" value=1 <?php echo !empty($testaccess) ? 'checked' : '' ?>> <b>Access</b><br>\r
-<input type=checkbox name="testibase" value=1 <?php echo !empty($testibase) ? 'checked' : '' ?>> <b>Interbase</b><br>\r
-<input type=checkbox name="testmssql" value=1 <?php echo !empty($testmssql) ? 'checked' : '' ?>> <b>MSSQL</b><br>\r
- <input type=checkbox name="testmysql" value=1 <?php echo !empty($testmysql) ? 'checked' : '' ?>> <b>MySQL</b><br>\r
-<input type=checkbox name="testmysqlodbc" value=1 <?php echo !empty($testmysqlodbc) ? 'checked' : '' ?>> <b>MySQL ODBC</b><br>\r
-<td><input type=checkbox name="testsqlite" value=1 <?php echo !empty($testsqlite) ? 'checked' : '' ?>> <b>SQLite</b><br>\r
-<input type=checkbox name="testproxy" value=1 <?php echo !empty($testproxy) ? 'checked' : '' ?>> <b>MySQL Proxy</b><br>\r
-<input type=checkbox name="testoracle" value=1 <?php echo !empty($testoracle) ? 'checked' : '' ?>> <b>Oracle (oci8)</b> <br>\r
-<input type=checkbox name="testpostgres" value=1 <?php echo !empty($testpostgres) ? 'checked' : '' ?>> <b>PostgreSQL</b><br>\r
-<input type=checkbox name="testpgodbc" value=1 <?php echo !empty($testpgodbc) ? 'checked' : '' ?>> <b>PostgreSQL ODBC</b><br>\r
-<td><input type=checkbox name="testdb2" value=1 <?php echo !empty($testdb2) ? 'checked' : '' ?>> DB2<br>\r
-<input type=checkbox name="testvfp" value=1 <?php echo !empty($testvfp) ? 'checked' : '' ?>> VFP<br>\r
-<input type=checkbox name="testado" value=1 <?php echo !empty($testado) ? 'checked' : '' ?>> ADO (for mssql and access)<br>\r
-<input type=checkbox name="nocountrecs" value=1 <?php echo !empty($nocountrecs) ? 'checked' : '' ?>> $ADODB_COUNTRECS=false<br>\r
-<input type=checkbox name="nolog" value=1 <?php echo !empty($nolog) ? 'checked' : '' ?>> No SQL Logging<br>\r
-<td><input type=submit>\r
-</form>\r
-</table>\r
-<?php\r
-\r
-if ($ADODB_FETCH_MODE != ADODB_FETCH_DEFAULT) print "<h3>FETCH MODE IS NOT ADODB_FETCH_DEFAULT</h3>";\r
-\r
-if (isset($nocountrecs)) $ADODB_COUNTRECS = false;\r
-\r
-// cannot test databases below, but we include them anyway to check\r
-// if they parse ok...\r
-\r
-if (!strpos(PHP_VERSION,'5') === 0) {\r
-       ADOLoadCode("sybase");\r
-       ADOLoadCode("postgres");\r
-       ADOLoadCode("postgres7");\r
-       ADOLoadCode("firebird");\r
-       ADOLoadCode("borland_ibase");\r
-       ADOLoadCode("informix");\r
-       ADOLoadCode("sqlanywhere");\r
-}\r
-\r
-\r
-flush();\r
-if (!empty($testpostgres)) {\r
-       //ADOLoadCode("postgres");\r
-\r
-       $db = &ADONewConnection('postgres');\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       if (@$db->Connect("localhost","tester","test","test")) {\r
-               testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname varchar,created date)");\r
-       }else\r
-               print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();\r
-}\r
-\r
-if (!empty($testpgodbc)) { \r
-       \r
-       $db = &ADONewConnection('odbc');\r
-       $db->hasTransactions = false;\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       \r
-       if ($db->PConnect('Postgresql')) {\r
-               $db->hasTransactions = true;\r
-               testdb($db,\r
-               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");\r
-       } else print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();\r
-}\r
-\r
-if (!empty($testibase)) {\r
-       \r
-       $db = &ADONewConnection('firebird');\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       if (@$db->PConnect("localhost:d:\\firebird\\10\\examples\\employee.gdb", "sysdba", "masterkey", ""))\r
-               testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname char(24),price numeric(12,2),created date)");\r
-        else print "ERROR: Interbase test requires a database called employee.gdb".'<BR>'.$db->ErrorMsg();\r
-       \r
-}\r
-\r
-\r
-if (!empty($testsqlite)) {\r
-       $db = &ADONewConnection('sqlite');\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       \r
-       if (@$db->PConnect("d:\\inetpub\\adodb\\sqlite.db", "", "", ""))\r
-               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
-       else print "ERROR: SQLite";\r
-       \r
-}\r
-\r
-// REQUIRES ODBC DSN CALLED nwind\r
-if (!empty($testaccess)) {\r
-       $db = &ADONewConnection('access');\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       \r
-       $dsn = "nwind";\r
-       $driver = "Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\inetpub\adodb\northwind.mdb;Uid=Admin;Pwd=;";\r
-       if (@$db->PConnect($dsn, "", "", ""))\r
-               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
-       else print "ERROR: Access test requires a Windows ODBC DSN=nwind, Access driver";\r
-       \r
-}\r
-\r
-if (!empty($testaccess) && !empty($testado)) { // ADO ACCESS\r
-\r
-       $db = &ADONewConnection("ado_access");\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       \r
-       $access = 'd:\inetpub\wwwroot\php\NWIND.MDB';\r
-       $myDSN =  'PROVIDER=Microsoft.Jet.OLEDB.4.0;'\r
-               . 'DATA SOURCE=' . $access . ';';\r
-               //. 'USER ID=;PASSWORD=;';\r
-       \r
-       if (@$db->PConnect($myDSN, "", "", "")) {\r
-               print "ADO version=".$db->_connectionID->version."<br>";\r
-               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
-       } else print "ERROR: Access test requires a Access database $access".'<BR>'.$db->ErrorMsg();\r
-       \r
-}\r
-\r
-if (!empty($testvfp)) { // ODBC\r
-       $db = &ADONewConnection('vfp');\r
-       print "<h1>Connecting $db->databaseType...</h1>";flush();\r
-\r
-       if ( $db->PConnect("vfp-adoxyz")) {\r
-               testdb($db,"create table d:\\inetpub\\adodb\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)");\r
-        } else print "ERROR: Visual FoxPro test requires a Windows ODBC DSN=vfp-adoxyz, VFP driver";\r
-       \r
-}\r
-\r
-\r
-// REQUIRES MySQL server at localhost with database 'test'\r
-if (!empty($testmysql)) { // MYSQL\r
-\r
-       $db = &ADONewConnection('mysql');\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';\r
-       else $server = "mangrove";\r
-       if ($db->PConnect($server, "root", "", "northwind")) {\r
-               //$db->debug=1;$db->Execute('drop table ADOXYZ');\r
-               testdb($db,\r
-               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");\r
-       } else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();\r
-}\r
-\r
-// REQUIRES MySQL server at localhost with database 'test'\r
-if (!empty($testmysqlodbc)) { // MYSQL\r
-       \r
-       $db = &ADONewConnection('odbc');\r
-       $db->hasTransactions = false;\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';\r
-       else $server = "mangrove";\r
-       if ($db->PConnect('mysql', "root", ""))\r
-               testdb($db,\r
-               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");\r
-       else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();\r
-}\r
-\r
-if (!empty($testproxy)){\r
-       $db = &ADONewConnection('proxy');\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';\r
-\r
-       if ($db->PConnect('http://localhost/php/phplens/adodb/server.php'))\r
-               testdb($db,\r
-               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");\r
-       else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();\r
-\r
-}\r
-\r
-ADOLoadCode('oci805');\r
-ADOLoadCode("oci8po");\r
-if (!empty($testoracle)) { \r
-       \r
-       $db = ADONewConnection('oci8po');\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       if ($db->Connect('', "scott", "natsoft",''))\r
-       //if ($db->PConnect("", "scott", "tiger", "juris.ecosystem.natsoft.com.my"))\r
-               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");\r
-       else print "ERROR: Oracle test requires an Oracle server setup with scott/natsoft".'<BR>'.$db->ErrorMsg();\r
-\r
-}\r
-ADOLoadCode("oracle"); // no longer supported\r
-if (false && !empty($testoracle)) { \r
-       \r
-       $db = ADONewConnection();\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       if ($db->PConnect("", "scott", "tiger", "natsoft.domain"))\r
-               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");\r
-       else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();\r
-\r
-}\r
-\r
-ADOLoadCode("db2"); // no longer supported\r
-if (!empty($testdb2)) { \r
-       \r
-       $db = ADONewConnection();\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       if ($db->Connect("db2_sample", "root", "natsoft", ""))\r
-               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");\r
-       else print "ERROR: DB2 test requires an server setup with odbc data source db2_sample".'<BR>'.$db->ErrorMsg();\r
-\r
-}\r
-\r
-\r
-ADOLoadCode('odbc_mssql');\r
-if (!empty($testmssql)) { // MS SQL Server via ODBC\r
-       $db = ADONewConnection();\r
-       \r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       \r
-       $dsn = "mssql-northwind";\r
-       $dsn = "Driver={SQL Server};Server=localhost;Database=northwind;";\r
-       \r
-       if (@$db->PConnect($dsn, "adodb", "natsoft", ""))  {\r
-               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");\r
-       }\r
-       else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN setup";\r
-\r
-}\r
-\r
-ADOLoadCode("ado_mssql");\r
-\r
-if (!empty($testmssql) && !empty($testado) ) { // ADO ACCESS MSSQL -- thru ODBC -- DSN-less\r
-       \r
-       $db = &ADONewConnection("ado_mssql");\r
-       //$db->debug=1;\r
-       print "<h1>Connecting DSN-less $db->databaseType...</h1>";\r
-       \r
-       $myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"\r
-               . "SERVER=tigress;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No"  ;\r
-\r
-               \r
-       if (@$db->PConnect($myDSN, "", "", ""))\r
-               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");\r
-       else print "ERROR: MSSQL test 2 requires MS SQL 7";\r
-       \r
-}\r
-\r
-\r
-ADOLoadCode("mssqlpo");\r
-if (!empty($testmssql)) { // MS SQL Server -- the extension is buggy -- probably better to use ODBC\r
-       $db = ADONewConnection("mssqlpo");\r
-       //$db->debug=1;\r
-       print "<h1>Connecting $db->databaseType...</h1>";\r
-       \r
-       $ok = $db->PConnect('tigress','adodb','natsoft','northwind');\r
-       //$rs = $db->Execute("exec sp_ddate");\r
-       //print_r($rs->fields);\r
-       //die();\r
-\r
-       if ($ok or @$db->PConnect("mangrove", "sa", "natsoft", "ai")) {\r
-               AutoDetect_MSSQL_Date_Order($db);\r
-       //      $db->Execute('drop table adoxyz');\r
-               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");\r
-       } else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='192.168.0.1', userid='sa', password='natsoft', database='ai'".'<BR>'.$db->ErrorMsg();\r
-       \r
-}\r
-\r
-if (!empty($testmssql) && !empty($testado)) { // ADO ACCESS MSSQL with OLEDB provider\r
-\r
-       $db = &ADONewConnection("ado_mssql");\r
-       print "<h1>Connecting DSN-less OLEDB Provider $db->databaseType...</h1>";\r
-       //$db->debug=1;\r
-       $myDSN="SERVER=tigress;DATABASE=northwind;Trusted_Connection=yes";\r
-       //$myDSN='SERVER=(local)\NetSDK;DATABASE=northwind;';\r
-       if ($db->PConnect($myDSN, "adodb", "natsoft", 'SQLOLEDB'))\r
-               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");\r
-       else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'";\r
-\r
-}\r
-\r
-\r
-print "<h3>Tests Completed</h3>";\r
-\r
-?>\r
+<?php
+  
+/*
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence.
+*/ 
+ /* this file is used by the ADODB test program: test.php */
+ ?>
+
+<table><tr valign=top><td>
+<form method=get>
+<input type=checkbox name="testaccess" value=1 <?php echo !empty($testaccess) ? 'checked' : '' ?>> <b>Access</b><br>
+<input type=checkbox name="testibase" value=1 <?php echo !empty($testibase) ? 'checked' : '' ?>> <b>Interbase</b><br>
+<input type=checkbox name="testmssql" value=1 <?php echo !empty($testmssql) ? 'checked' : '' ?>> <b>MSSQL</b><br>
+ <input type=checkbox name="testmysql" value=1 <?php echo !empty($testmysql) ? 'checked' : '' ?>> <b>MySQL</b><br>
+<input type=checkbox name="testmysqlodbc" value=1 <?php echo !empty($testmysqlodbc) ? 'checked' : '' ?>> <b>MySQL ODBC</b><br>
+<td><input type=checkbox name="testsqlite" value=1 <?php echo !empty($testsqlite) ? 'checked' : '' ?>> <b>SQLite</b><br>
+<input type=checkbox name="testproxy" value=1 <?php echo !empty($testproxy) ? 'checked' : '' ?>> <b>MySQL Proxy</b><br>
+<input type=checkbox name="testoracle" value=1 <?php echo !empty($testoracle) ? 'checked' : '' ?>> <b>Oracle (oci8)</b> <br>
+<input type=checkbox name="testpostgres" value=1 <?php echo !empty($testpostgres) ? 'checked' : '' ?>> <b>PostgreSQL</b><br>
+<input type=checkbox name="testpgodbc" value=1 <?php echo !empty($testpgodbc) ? 'checked' : '' ?>> <b>PostgreSQL ODBC</b><br>
+<td><input type=checkbox name="testdb2" value=1 <?php echo !empty($testdb2) ? 'checked' : '' ?>> DB2<br>
+<input type=checkbox name="testvfp" value=1 <?php echo !empty($testvfp) ? 'checked' : '' ?>> VFP<br>
+<input type=checkbox name="testado" value=1 <?php echo !empty($testado) ? 'checked' : '' ?>> ADO (for mssql and access)<br>
+<input type=checkbox name="nocountrecs" value=1 <?php echo !empty($nocountrecs) ? 'checked' : '' ?>> $ADODB_COUNTRECS=false<br>
+<input type=checkbox name="nolog" value=1 <?php echo !empty($nolog) ? 'checked' : '' ?>> No SQL Logging<br>
+<td><input type=submit>
+</form>
+</table>
+<?php
+
+if ($ADODB_FETCH_MODE != ADODB_FETCH_DEFAULT) print "<h3>FETCH MODE IS NOT ADODB_FETCH_DEFAULT</h3>";
+
+if (isset($nocountrecs)) $ADODB_COUNTRECS = false;
+
+// cannot test databases below, but we include them anyway to check
+// if they parse ok...
+
+if (!strpos(PHP_VERSION,'5') === 0) {
+       ADOLoadCode("sybase");
+       ADOLoadCode("postgres");
+       ADOLoadCode("postgres7");
+       ADOLoadCode("firebird");
+       ADOLoadCode("borland_ibase");
+       ADOLoadCode("informix");
+       ADOLoadCode("sqlanywhere");
+}
+
+
+flush();
+if (!empty($testpostgres)) {
+       //ADOLoadCode("postgres");
+
+       $db = &ADONewConnection('postgres');
+       print "<h1>Connecting $db->databaseType...</h1>";
+       if (@$db->Connect("localhost","tester","test","test")) {
+               testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname varchar,created date)");
+       }else
+               print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();
+}
+
+if (!empty($testpgodbc)) { 
+       
+       $db = &ADONewConnection('odbc');
+       $db->hasTransactions = false;
+       print "<h1>Connecting $db->databaseType...</h1>";
+       
+       if ($db->PConnect('Postgresql')) {
+               $db->hasTransactions = true;
+               testdb($db,
+               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
+       } else print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();
+}
+
+if (!empty($testibase)) {
+       
+       $db = &ADONewConnection('firebird');
+       print "<h1>Connecting $db->databaseType...</h1>";
+       if (@$db->PConnect("localhost:d:\\firebird\\10\\examples\\employee.gdb", "sysdba", "masterkey", ""))
+               testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname char(24),price numeric(12,2),created date)");
+        else print "ERROR: Interbase test requires a database called employee.gdb".'<BR>'.$db->ErrorMsg();
+       
+}
+
+
+if (!empty($testsqlite)) {
+       $db = &ADONewConnection('sqlite');
+       print "<h1>Connecting $db->databaseType...</h1>";
+       
+       if (@$db->PConnect("d:\\inetpub\\adodb\\sqlite.db", "", "", ""))
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
+       else print "ERROR: SQLite";
+       
+}
+
+// REQUIRES ODBC DSN CALLED nwind
+if (!empty($testaccess)) {
+       $db = &ADONewConnection('access');
+       print "<h1>Connecting $db->databaseType...</h1>";
+       
+       $dsn = "nwind";
+       $driver = "Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\inetpub\adodb\northwind.mdb;Uid=Admin;Pwd=;";
+       if (@$db->PConnect($dsn, "", "", ""))
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
+       else print "ERROR: Access test requires a Windows ODBC DSN=nwind, Access driver";
+       
+}
+
+if (!empty($testaccess) && !empty($testado)) { // ADO ACCESS
+
+       $db = &ADONewConnection("ado_access");
+       print "<h1>Connecting $db->databaseType...</h1>";
+       
+       $access = 'd:\inetpub\wwwroot\php\NWIND.MDB';
+       $myDSN =  'PROVIDER=Microsoft.Jet.OLEDB.4.0;'
+               . 'DATA SOURCE=' . $access . ';';
+               //. 'USER ID=;PASSWORD=;';
+       
+       if (@$db->PConnect($myDSN, "", "", "")) {
+               print "ADO version=".$db->_connectionID->version."<br>";
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
+       } else print "ERROR: Access test requires a Access database $access".'<BR>'.$db->ErrorMsg();
+       
+}
+
+if (!empty($testvfp)) { // ODBC
+       $db = &ADONewConnection('vfp');
+       print "<h1>Connecting $db->databaseType...</h1>";flush();
+
+       if ( $db->PConnect("vfp-adoxyz")) {
+               testdb($db,"create table d:\\inetpub\\adodb\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)");
+        } else print "ERROR: Visual FoxPro test requires a Windows ODBC DSN=vfp-adoxyz, VFP driver";
+       
+}
+
+
+// REQUIRES MySQL server at localhost with database 'test'
+if (!empty($testmysql)) { // MYSQL
+
+       $db = &ADONewConnection('mysql');
+       print "<h1>Connecting $db->databaseType...</h1>";
+       if (PHP_VERSION >= 5 || $HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
+       else $server = "mangrove";
+       if ($db->PConnect($server, "root", "", "northwind")) {
+               //$db->debug=1;$db->Execute('drop table ADOXYZ');
+               testdb($db,
+               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");
+       } else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
+}
+
+// REQUIRES MySQL server at localhost with database 'test'
+if (!empty($testmysqlodbc)) { // MYSQL
+       
+       $db = &ADONewConnection('odbc');
+       $db->hasTransactions = false;
+       print "<h1>Connecting $db->databaseType...</h1>";
+       if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
+       else $server = "mangrove";
+       if ($db->PConnect('mysql', "root", ""))
+               testdb($db,
+               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
+       else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
+}
+
+if (!empty($testproxy)){
+       $db = &ADONewConnection('proxy');
+       print "<h1>Connecting $db->databaseType...</h1>";
+       if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
+
+       if ($db->PConnect('http://localhost/php/phplens/adodb/server.php'))
+               testdb($db,
+               "create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
+       else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
+
+}
+
+ADOLoadCode('oci805');
+ADOLoadCode("oci8po");
+if (!empty($testoracle)) { 
+       
+       $db = ADONewConnection('oci8po');
+       print "<h1>Connecting $db->databaseType...</h1>";
+       if ($db->Connect('', "scott", "natsoft",''))
+       //if ($db->PConnect("", "scott", "tiger", "juris.ecosystem.natsoft.com.my"))
+               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
+       else print "ERROR: Oracle test requires an Oracle server setup with scott/natsoft".'<BR>'.$db->ErrorMsg();
+
+}
+ADOLoadCode("oracle"); // no longer supported
+if (false && !empty($testoracle)) { 
+       
+       $db = ADONewConnection();
+       print "<h1>Connecting $db->databaseType...</h1>";
+       if ($db->PConnect("", "scott", "tiger", "natsoft.domain"))
+               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
+       else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();
+
+}
+
+ADOLoadCode("db2"); // no longer supported
+if (!empty($testdb2)) { 
+       
+       $db = ADONewConnection();
+       print "<h1>Connecting $db->databaseType...</h1>";
+       if ($db->Connect("db2_sample", "root", "natsoft", ""))
+               testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
+       else print "ERROR: DB2 test requires an server setup with odbc data source db2_sample".'<BR>'.$db->ErrorMsg();
+
+}
+
+
+ADOLoadCode('odbc_mssql');
+if (!empty($testmssql)) { // MS SQL Server via ODBC
+       $db = ADONewConnection();
+       
+       print "<h1>Connecting $db->databaseType...</h1>";
+       
+       $dsn = "mssql-northwind";
+       $dsn = "Driver={SQL Server};Server=localhost;Database=northwind;";
+       
+       if (@$db->PConnect($dsn, "adodb", "natsoft", ""))  {
+               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
+       }
+       else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN setup";
+
+}
+
+ADOLoadCode("ado_mssql");
+
+if (!empty($testmssql) && !empty($testado) ) { // ADO ACCESS MSSQL -- thru ODBC -- DSN-less
+       
+       $db = &ADONewConnection("ado_mssql");
+       //$db->debug=1;
+       print "<h1>Connecting DSN-less $db->databaseType...</h1>";
+       
+       $myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"
+               . "SERVER=tigress;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No"  ;
+
+               
+       if (@$db->PConnect($myDSN, "", "", ""))
+               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
+       else print "ERROR: MSSQL test 2 requires MS SQL 7";
+       
+}
+
+
+ADOLoadCode("mssqlpo");
+if (!empty($testmssql)) { // MS SQL Server -- the extension is buggy -- probably better to use ODBC
+       $db = ADONewConnection("mssqlpo");
+       //$db->debug=1;
+       print "<h1>Connecting $db->databaseType...</h1>";
+       
+       $ok = $db->PConnect('tigress','adodb','natsoft','northwind');
+       //$rs = $db->Execute("exec sp_ddate");
+       //print_r($rs->fields);
+       //die();
+
+       if ($ok or @$db->PConnect("mangrove", "sa", "natsoft", "ai")) {
+               AutoDetect_MSSQL_Date_Order($db);
+       //      $db->Execute('drop table adoxyz');
+               testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
+       } else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='192.168.0.1', userid='sa', password='natsoft', database='ai'".'<BR>'.$db->ErrorMsg();
+       
+}
+
+if (!empty($testmssql) && !empty($testado)) { // ADO ACCESS MSSQL with OLEDB provider
+
+       $db = &ADONewConnection("ado_mssql");
+       print "<h1>Connecting DSN-less OLEDB Provider $db->databaseType...</h1>";
+       //$db->debug=1;
+       $myDSN="SERVER=tigress;DATABASE=northwind;Trusted_Connection=yes";
+       //$myDSN='SERVER=(local)\NetSDK;DATABASE=northwind;';
+       if ($db->PConnect($myDSN, "adodb", "natsoft", 'SQLOLEDB'))
+               testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
+       else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'";
+
+}
+
+
+print "<h3>Tests Completed</h3>";
+
+?>
index 05554dd29d77cb4c5572bdc449fb75065af5e820..479f7124b53e15d2b4ec4770b019e1b42db5ed32 100644 (file)
@@ -1,36 +1,36 @@
-<?php\r
-/*\r
-       V4.11 27 Jan 2004 \r
-       \r
-       Run multiple copies of this php script at the same time\r
-       to test unique generation of id's in multiuser mode\r
-*/\r
-include_once('../adodb.inc.php');\r
-$testaccess = true;\r
-include_once('testdatabases.inc.php');\r
-\r
-function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")\r
-{\r
-       $table = 'adodbseq';\r
-       \r
-       $db->Execute("drop table $table");\r
-       //$db->debug=true;\r
-       \r
-       $ctr = 5000;\r
-       $lastnum = 0;\r
-       \r
-       while (--$ctr >= 0) {\r
-               $num = $db->GenID($table);\r
-               if ($num === false) {   \r
-                       print "GenID returned false";\r
-                       break;\r
-               }\r
-               if ($lastnum + 1 == $num) print " $num ";\r
-               else {\r
-                       print " <font color=red>$num</font> ";\r
-                       flush();\r
-               }\r
-               $lastnum = $num;\r
-       }\r
-}\r
+<?php
+/*
+       V4.20 22 Feb 2004 
+       
+       Run multiple copies of this php script at the same time
+       to test unique generation of id's in multiuser mode
+*/
+include_once('../adodb.inc.php');
+$testaccess = true;
+include_once('testdatabases.inc.php');
+
+function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
+{
+       $table = 'adodbseq';
+       
+       $db->Execute("drop table $table");
+       //$db->debug=true;
+       
+       $ctr = 5000;
+       $lastnum = 0;
+       
+       while (--$ctr >= 0) {
+               $num = $db->GenID($table);
+               if ($num === false) {   
+                       print "GenID returned false";
+                       break;
+               }
+               if ($lastnum + 1 == $num) print " $num ";
+               else {
+                       print " <font color=red>$num</font> ";
+                       flush();
+               }
+               $lastnum = $num;
+       }
+}
 ?>
\ No newline at end of file
index b54b850c32255fd1d551bcb6ba5e0542824ea9fd..6db4123c19443138269263f36c1eb64b0de74324 100644 (file)
@@ -1,62 +1,76 @@
-<?php\r
-\r
-/** \r
- * @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license. \r
- * Whenever there is any discrepancy between the two licenses, \r
- * the BSD license will take precedence. \r
- *\r
- * Set tabs to 4 for best viewing.\r
- * \r
- * Latest version is available at http://php.weblogs.com\r
- *\r
- * Test GetUpdateSQL and GetInsertSQL.\r
- */\r
\r
-error_reporting(E_ALL);\r
-\r
-\r
-include('../adodb.inc.php');\r
-include('../tohtml.inc.php');\r
-\r
-//==========================\r
-// This code tests an insert\r
-\r
-\r
-\r
-$conn = &ADONewConnection("mssql");  // create a connection\r
-$conn->Connect('localhost','sa','natsoft','northwind') or die('Fail');\r
-\r
-$p = $conn->Prepare('insert into products (productname,unitprice,dcreated) values (?,?,?)');\r
-echo "<pre>";\r
-print_r($p);\r
-\r
-$conn->debug=1;\r
-$conn->Execute($p,array('John'.rand(),33.3,$conn->DBDate(time())));\r
-\r
-$p = $conn->Prepare('select * from products where productname like ?');\r
-$arr = $conn->getarray($p,array('V%'));\r
-print_r($arr);\r
-die();\r
-\r
-//$conn = &ADONewConnection("mssql");\r
-//$conn->Connect('mangrove','sa','natsoft','ai');\r
-\r
-//$conn->Connect('mangrove','sa','natsoft','ai');\r
-$conn->debug=1;\r
-$conn->Execute('delete from blobtest');\r
-\r
-$conn->Execute('insert into blobtest (id) values(1)');\r
-$conn->UpdateBlobFile('blobtest','b1','../cute_icons_for_site/adodb.gif','id=1');\r
-$rs = $conn->Execute('select b1 from blobtest where id=1');\r
-\r
-$output = "c:\\temp\\test_out-".date('H-i-s').".gif"; \r
-print "Saving file <b>$output</b>, size=".strlen($rs->fields[0])."<p>";\r
-$fd = fopen($output, "wb"); \r
-fwrite($fd, $rs->fields[0]); \r
-fclose($fd); \r
-\r
-print " <a href=file://$output>View Image</a>";\r
-//$rs = $conn->Execute('SELECT id,SUBSTRING(b1, 1, 10) FROM blobtest');\r
-//rs2html($rs);\r
+<?php
+
+/** 
+ * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Set tabs to 4 for best viewing.
+ * 
+ * Latest version is available at http://php.weblogs.com
+ *
+ * Test GetUpdateSQL and GetInsertSQL.
+ */
+error_reporting(E_ALL);
+
+
+include('../adodb.inc.php');
+include('../tohtml.inc.php');
+
+//==========================
+// This code tests an insert
+
+
+
+$conn = &ADONewConnection("mssql");  // create a connection
+$conn->Connect('localhost','sa','natsoft','northwind') or die('Fail');
+
+$conn->debug =1;
+$query = 'select * from products';
+$conn->SetFetchMode(ADODB_FETCH_ASSOC);
+$rs = $conn->Execute($query);
+echo "<pre>";
+while( !$rs->EOF ) {
+       $output[] = $rs->fields;
+       var_dump($rs->fields);
+       $rs->MoveNext();
+       print "<p>";
+}
+die();
+
+
+$p = $conn->Prepare('insert into products (productname,unitprice,dcreated) values (?,?,?)');
+echo "<pre>";
+print_r($p);
+
+$conn->debug=1;
+$conn->Execute($p,array('John'.rand(),33.3,$conn->DBDate(time())));
+
+$p = $conn->Prepare('select * from products where productname like ?');
+$arr = $conn->getarray($p,array('V%'));
+print_r($arr);
+die();
+
+//$conn = &ADONewConnection("mssql");
+//$conn->Connect('mangrove','sa','natsoft','ai');
+
+//$conn->Connect('mangrove','sa','natsoft','ai');
+$conn->debug=1;
+$conn->Execute('delete from blobtest');
+
+$conn->Execute('insert into blobtest (id) values(1)');
+$conn->UpdateBlobFile('blobtest','b1','../cute_icons_for_site/adodb.gif','id=1');
+$rs = $conn->Execute('select b1 from blobtest where id=1');
+
+$output = "c:\\temp\\test_out-".date('H-i-s').".gif"; 
+print "Saving file <b>$output</b>, size=".strlen($rs->fields[0])."<p>";
+$fd = fopen($output, "wb"); 
+fwrite($fd, $rs->fields[0]); 
+fclose($fd); 
+
+print " <a href=file://$output>View Image</a>";
+//$rs = $conn->Execute('SELECT id,SUBSTRING(b1, 1, 10) FROM blobtest');
+//rs2html($rs);
 ?>
\ No newline at end of file
index bf743acb2fea0963f549c8314e85a6a8564db9a4..d748efca463af2d0b52fd462f3f9f93319c80d02 100644 (file)
@@ -1,70 +1,70 @@
-<html>\r
-<body>\r
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-  Set tabs to 4 for best viewing.\r
-       \r
-  Latest version is available at http://php.weblogs.com/\r
-*/\r
-error_reporting(63);\r
-include("../adodb.inc.php");\r
-include("../tohtml.inc.php");\r
-\r
-if (1) {\r
-       $db = ADONewConnection('oci8po');\r
-       \r
-       $db->PConnect('','scott','tiger');\r
-\r
-       if (!empty($testblob)) {\r
-               $varHoldingBlob = 'ABC DEF GEF John TEST';\r
-               $num = time()%10240;\r
-               // create table atable (id integer, ablob blob);\r
-               $db->Execute('insert into ATABLE (id,ablob) values('.$num.',empty_blob())');\r
-               $db->UpdateBlob('ATABLE', 'ablob', $varHoldingBlob, 'id='.$num, 'BLOB');\r
-               \r
-               $rs = &$db->Execute('select * from atable');\r
-               \r
-               if (!$rs) die("Empty RS");\r
-               if ($rs->EOF) die("EOF RS");\r
-               rs2html($rs);\r
-       }\r
-       $stmt = $db->Prepare('select * from adoxyz where id=?');\r
-       for ($i = 1; $i <= 10; $i++) {\r
-       $rs = &$db->Execute(\r
-               $stmt,\r
-               array($i));\r
-                       \r
-               if (!$rs) die("Empty RS");\r
-               if ($rs->EOF) die("EOF RS");\r
-               rs2html($rs);\r
-       }\r
-}\r
-if (1) {\r
-       $db = ADONewConnection('oci8');\r
-       $db->PConnect('','scott','tiger');\r
-       $db->debug = true;\r
-       $db->Execute("delete from emp where ename='John'");\r
-       print $db->Affected_Rows().'<BR>';\r
-       $stmt = &$db->Prepare('insert into emp (empno, ename) values (:empno, :ename)');\r
-       $rs = $db->Execute($stmt,array('empno'=>4321,'ename'=>'John'));\r
-       // prepare not quite ready for prime time\r
-       //$rs = $db->Execute($stmt,array('empno'=>3775,'ename'=>'John'));\r
-       if (!$rs) die("Empty RS");\r
-}\r
-\r
-if (0) {\r
-       $db = ADONewConnection('odbc_oracle');\r
-       if (!$db->PConnect('local_oracle','scott','tiger')) die('fail connect');\r
-       $db->debug = true;\r
-       $rs = &$db->Execute(\r
-               'select * from adoxyz where firstname=? and trim(lastname)=?',\r
-               array('first'=>'Caroline','last'=>'Miranda'));\r
-       if (!$rs) die("Empty RS");\r
-       if ($rs->EOF) die("EOF RS");\r
-       rs2html($rs);\r
-}\r
+<html>
+<body>
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+       
+  Latest version is available at http://php.weblogs.com/
+*/
+error_reporting(63);
+include("../adodb.inc.php");
+include("../tohtml.inc.php");
+
+if (1) {
+       $db = ADONewConnection('oci8po');
+       
+       $db->PConnect('','scott','tiger');
+
+       if (!empty($testblob)) {
+               $varHoldingBlob = 'ABC DEF GEF John TEST';
+               $num = time()%10240;
+               // create table atable (id integer, ablob blob);
+               $db->Execute('insert into ATABLE (id,ablob) values('.$num.',empty_blob())');
+               $db->UpdateBlob('ATABLE', 'ablob', $varHoldingBlob, 'id='.$num, 'BLOB');
+               
+               $rs = &$db->Execute('select * from atable');
+               
+               if (!$rs) die("Empty RS");
+               if ($rs->EOF) die("EOF RS");
+               rs2html($rs);
+       }
+       $stmt = $db->Prepare('select * from adoxyz where id=?');
+       for ($i = 1; $i <= 10; $i++) {
+       $rs = &$db->Execute(
+               $stmt,
+               array($i));
+                       
+               if (!$rs) die("Empty RS");
+               if ($rs->EOF) die("EOF RS");
+               rs2html($rs);
+       }
+}
+if (1) {
+       $db = ADONewConnection('oci8');
+       $db->PConnect('','scott','tiger');
+       $db->debug = true;
+       $db->Execute("delete from emp where ename='John'");
+       print $db->Affected_Rows().'<BR>';
+       $stmt = &$db->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
+       $rs = $db->Execute($stmt,array('empno'=>4321,'ename'=>'John'));
+       // prepare not quite ready for prime time
+       //$rs = $db->Execute($stmt,array('empno'=>3775,'ename'=>'John'));
+       if (!$rs) die("Empty RS");
+}
+
+if (0) {
+       $db = ADONewConnection('odbc_oracle');
+       if (!$db->PConnect('local_oracle','scott','tiger')) die('fail connect');
+       $db->debug = true;
+       $rs = &$db->Execute(
+               'select * from adoxyz where firstname=? and trim(lastname)=?',
+               array('first'=>'Caroline','last'=>'Miranda'));
+       if (!$rs) die("Empty RS");
+       if ($rs->EOF) die("EOF RS");
+       rs2html($rs);
+}
 ?>
\ No newline at end of file
index 19afa3628d36975224842bf822b131c7742d0783..a80fc9b9392d9382d2210f37856bb4145459905b 100644 (file)
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-  Set tabs to 4 for best viewing.\r
-       \r
-  Latest version is available at http://php.weblogs.com/\r
-*/\r
-\r
-/*\r
-       Test for Oracle Variable Cursors, which are treated as ADOdb recordsets.\r
-       \r
-       We have 2 examples. The first shows us using the Parameter statement. \r
-       The second shows us using the new ExecuteCursor($sql, $cursorName)\r
-       function.\r
-       \r
-------------------------------------------------------------------\r
--- TEST PACKAGE YOU NEED TO INSTALL ON ORACLE - run from sql*plus\r
-------------------------------------------------------------------\r
-\r
-CREATE or replace PACKAGE adodb AS\r
-TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;\r
-  -- list all tables that match tablenames in current schema\r
-PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);\r
-END adodb;\r
-/\r
-CREATE or replace PACKAGE BODY adodb AS\r
-PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS\r
-       BEGIN\r
-               OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;\r
-       END open_tab;\r
-END adodb;\r
-/\r
-\r
-------------------------------------------------------------------\r
--- END PACKAGE\r
-------------------------------------------------------------------\r
-\r
-*/\r
-\r
-include('../adodb.inc.php');\r
-include('../tohtml.inc.php');\r
-\r
-       error_reporting(E_ALL);\r
-       $db = ADONewConnection('oci8');\r
-       $db->PConnect('','scott','natsoft');\r
-       $db->debug = 99;\r
-\r
-\r
-/*\r
--- TEST PACKAGE\r
-CREATE OR REPLACE PACKAGE adodb AS\r
-TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;\r
-PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);\r
-PROCEDURE data_out(input IN varchar, output OUT varchar); \r
-END adodb;\r
-/\r
-\r
-CREATE OR REPLACE PACKAGE BODY adodb AS\r
-PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS\r
-       BEGIN\r
-               OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;\r
-       END open_tab;\r
-       \r
-PROCEDURE data_out(input IN varchar, output OUT varchar) IS\r
-       BEGIN\r
-               output := 'Cinta Hati '||input;\r
-       END;\r
-END adodb;\r
-/\r
-*/\r
-       $stmt = $db->Prepare("BEGIN adodb.open_tab(:RS,'A%'); END;");\r
-       $db->InParameter($stmt, $cur, 'RS', -1, OCI_B_CURSOR);\r
-       $rs = $db->Execute($stmt);\r
-\r
-       if ($rs && !$rs->EOF) {\r
-               print "Test 1 RowCount: ".$rs->RecordCount()."<p>";\r
-       } else {\r
-               print "<b>Error in using Cursor Variables 1</b><p>";\r
-       }\r
-       \r
-       \r
-       print "<h4>Testing Stored Procedures for oci8</h4>";\r
-       \r
-       $stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;",true);\r
-       $a1 = 'Malaysia';\r
-       //$a2 = ''; # a2 doesn't even need to be defined!\r
-       $db->InParameter($stmt,$a1,'a1');\r
-       $db->OutParameter($stmt,$a2,'a2');\r
-       $rs = $db->Execute($stmt);\r
-       if ($rs) {\r
-               if ($a2 !== 'Cinta Hati Malaysia') print "<b>Stored Procedure Error: a2 = $a2</b><p>";\r
-               else echo  "OK: a2=$a2<p>";\r
-       } else {\r
-               print "<b>Error in using Stored Procedure IN/Out Variables</b><p>";\r
-       }\r
-       \r
-       \r
-       $tname = 'A%';\r
-       \r
-       $stmt = $db->PrepareSP('select * from tab where tname like :tablename');\r
-       $db->Parameter($stmt,$tname,'tablename');\r
-       $rs = $db->Execute($stmt);\r
-       rs2html($rs);\r
-               \r
-               \r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+       
+  Latest version is available at http://php.weblogs.com/
+*/
+
+/*
+       Test for Oracle Variable Cursors, which are treated as ADOdb recordsets.
+       
+       We have 2 examples. The first shows us using the Parameter statement. 
+       The second shows us using the new ExecuteCursor($sql, $cursorName)
+       function.
+       
+------------------------------------------------------------------
+-- TEST PACKAGE YOU NEED TO INSTALL ON ORACLE - run from sql*plus
+------------------------------------------------------------------
+
+
+-- TEST PACKAGE
+CREATE OR REPLACE PACKAGE adodb AS
+TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);
+PROCEDURE data_out(input IN varchar, output OUT varchar); 
+
+procedure myproc (p1 in number, p2 out number);
+END adodb;
+/
+
+CREATE OR REPLACE PACKAGE BODY adodb AS
+PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS
+       BEGIN
+               OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;
+       END open_tab;
+       
+PROCEDURE data_out(input IN varchar, output OUT varchar) IS
+       BEGIN
+               output := 'Cinta Hati '||input;
+       END;
+       
+procedure myproc (p1 in number, p2 out number) as
+begin
+p2 := p1;
+end;
+END adodb;
+/
+
+------------------------------------------------------------------
+-- END PACKAGE
+------------------------------------------------------------------
+
+*/
+
+include('../adodb.inc.php');
+include('../tohtml.inc.php');
+
+       error_reporting(E_ALL);
+       $db = ADONewConnection('oci8');
+       $db->PConnect('','scott','natsoft');
+       $db->debug = 99;
+
+
+/*
+*/
+
+       define('MYNUM',5);
+       
+
+       
+       $stmt = $db->Prepare("BEGIN adodb.open_tab(:RS,'A%'); END;");
+       $db->InParameter($stmt, $cur, 'RS', -1, OCI_B_CURSOR);
+       $rs = $db->Execute($stmt);
+
+       if ($rs && !$rs->EOF) {
+               print "Test 1 RowCount: ".$rs->RecordCount()."<p>";
+       } else {
+               print "<b>Error in using Cursor Variables 1</b><p>";
+       }
+       
+       
+       print "<h4>Testing Stored Procedures for oci8</h4>";
+       
+       $stid = $db->PrepareSP('BEGIN adodb.myproc('.MYNUM.', :myov); END;');
+       $db->OutParameter($stid, $myov, 'myov');
+       $db->Execute($stid);
+       if ($myov != MYNUM) print "<p><b>Error with myproc</b></p>";
+       
+       
+       $stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;",true);
+       $a1 = 'Malaysia';
+       //$a2 = ''; # a2 doesn't even need to be defined!
+       $db->InParameter($stmt,$a1,'a1');
+       $db->OutParameter($stmt,$a2,'a2');
+       $rs = $db->Execute($stmt);
+       if ($rs) {
+               if ($a2 !== 'Cinta Hati Malaysia') print "<b>Stored Procedure Error: a2 = $a2</b><p>";
+               else echo  "OK: a2=$a2<p>";
+       } else {
+               print "<b>Error in using Stored Procedure IN/Out Variables</b><p>";
+       }
+       
+       
+       $tname = 'A%';
+       
+       $stmt = $db->PrepareSP('select * from tab where tname like :tablename');
+       $db->Parameter($stmt,$tname,'tablename');
+       $rs = $db->Execute($stmt);
+       rs2html($rs);
+               
+               
 ?>
\ No newline at end of file
index 3cf29aaf7d3a0078e063226745cb82b4c179ba55..89c9594649df5eaad99127596681db71dd9662ff 100644 (file)
@@ -1,83 +1,83 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-  Set tabs to 4 for best viewing.\r
-       \r
-  Latest version is available at http://php.weblogs.com/\r
-*/\r
-\r
-error_reporting(E_ALL);\r
-\r
-\r
-include_once('../adodb.inc.php');\r
-include_once('../adodb-pager.inc.php');\r
-\r
-$driver = 'oci8';\r
-$sql = 'select  ID, firstname as "First Name", lastname as "Last Name" from adoxyz  order  by  id';\r
-//$sql = 'select count(*),firstname from adoxyz group by firstname order by 2 ';\r
-$sql = 'select distinct firstname, lastname from adoxyz  order  by  firstname';\r
-\r
-if ($driver == 'postgres') {\r
-       $db = NewADOConnection('postgres');\r
-       $db->PConnect('localhost','tester','test','test');\r
-}\r
-\r
-if ($driver == 'access') {\r
-       $db = NewADOConnection('access');\r
-       $db->PConnect("nwind", "", "", "");\r
-}\r
-\r
-if ($driver == 'ibase') {\r
-       $db = NewADOConnection('ibase');\r
-       $db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", "");\r
-       $sql = 'select distinct firstname, lastname  from adoxyz  order  by  firstname';\r
-\r
-}\r
-if ($driver == 'mssql') {\r
-       $db = NewADOConnection('mssql');\r
-       $db->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');\r
-}\r
-if ($driver == 'oci8') {\r
-       $db = NewADOConnection('oci8');\r
-       $db->Connect('','scott','natsoft');\r
-}\r
-\r
-if ($driver == 'access') {\r
-       $db = NewADOConnection('access');\r
-       $db->Connect('nwind');\r
-}\r
-\r
-if (empty($driver) or $driver == 'mysql') {\r
-       $db = NewADOConnection('mysql');\r
-       $db->Connect('localhost','root','','xphplens');\r
-}\r
-\r
-//$db->pageExecuteCountRows = false;\r
-\r
-$db->debug = true;\r
-\r
-if (0) {\r
-$rs = &$db->Execute($sql);\r
-include_once('../toexport.inc.php');\r
-print "<pre>";\r
-print rs2csv($rs); # return a string\r
-\r
-print '<hr>';\r
-$rs->MoveFirst(); # note, some databases do not support MoveFirst\r
-print rs2tab($rs); # return a string\r
-\r
-print '<hr>';\r
-$rs->MoveFirst();\r
-rs2tabout($rs); # send to stdout directly\r
-print "</pre>";\r
-}\r
-\r
-$pager = new ADODB_Pager($db,$sql);\r
-$pager->showPageLinks = true;\r
-$pager->linksPerPage = 3;\r
-$pager->cache = 60;\r
-$pager->Render($rows=7);\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+       
+  Latest version is available at http://php.weblogs.com/
+*/
+
+error_reporting(E_ALL);
+
+
+include_once('../adodb.inc.php');
+include_once('../adodb-pager.inc.php');
+
+$driver = 'oci8';
+$sql = 'select  ID, firstname as "First Name", lastname as "Last Name" from adoxyz  order  by  id';
+//$sql = 'select count(*),firstname from adoxyz group by firstname order by 2 ';
+$sql = 'select distinct firstname, lastname from adoxyz  order  by  firstname';
+
+if ($driver == 'postgres') {
+       $db = NewADOConnection('postgres');
+       $db->PConnect('localhost','tester','test','test');
+}
+
+if ($driver == 'access') {
+       $db = NewADOConnection('access');
+       $db->PConnect("nwind", "", "", "");
+}
+
+if ($driver == 'ibase') {
+       $db = NewADOConnection('ibase');
+       $db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", "");
+       $sql = 'select distinct firstname, lastname  from adoxyz  order  by  firstname';
+
+}
+if ($driver == 'mssql') {
+       $db = NewADOConnection('mssql');
+       $db->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');
+}
+if ($driver == 'oci8') {
+       $db = NewADOConnection('oci8');
+       $db->Connect('','scott','natsoft');
+}
+
+if ($driver == 'access') {
+       $db = NewADOConnection('access');
+       $db->Connect('nwind');
+}
+
+if (empty($driver) or $driver == 'mysql') {
+       $db = NewADOConnection('mysql');
+       $db->Connect('localhost','root','','xphplens');
+}
+
+//$db->pageExecuteCountRows = false;
+
+$db->debug = true;
+
+if (0) {
+$rs = &$db->Execute($sql);
+include_once('../toexport.inc.php');
+print "<pre>";
+print rs2csv($rs); # return a string
+
+print '<hr>';
+$rs->MoveFirst(); # note, some databases do not support MoveFirst
+print rs2tab($rs); # return a string
+
+print '<hr>';
+$rs->MoveFirst();
+rs2tabout($rs); # send to stdout directly
+print "</pre>";
+}
+
+$pager = new ADODB_Pager($db,$sql);
+$pager->showPageLinks = true;
+$pager->linksPerPage = 3;
+$pager->cache = 60;
+$pager->Render($rows=7);
 ?>
\ No newline at end of file
index d3bd9d6469f40885273a8237d903c609fee144b2..05ef8ca87199c8f324a2c7f0d9c81e4f9a042649 100644 (file)
@@ -1,34 +1,34 @@
-<?php\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-  Set tabs to 4 for best viewing.\r
-       \r
-  Latest version is available at http://php.weblogs.com/\r
-*/\r
-\r
-error_reporting(E_ALL);\r
-\r
-include_once('../adodb-pear.inc.php');\r
-$username = 'root';\r
-$password = '';\r
-$hostname = 'localhost';\r
-$databasename = 'xphplens';\r
-$driver = 'mysql';\r
-\r
-$dsn = "$driver://$username:$password@$hostname/$databasename";\r
-\r
-$db = DB::Connect($dsn);\r
-$db->setFetchMode(ADODB_FETCH_ASSOC);\r
-$rs = $db->Query('select firstname,lastname from adoxyz');\r
-$cnt = 0;\r
-while ($arr = $rs->FetchRow()) {\r
-       print_r($arr);\r
-       print "<br>";\r
-       $cnt += 1;\r
-}\r
-\r
-if ($cnt != 50) print "<b>Error in \$cnt = $cnt</b>";\r
+<?php
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+       
+  Latest version is available at http://php.weblogs.com/
+*/
+
+error_reporting(E_ALL);
+
+include_once('../adodb-pear.inc.php');
+$username = 'root';
+$password = '';
+$hostname = 'localhost';
+$databasename = 'xphplens';
+$driver = 'mysql';
+
+$dsn = "$driver://$username:$password@$hostname/$databasename";
+
+$db = DB::Connect($dsn);
+$db->setFetchMode(ADODB_FETCH_ASSOC);
+$rs = $db->Query('select firstname,lastname from adoxyz');
+$cnt = 0;
+while ($arr = $rs->FetchRow()) {
+       print_r($arr);
+       print "<br>";
+       $cnt += 1;
+}
+
+if ($cnt != 50) print "<b>Error in \$cnt = $cnt</b>";
 ?>
\ No newline at end of file
index 597987c18eed02d5d3bab44a937060ac44745236..691aa5f988abab5c87ee90416a98dbe14cdc3d9c 100644 (file)
@@ -1,66 +1,66 @@
-<?php\r
-\r
-/* \r
-V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
-  Released under both BSD license and Lesser GPL library license. \r
-  Whenever there is any discrepancy between the two licenses, \r
-  the BSD license will take precedence. \r
-  Set tabs to 4 for best viewing.\r
-       \r
-  Latest version is available at http://php.weblogs.com/\r
-*/\r
-\r
-function NotifyExpire($ref,$key)\r
-{\r
-       print "<p><b>Notify Expiring=$ref, sessionkey=$key</b></p>";\r
-}\r
-\r
-//-------------------------------------------------------------------\r
-       \r
-       \r
-#### CONNECTION\r
-       $ADODB_SESSION_DRIVER='oci8';\r
-       $ADODB_SESSION_CONNECT='';\r
-       $ADODB_SESSION_USER ='scott';\r
-       $ADODB_SESSION_PWD ='natsoft';\r
-       $ADODB_SESSION_DB ='';\r
-       \r
-       \r
-### TURN DEBUGGING ON\r
-       $ADODB_SESS_DEBUG = true;\r
-\r
-       \r
-#### SETUP NOTIFICATION\r
-       $USER = 'JLIM'.rand();\r
-       $ADODB_SESSION_EXPIRE_NOTIFY = array('USER','NotifyExpire');\r
-\r
-       \r
-#### INIT\r
-       ob_start();\r
-       error_reporting(E_ALL);\r
-       include('../session/adodb-cryptsession.php');\r
-       session_start();\r
-\r
-\r
-### SETUP SESSION VARIABLES \r
-       $HTTP_SESSION_VARS['MONKEY'] = array('1','abc',44.41);\r
-       if (!isset($HTTP_GET_VARS['nochange'])) @$HTTP_SESSION_VARS['AVAR'] += 1;\r
-\r
-       \r
-### START DISPLAY\r
-       print "<h3>PHP ".PHP_VERSION."</h3>";\r
-       print "<p><b>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</b></p>";\r
-       \r
-       print "<hr> <b>Cookies</b>: ";\r
-       print_r($HTTP_COOKIE_VARS);\r
-       \r
-### RANDOMLY PERFORM Garbage Collection\r
-       if (rand() % 10 == 0) {\r
-       \r
-               print "<hr><p><b>Garbage Collection</b></p>";\r
-               adodb_sess_gc(10);\r
-               \r
-               print "<p>Random session destroy</p>";\r
-               session_destroy();\r
-       }\r
+<?php
+
+/* 
+V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
+  Set tabs to 4 for best viewing.
+       
+  Latest version is available at http://php.weblogs.com/
+*/
+
+function NotifyExpire($ref,$key)
+{
+       print "<p><b>Notify Expiring=$ref, sessionkey=$key</b></p>";
+}
+
+//-------------------------------------------------------------------
+       
+       
+#### CONNECTION
+       $ADODB_SESSION_DRIVER='oci8';
+       $ADODB_SESSION_CONNECT='';
+       $ADODB_SESSION_USER ='scott';
+       $ADODB_SESSION_PWD ='natsoft';
+       $ADODB_SESSION_DB ='';
+       
+       
+### TURN DEBUGGING ON
+       $ADODB_SESS_DEBUG = true;
+
+       
+#### SETUP NOTIFICATION
+       $USER = 'JLIM'.rand();
+       $ADODB_SESSION_EXPIRE_NOTIFY = array('USER','NotifyExpire');
+
+       
+#### INIT
+       ob_start();
+       error_reporting(E_ALL);
+       include('../session/adodb-cryptsession.php');
+       session_start();
+
+
+### SETUP SESSION VARIABLES 
+       $HTTP_SESSION_VARS['MONKEY'] = array('1','abc',44.41);
+       if (!isset($HTTP_GET_VARS['nochange'])) @$HTTP_SESSION_VARS['AVAR'] += 1;
+
+       
+### START DISPLAY
+       print "<h3>PHP ".PHP_VERSION."</h3>";
+       print "<p><b>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</b></p>";
+       
+       print "<hr> <b>Cookies</b>: ";
+       print_r($HTTP_COOKIE_VARS);
+       
+### RANDOMLY PERFORM Garbage Collection
+       if (rand() % 10 == 0) {
+       
+               print "<hr><p><b>Garbage Collection</b></p>";
+               adodb_sess_gc(10);
+               
+               print "<p>Random session destroy</p>";
+               session_destroy();
+       }
 ?>
\ No newline at end of file
index e20db41ed29513a2a0e92f9750fec6a6c27b408d..a3b743ca1f4127e535a74206322213777f625c20 100644 (file)
@@ -1,65 +1,65 @@
-<?php\r
-error_reporting(E_ALL);\r
-ini_set('mssql.datetimeconvert',0); \r
-\r
-function tmssql()\r
-{\r
-       print "<h3>mssql</h3>";\r
-       $db = mssql_connect('JAGUAR\vsdotnet','adodb','natsoft') or die('No Connection');\r
-       mssql_select_db('northwind',$db);\r
-       \r
-       $rs = mssql_query('select getdate() as date',$db);\r
-       $o = mssql_fetch_row($rs);\r
-       print_r($o);\r
-       mssql_free_result($rs);\r
-       \r
-       print "<p>Delete</p>"; flush();\r
-       $rs2 = mssql_query('delete from adoxyz',$db);\r
-       $p = mssql_num_rows($rs2);\r
-       mssql_free_result($rs2);\r
-\r
-}\r
-\r
-function tpear()\r
-{\r
-include_once('DB.php');\r
-\r
-       print "<h3>PEAR</h3>";\r
-       $username = 'adodb';\r
-       $password = 'natsoft';\r
-       $hostname = 'JAGUAR\vsdotnet';\r
-       $databasename = 'northwind';\r
-       \r
-       $dsn = "mssql://$username:$password@$hostname/$databasename";\r
-       $conn = &DB::connect($dsn);\r
-       print "date=".$conn->GetOne('select getdate()')."<br>";\r
-       @$conn->query('create table tester (id integer)');\r
-       print "<p>Delete</p>"; flush();\r
-       $rs = $conn->query('delete from tester');\r
-       print "date=".$conn->GetOne('select getdate()')."<br>";\r
-}\r
-\r
-function tadodb()\r
-{\r
-include_once('../adodb.inc.php');\r
-\r
-       print "<h3>ADOdb</h3>";\r
-       $conn = NewADOConnection('mssql');\r
-       $conn->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');\r
-//     $conn->debug=1;\r
-       print "date=".$conn->GetOne('select getdate()')."<br>";\r
-       $conn->Execute('create table tester (id integer)');\r
-       print "<p>Delete</p>"; flush();\r
-       $rs = $conn->Execute('delete from tester');\r
-       print "date=".$conn->GetOne('select getdate()')."<br>";\r
-}\r
-?>\r
-<a href=tmssql.php?do=tmssql>mssql</a>\r
-<a href=tmssql.php?do=tpear>pear</a>\r
-<a href=tmssql.php?do=tadodb>adodb</a>\r
-<?php\r
-if (!empty($_GET['do'])) {\r
-       $do = $_GET['do'];\r
-       $do();\r
-}\r
+<?php
+error_reporting(E_ALL);
+ini_set('mssql.datetimeconvert',0); 
+
+function tmssql()
+{
+       print "<h3>mssql</h3>";
+       $db = mssql_connect('JAGUAR\vsdotnet','adodb','natsoft') or die('No Connection');
+       mssql_select_db('northwind',$db);
+       
+       $rs = mssql_query('select getdate() as date',$db);
+       $o = mssql_fetch_row($rs);
+       print_r($o);
+       mssql_free_result($rs);
+       
+       print "<p>Delete</p>"; flush();
+       $rs2 = mssql_query('delete from adoxyz',$db);
+       $p = mssql_num_rows($rs2);
+       mssql_free_result($rs2);
+
+}
+
+function tpear()
+{
+include_once('DB.php');
+
+       print "<h3>PEAR</h3>";
+       $username = 'adodb';
+       $password = 'natsoft';
+       $hostname = 'JAGUAR\vsdotnet';
+       $databasename = 'northwind';
+       
+       $dsn = "mssql://$username:$password@$hostname/$databasename";
+       $conn = &DB::connect($dsn);
+       print "date=".$conn->GetOne('select getdate()')."<br>";
+       @$conn->query('create table tester (id integer)');
+       print "<p>Delete</p>"; flush();
+       $rs = $conn->query('delete from tester');
+       print "date=".$conn->GetOne('select getdate()')."<br>";
+}
+
+function tadodb()
+{
+include_once('../adodb.inc.php');
+
+       print "<h3>ADOdb</h3>";
+       $conn = NewADOConnection('mssql');
+       $conn->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');
+//     $conn->debug=1;
+       print "date=".$conn->GetOne('select getdate()')."<br>";
+       $conn->Execute('create table tester (id integer)');
+       print "<p>Delete</p>"; flush();
+       $rs = $conn->Execute('delete from tester');
+       print "date=".$conn->GetOne('select getdate()')."<br>";
+}
+?>
+<a href=tmssql.php?do=tmssql>mssql</a>
+<a href=tmssql.php?do=tpear>pear</a>
+<a href=tmssql.php?do=tadodb>adodb</a>
+<?php
+if (!empty($_GET['do'])) {
+       $do = $_GET['do'];
+       $do();
+}
 ?>
\ No newline at end of file
index acae10741abdcc47c72cf5739bfeccf7e56e4a18..6fc9ab798a6d1338461aa4d9449111a9225fd008 100644 (file)
@@ -1,29 +1,30 @@
-<?xml version="1.0"?>\r
-<schema>\r
-  <table name="mytable">\r
-    <field name="row1" type="I">\r
-      <descr>An integer row that's a primary key and autoincrements</descr>\r
-      <KEY/>\r
-      <AUTOINCREMENT/>\r
-    </field>\r
-    <field name="row2" type="C" size="16">\r
-      <descr>A 16 character varchar row that can't be null</descr>\r
-      <NOTNULL/>\r
-    </field>\r
-  </table>\r
-  <index name="myindex" table="mytable">\r
-    <col>row1</col>\r
-    <col>row2</col>\r
-  </index>\r
-  <sql>\r
-    <descr>SQL to be executed only on specific platforms</descr>\r
-    <query platform="postgres|postgres7">\r
-      insert into mytable ( row1, row2 ) values ( 12, 'stuff' )\r
-    </query>\r
-    <query platform="mysql">\r
-      insert into mytable ( row1, row2 ) values ( 12, 'different stuff' )\r
-    </query>\r
-  </sql>\r
-  <table name="obsoletetable"><DROP/></table>\r
-  <index name="obsoleteindex"><DROP/></index>\r
-</schema>\r
+<?xml version="1.0"?>
+<schema version="0.2">
+  <table name="mytable">
+    <field name="row1" type="I">
+      <descr>An integer row that's a primary key and autoincrements</descr>
+      <KEY/>
+      <AUTOINCREMENT/>
+    </field>
+    <field name="row2" type="C" size="16">
+      <descr>A 16 character varchar row that can't be null</descr>
+      <NOTNULL/>
+    </field>
+    <index name="myindex">
+      <col>row1</col>
+      <col>row2</col>
+    </index>
+  </table>
+  <sql>
+    <descr>SQL to be executed only on specific platforms</descr>
+    <query platform="postgres|postgres7">
+      insert into mytable ( row1, row2 ) values ( 12, 'postgres stuff' )
+    </query>
+    <query platform="mysql">
+      insert into mytable ( row1, row2 ) values ( 12, 'mysql stuff' )
+    </query>
+  </sql>
+  <table name="obsoletetable">
+    <DROP/>
+  </table>
+</schema>
\ No newline at end of file
index c5a63fc54e87801e4d878e09f690b03c678cfdd1..80c9e2af3a08ea2a362bfd00c70a7e175cd2983a 100644 (file)
-<?php\r
-\r
-/** \r
- * @version V4.11 27 Jan 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
- * Released under both BSD license and Lesser GPL library license. \r
- * Whenever there is any discrepancy between the two licenses, \r
- * the BSD license will take precedence. \r
- *\r
- * Code to export recordsets in several formats:\r
- *\r
- * AS VARIABLE\r
- * $s = rs2csv($rs); # comma-separated values\r
- * $s = rs2tab($rs); # tab delimited\r
- * \r
- * TO A FILE\r
- * $f = fopen($path,'w');\r
- * rs2csvfile($rs,$f);\r
- * fclose($f);\r
- *\r
- * TO STDOUT\r
- * rs2csvout($rs);\r
- */\r
\r
-// returns a recordset as a csv string\r
-function rs2csv(&$rs,$addtitles=true)\r
-{\r
-       return _adodb_export($rs,',',',',false,$addtitles);\r
-}\r
-\r
-// writes recordset to csv file \r
-function rs2csvfile(&$rs,$fp,$addtitles=true)\r
-{\r
-       _adodb_export($rs,',',',',$fp,$addtitles);\r
-}\r
-\r
-// write recordset as csv string to stdout\r
-function rs2csvout(&$rs,$addtitles=true)\r
-{\r
-       $fp = fopen('php://stdout','wb');\r
-       _adodb_export($rs,',',',',true,$addtitles);\r
-       fclose($fp);\r
-}\r
-\r
-function rs2tab(&$rs,$addtitles=true)\r
-{\r
-       return _adodb_export($rs,"\t",',',false,$addtitles);\r
-}\r
-\r
-// to file pointer\r
-function rs2tabfile(&$rs,$fp,$addtitles=true)\r
-{\r
-       _adodb_export($rs,"\t",',',$fp,$addtitles);\r
-}\r
-\r
-// to stdout\r
-function rs2tabout(&$rs,$addtitles=true)\r
-{\r
-       $fp = fopen('php://stdout','wb');\r
-       _adodb_export($rs,"\t",' ',true,$addtitles);\r
-       fclose($fp);\r
-}\r
-\r
-function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote = '"',$escquote = '"',$replaceNewLine = ' ')\r
-{\r
-       if (!$rs) return '';\r
-       //----------\r
-       // CONSTANTS\r
-       $NEWLINE = "\r\n";\r
-       $BUFLINES = 100;\r
-       $escquotequote = $escquote.$quote;\r
-       $s = '';\r
-       \r
-       if ($addtitles) {\r
-               $fieldTypes = $rs->FieldTypesArray();\r
-               reset($fieldTypes);\r
-               while(list(,$o) = each($fieldTypes)) {\r
-                       \r
-                       $v = $o->name;\r
-                       if ($escquote) $v = str_replace($quote,$escquotequote,$v);\r
-                       $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));\r
-                       $elements[] = $v;\r
-                       \r
-               }\r
-               $s .= implode($sep, $elements).$NEWLINE;\r
-       }\r
-       $hasNumIndex = isset($rs->fields[0]);\r
-       \r
-       $line = 0;\r
-       $max = $rs->FieldCount();\r
-       \r
-       while (!$rs->EOF) {\r
-               $elements = array();\r
-               $i = 0;\r
-               \r
-               if ($hasNumIndex) {\r
-                       for ($j=0; $j < $max; $j++) {\r
-                               $v = trim($rs->fields[$j]);\r
-                               if ($escquote) $v = str_replace($quote,$escquotequote,$v);\r
-                               $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));\r
-                               \r
-                               if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";\r
-                               else $elements[] = $v;\r
-                       }\r
-               } else { // ASSOCIATIVE ARRAY\r
-                       foreach($rs->fields as $v) {\r
-                               if ($escquote) $v = str_replace($quote,$escquotequote,trim($v));\r
-                               $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));\r
-                               \r
-                               if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";\r
-                               else $elements[] = $v;\r
-                       }\r
-               }\r
-               $s .= implode($sep, $elements).$NEWLINE;\r
-               $rs->MoveNext();\r
-               $line += 1;\r
-               if ($fp && ($line % $BUFLINES) == 0) {\r
-                       if ($fp === true) echo $s;\r
-                       else fwrite($fp,$s);\r
-                       $s = '';\r
-               }\r
-       }\r
-       \r
-       if ($fp) {\r
-               if ($fp === true) echo $s;\r
-               else fwrite($fp,$s);\r
-               $s = '';\r
-       }\r
-       \r
-       return $s;\r
-}\r
+<?php
+
+/** 
+ * @version V4.20 22 Feb 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
+ *
+ * Code to export recordsets in several formats:
+ *
+ * AS VARIABLE
+ * $s = rs2csv($rs); # comma-separated values
+ * $s = rs2tab($rs); # tab delimited
+ * 
+ * TO A FILE
+ * $f = fopen($path,'w');
+ * rs2csvfile($rs,$f);
+ * fclose($f);
+ *
+ * TO STDOUT
+ * rs2csvout($rs);
+ */
+// returns a recordset as a csv string
+function rs2csv(&$rs,$addtitles=true)
+{
+       return _adodb_export($rs,',',',',false,$addtitles);
+}
+
+// writes recordset to csv file 
+function rs2csvfile(&$rs,$fp,$addtitles=true)
+{
+       _adodb_export($rs,',',',',$fp,$addtitles);
+}
+
+// write recordset as csv string to stdout
+function rs2csvout(&$rs,$addtitles=true)
+{
+       $fp = fopen('php://stdout','wb');
+       _adodb_export($rs,',',',',true,$addtitles);
+       fclose($fp);
+}
+
+function rs2tab(&$rs,$addtitles=true)
+{
+       return _adodb_export($rs,"\t",',',false,$addtitles);
+}
+
+// to file pointer
+function rs2tabfile(&$rs,$fp,$addtitles=true)
+{
+       _adodb_export($rs,"\t",',',$fp,$addtitles);
+}
+
+// to stdout
+function rs2tabout(&$rs,$addtitles=true)
+{
+       $fp = fopen('php://stdout','wb');
+       _adodb_export($rs,"\t",' ',true,$addtitles);
+       fclose($fp);
+}
+
+function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote = '"',$escquote = '"',$replaceNewLine = ' ')
+{
+       if (!$rs) return '';
+       //----------
+       // CONSTANTS
+       $NEWLINE = "\r\n";
+       $BUFLINES = 100;
+       $escquotequote = $escquote.$quote;
+       $s = '';
+       
+       if ($addtitles) {
+               $fieldTypes = $rs->FieldTypesArray();
+               reset($fieldTypes);
+               while(list(,$o) = each($fieldTypes)) {
+                       
+                       $v = $o->name;
+                       if ($escquote) $v = str_replace($quote,$escquotequote,$v);
+                       $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
+                       $elements[] = $v;
+                       
+               }
+               $s .= implode($sep, $elements).$NEWLINE;
+       }
+       $hasNumIndex = isset($rs->fields[0]);
+       
+       $line = 0;
+       $max = $rs->FieldCount();
+       
+       while (!$rs->EOF) {
+               $elements = array();
+               $i = 0;
+               
+               if ($hasNumIndex) {
+                       for ($j=0; $j < $max; $j++) {
+                               $v = trim($rs->fields[$j]);
+                               if ($escquote) $v = str_replace($quote,$escquotequote,$v);
+                               $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
+                               
+                               if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
+                               else $elements[] = $v;
+                       }
+               } else { // ASSOCIATIVE ARRAY
+                       foreach($rs->fields as $v) {
+                               if ($escquote) $v = str_replace($quote,$escquotequote,trim($v));
+                               $v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
+                               
+                               if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
+                               else $elements[] = $v;
+                       }
+               }
+               $s .= implode($sep, $elements).$NEWLINE;
+               $rs->MoveNext();
+               $line += 1;
+               if ($fp && ($line % $BUFLINES) == 0) {
+                       if ($fp === true) echo $s;
+                       else fwrite($fp,$s);
+                       $s = '';
+               }
+       }
+       
+       if ($fp) {
+               if ($fp === true) echo $s;
+               else fwrite($fp,$s);
+               $s = '';
+       }
+       
+       return $s;
+}
 ?>
\ No newline at end of file
index d42c7d8993dbed1cbb9868c592b185457cf91995..dac81ddb756b874cf8777bd4673c959ea2e60c01 100644 (file)
@@ -1,6 +1,6 @@
 <?php \r
 /*\r
-  V4.11 27 Jan 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
+  V4.20 22 Feb 2004  (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved.\r
   Released under both BSD license and Lesser GPL library license. \r
   Whenever there is any discrepancy between the two licenses, \r
   the BSD license will take precedence.\r
@@ -64,9 +64,8 @@ GLOBAL $gSQLMaxRows,$gSQLBlockRows;
        if ($echo) print $hdr."\n\n";\r
        else $html = $hdr;\r
        \r
-       // smart algorithm - handles ADODB_FETCH_MODE's correctly!\r
-       $numoffset = isset($rs->fields[0]);\r
-\r
+       // smart algorithm - handles ADODB_FETCH_MODE's correctly by probing...\r
+       $numoffset = isset($rs->fields[0]) ||isset($rs->fields[1]) || isset($rs->fields[2]);\r
        while (!$rs->EOF) {\r
                \r
                $s .= "<TR valign=top>\n";\r
index b060a98513b9192bf12c564c989021419a4b4e6e..3f2261e62de9808f5ac794d12c6ab860a1b1dee7 100644 (file)
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
-\r
-<html>\r
-<head>\r
-       <title>Tutorial: Moving from MySQL to ADODB</title>\r
-</head>\r
-\r
-<body bgcolor=white>\r
-<h1>Tutorial: Moving from MySQL to ADODB</h1>\r
-\r
-<pre>          You say eether and I say eyether, \r
-               You say neether and I say nyther; \r
-               Eether, eyether, neether, nyther - \r
-               Let's call the whole thing off ! \r
-<br>\r
-               You like potato and I like po-tah-to, \r
-               You like tomato and I like to-mah-to; \r
-               Potato, po-tah-to, tomato, to-mah-to - \r
-               Let's call the whole thing off ! \r
-</pre>\r
-<p>I love this song, especially the version with Louis Armstrong and Ella singing \r
-  duet. It is all about how hard it is for two people in love to be compatible \r
-  with each other. It's about compromise and finding a common ground, and that's \r
-  what this article is all about. \r
-<p>PHP is all about creating dynamic web-sites with the least fuss and the most \r
-  fun. To create these websites we need to use databases to retrieve login information, \r
-  to splash dynamic news onto the web page and store forum postings. So let's \r
-  say we were using the popular MySQL database for this. Your company has done \r
-  such a fantastic job that the Web site is more popular than your wildest dreams. \r
-  You find that MySQL cannot scale to handle the workload; time to switch databases. \r
-<p> Unfortunately in PHP every database is accessed slightly differently. To connect \r
-  to MySQL, you would use <i>mysql_connect()</i>; when you decide to upgrade to \r
-  Oracle or Microsoft SQL Server, you would use <i>ocilogon() </i>or <i>mssql_connect()</i> \r
-  respectively. What is worse is that the parameters you use for the different \r
-  connect functions are different also.. One database says po-tato, the other \r
-  database says pota-to. Oh-oh. \r
-<h3>Let's NOT call the whole thing off</h3>\r
-<p>A database wrapper library such as ADODB comes in handy when you need to ensure portability. It provides \r
-  you with a common API to communicate with any supported database so you don't have to call things off. <p>\r
-\r
-<p>ADODB stands for Active Data Objects DataBase (sorry computer guys are sometimes \r
-  not very original). ADODB currently supports MySQL, PostgreSQL, Oracle, Interbase, \r
-  Microsoft SQL Server, Access, FoxPro, Sybase, ODBC and ADO. You can download \r
-  ADODB from <a href=http://php.weblogs.com/adodb></a><a href="http://php.weblogs.com/adodb">http://php.weblogs.com/adodb</a>.\r
-<h3>MySQL Example</h3>\r
-<p>The most common database used with PHP is MySQL, so I guess you should be familiar \r
-  with the following code. It connects to a MySQL server at <i>localhost</i>, \r
-  database <i>mydb</i>, and executes an SQL select statement. The results are \r
-  printed, one line per row. \r
-<pre><font color="#666600">$db = <b>mysql_connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;);\r
-<b>mysql_select_db</b>(&quot;mydb&quot;,$db);</font>\r
-<font color="#660000">$result = <b>mysql_query</b>(&quot;SELECT * FROM employees&quot;,$db)</font><code><font color="#663300">;\r
-if ($result === false) die(&quot;failed&quot;);</font></code> \r
-<font color="#006666"><b>while</b> ($fields =<b> mysql_fetch_row</b>($result)) &#123;\r
- <b>for</b> ($i=0, $max=sizeof($fields); $i &lt; $max; $i++) &#123;\r
-               <b>print</b> $fields[$i].' ';\r
- &#125;\r
- <b>print</b> &quot;&lt;br&gt;\n&quot;;\r
-&#125;</font> \r
-</pre>\r
-<p>The above code has been color-coded by section. The first section is the connection \r
-  phase. The second is the execution of the SQL, and the last section is displaying \r
-  the fields. The <i>while</i> loop scans the rows of the result, while the <i>for</i> \r
-  loop scans the fields in one row.</p>\r
-<p>Here is the equivalent code in ADODB</p>\r
-<pre><b><font color="#666600"> include(&quot;adodb.inc.php&quot;);</font></b><font color="#666600">\r
- $db = <b>NewADOConnection</b>('mysql');\r
- $db-&gt;<b>Connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;mydb&quot;);</font>\r
- <font color="#663300">$result = $db-&gt;<b>Execute</b>(&quot;SELECT * FROM employees&quot;);\r
- </font><font color="#663300"></font><code><font color="#663300">if ($result === false) die(&quot;failed&quot;)</font></code><code><font color="#663300">;</font></code>  \r
- <font color="#006666"><b>while</b> (!$result-&gt;EOF) &#123;\r
-       <b>for</b> ($i=0, $max=$result-&gt;<b>FieldCount</b>(); $i &lt; $max; $i++)\r
-                  <b>print</b> $result-&gt;fields[$i].' ';\r
-       $result-&gt;<b>MoveNext</b>();\r
-       <b>print</b> &quot;&lt;br&gt;\n&quot;;\r
- &#125;</font> </pre>\r
-<p></p>\r
-<p>Now porting to Oracle is as simple as changing the second line to <code>NewADOConnection('oracle')</code>. \r
-  Let's walk through the code...</p>\r
-<h3>Connecting to the Database</h3>\r
-<p></p>\r
-<pre><b><font color="#666600">include(&quot;adodb.inc.php&quot;);</font></b><font color="#666600">\r
-$db = <b>NewADOConnection</b>('mysql');\r
-$db-&gt;<b>Connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;mydb&quot;);</font></pre>\r
-<p>The connection code is a bit more sophisticated than MySQL's because our needs \r
-  are more sophisticated. In ADODB, we use an object-oriented approach to managing \r
-  the complexity of handling multiple databases. We have different classes to \r
-  handle different databases. If you aren't familiar with object-oriented programing, \r
-  don't worry -- the complexity is all hidden away in the<code> NewADOConnection()</code> \r
-  function.</p>\r
-<p>To conserve memory, we only load the PHP code specific to the database you \r
-  are connecting to. We do this by calling <code>NewADOConnection(databasedriver)</code>. \r
-  Legal database drivers include <i>mysql, mssql, oracle, oci8, postgres, sybase, \r
-  vfp, access, ibase </i>and many others.</p>\r
-<p>Then we create a new instance of the connection class by calling <code>NewADOConnection()</code>. \r
-  Finally we connect to the database using <code>$db-&gt;Connect(). </code></p>\r
-<h3>Executing the SQL</h3>\r
-<p><code><font color="#663300">$result = $db-&gt;<b>Execute</b>(&quot;SELECT * \r
-  FROM employees&quot;);<br>\r
-  if ($result === false) die(&quot;failed&quot;)</font></code><code><font color="#663300">;</font></code> \r
-  <br>\r
-</p>\r
-<p>Sending the SQL statement to the server is straight forward. Execute() will \r
-  return a recordset object on successful execution. You should check $result \r
-  as we do above.\r
-<p>An issue that confuses beginners is the fact that we have two types of objects \r
-  in ADODB, the connection object and the recordset object. When do we use each?\r
-<p>The connection object ($db) is responsible for connecting to the database, \r
-  formatting your SQL and querying the database server. The recordset object ($result) \r
-  is responsible for retrieving the results and formatting the reply as text or \r
-  as an array.\r
-<p>The only thing I need to add is that ADODB provides several helper functions \r
-  for making INSERT and UPDATE statements easier, which we will cover in the Advanced \r
-  section. \r
-<h3>Retrieving the Data<br>\r
-</h3>\r
-<pre><font color="#006666"><b>while</b> (!$result-&gt;EOF) &#123;\r
-   <b>for</b> ($i=0, $max=$result-&gt;<b>FieldCount</b>(); $i &lt; $max; $i++)\r
-          <b>print</b> $result-&gt;fields[$i].' ';\r
-   $result-&gt;<b>MoveNext</b>();\r
-   <b>print</b> &quot;&lt;br&gt;\n&quot;;\r
-&#125;</font></pre>\r
-<p>The paradigm for getting the data is that it's like reading a file. For every \r
-  line, we check first whether we have reached the end-of-file (EOF). While not \r
-  end-of-file, loop through each field in the row. Then move to the next line \r
-  (MoveNext) and repeat. \r
-<p>The <code>$result-&gt;fields[]</code> array is generated by the PHP database \r
-  extension. Some database extensions do not index the array by field name. \r
-  To force indexing by name - that is associative arrays - \r
-  use the $ADODB_FETCH_MODE global variable. \r
-<pre>\r
-       $<b>ADODB_FETCH_MODE</b> = ADODB_FETCH_NUM;\r
-       $rs1 = $db->Execute('select * from table');\r
-       $<b>ADODB_FETCH_MODE</b> = ADODB_FETCH_ASSOC;\r
-       $rs2 = $db->Execute('select * from table');\r
-       print_r($rs1->fields); // shows <i>array([0]=>'v0',[1] =>'v1')</i>\r
-       print_r($rs2->fields); // shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i>\r
-</pre>\r
-<p>\r
-As you can see in the above example, both recordsets store and use different fetch modes\r
-based on the $ADODB_FETCH_MODE setting when the recordset was created by Execute().</p>\r
-<h2>ADOConnection<a name="ADOConnection"></a></h2>\r
-<p>Object that performs the connection to the database, executes SQL statements \r
-  and has a set of utility functions for standardising the format of SQL statements \r
-  for issues such as concatenation and date formats.</p>\r
-  \r
-<h3>Other Useful Functions</h3>\r
-<p><code>$recordset-&gt;Move($pos)</code> scrolls to that particular row. ADODB supports forward \r
-  scrolling for all databases. Some databases will not support backwards scrolling. \r
-  This is normally not a problem as you can always cache records to simulate backwards \r
-  scrolling. \r
-<p><code>$recordset-&gt;RecordCount()</code> returns the number of records accessed by the \r
-  SQL statement. Some databases will return -1 because it is not supported. \r
-<p><code>$recordset-&gt;GetArray()</code> returns the result as an array. \r
-<p><code>rs2html($recordset)</code> is a function that is generates a HTML table based on the \r
-  $recordset passed to it. An example with the relevant lines in bold:\r
-<pre>   include('adodb.inc.php'); \r
-   <b>include('tohtml.inc.php');</b> /* includes the rs2html function */\r
-   $conn = &amp;ADONewConnection('mysql'); \r
-   $conn-&gt;PConnect('localhost','userid','password','database');\r
-   $rs = $conn-&gt;Execute('select * from table');\r
-  <b> rs2html($rs)</b>; /* recordset to html table */ </pre>\r
-<p>There are many other helper functions that are listed in the documentation available at <a href="http://php.weblogs.com/adodb_manual"></a><a href="http://php.weblogs.com/adodb_manual">http://php.weblogs.com/adodb_manual</a>. \r
-<h2>Advanced Material</h2>\r
-<h3>Inserts and Updates </h3>\r
-<p>Let's say you want to insert the following data into a database. \r
-<p><b>ID</b> = 3<br>\r
-  <b>TheDate</b>=mktime(0,0,0,8,31,2001) /* 31st August 2001 */<br>\r
-  <b>Note</b>= sugar why don't we call it off \r
-<p>When you move to another database, your insert might no longer work.</p>\r
-<p>The first problem is that each database has a different default date format. \r
-  MySQL expects YYYY-MM-DD format, while other databases have different defaults. \r
-  ADODB has a function called DBDate() that addresses this issue by converting \r
-  converting the date to the correct format.</p>\r
-<p>The next problem is that the <b>don't</b> in the Note needs to be quoted. In \r
-  MySQL, we use <b>don\'t</b> but in some other databases (Sybase, Access, Microsoft \r
-  SQL Server) we use <b>don''t. </b>The qstr() function addresses this issue.</p>\r
-<p>So how do we use the functions? Like this:</p>\r
-<pre>$sql = &quot;INSERT INTO table (id, thedate,note) values (&quot; \r
-   . $<b>ID</b> . ','\r
-   . $db-&gt;DBDate($<b>TheDate</b>) .','\r
-   . $db-&gt;qstr($<b>Note</b>).&quot;)&quot;;\r
-$db-&gt;Execute($sql);</pre>\r
-<p>ADODB also supports <code>$connection-&gt;Affected_Rows()</code> (returns the \r
-  number of rows affected by last update or delete) and <code>$recordset-&gt;Insert_ID()</code> \r
-  (returns last autoincrement number generated by an insert statement). Be forewarned \r
-  that not all databases support the two functions.<br>\r
-</p>\r
-<h3>MetaTypes</h3>\r
-<p>You can find out more information about each of the fields (I use the words \r
-  fields and columns interchangebly) you are selecting by calling the recordset \r
-  method <code>FetchField($fieldoffset)</code>. This will return an object with \r
-  3 properties: name, type and max_length. \r
-<pre>For example:</pre>\r
-<pre>$recordset = $conn-&gt;Execute(&quot;select adate from table&quot;);<br>$f0 = $recordset-&gt;FetchField(0);\r
-</pre>\r
-<p>Then <code>$f0-&gt;name</code> will hold <i>'adata'</i>, <code>$f0-&gt;type</code> \r
-  will be set to '<i>date'</i>. If the max_length is unknown, it will be set to \r
-  -1. \r
-<p>One problem with handling different databases is that each database often calls \r
-  the same type by a different name. For example a <i>timestamp</i> type is called \r
-  <i>datetime</i> in one database and <i>time</i> in another. So ADODB has a special \r
-  <code>MetaType($type, $max_length)</code> function that standardises the types \r
-  to the following: \r
-<p>C: character and varchar types<br>\r
-  X: text or long character (eg. more than 255 bytes wide).<br>\r
-  B: blob or binary image<br>\r
-  D: date<br>\r
-  T: timestamp<br>\r
-  L: logical (boolean)<br>\r
-  I: integer<br>\r
-  N: numeric (float, double, money) \r
-<p>In the above date example, \r
-<p><code>$recordset = $conn-&gt;Execute(&quot;select adate from table&quot;);<br>\r
-  $f0 = $recordset-&gt;FetchField(0);<br>\r
-  $type = $recordset-&gt;MetaType($f0-&gt;type, $f0-&gt;max_length);<br>\r
-  print $type; /* should print 'D'</code> */\r
-<p> \r
-<p><b>Select Limit and Top Support</b> \r
-<p>ADODB has a function called $connection->SelectLimit($sql,$nrows,$offset) that allows\r
-you to retrieve a subset of the recordset. This will take advantage of native\r
-SELECT TOP on Microsoft products and SELECT ... LIMIT with PostgreSQL and MySQL, and\r
-emulated if the database does not support it.\r
-<p><b>Caching Support</b> \r
-<p>ADODB allows you to cache recordsets in your file system, and only requery the database\r
-server after a certain timeout period with $connection->CacheExecute($secs2cache,$sql) and \r
-$connection->CacheSelectLimit($secs2cache,$sql,$nrows,$offset).\r
-<p><b>PHP4 Session Handler Support</b> \r
-<p>ADODB also supports PHP4 session handlers. You can store your session variables \r
-  in a database for true scalability using ADODB. For further information, visit \r
-  <a href="http://php.weblogs.com/adodb-sessions"></a><a href="http://php.weblogs.com/adodb-sessions">http://php.weblogs.com/adodb-sessions</a>\r
-<h3>Commercial Use Encouraged</h3>\r
-<p>If you plan to write commercial PHP applications that you want to resell, you should consider ADODB. It has been released using the lesser GPL, which means you can legally include it in commercial applications, while keeping your code proprietary. Commercial use of ADODB is strongly encouraged! We are using it internally for this reason.<p>\r
-\r
-<h2>Conclusion</h2>\r
-<p>As a thank you for finishing this article, here are the complete lyrics for \r
-  <i>let's call the whole thing off</i>.<br>\r
-  <br>\r
-<pre>\r
-   Refrain \r
-<br>\r
-               You say eether and I say eyether, \r
-               You say neether and I say nyther; \r
-               Eether, eyether, neether, nyther - \r
-               Let's call the whole thing off ! \r
-<br>\r
-               You like potato and I like po-tah-to, \r
-               You like tomato and I like to-mah-to; \r
-               Potato, po-tah-to, tomato, to-mah-to - \r
-               Let's call the whole thing off ! \r
-<br>\r
-But oh, if we call the whole thing off, then we must part. \r
-And oh, if we ever part, then that might break my heart. \r
-<br>\r
-               So, if you like pajamas and I like pa-jah-mas, \r
-               I'll wear pajamas and give up pa-jah-mas. \r
-               For we know we \r
-               Need each other, so we \r
-               Better call the calling off off. \r
-               Let's call the whole thing off ! \r
-<br>\r
-   Second Refrain \r
-<br>\r
-               You say laughter and I say lawfter, \r
-               You say after and I say awfter; \r
-               Laughter, lawfter, after, awfter - \r
-               Let's call the whole thing off ! \r
-<br>\r
-               You like vanilla and I like vanella, \r
-               You, sa's'parilla and I sa's'parella; \r
-               Vanilla, vanella, choc'late, strawb'ry - \r
-               Let's call the whole thing off ! \r
-<br>\r
-But oh, if we call the whole thing off, then we must part. \r
-And oh, if we ever part, then that might break my heart. \r
-<br>\r
-               So, if you go for oysters and I go for ersters, \r
-               I'll order oysters and cancel the ersters. \r
-               For we know we \r
-               Need each other, so we \r
-               Better call the calling off off. \r
-               Let's call the whole thing off ! \r
-  </pre>\r
-<p><font size=2>Song and lyrics by George and Ira Gershwin, introduced by Fred Astaire and Ginger Rogers\r
-in the film "Shall We Dance?"  </font><p>\r
-<p>\r
-(c)2001-2002 John Lim.\r
-\r
-</body>\r
-</html>\r
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+
+<html>
+<head>
+       <title>Tutorial: Moving from MySQL to ADODB</title>
+</head>
+
+<body bgcolor=white>
+<h1>Tutorial: Moving from MySQL to ADODB</h1>
+
+<pre>          You say eether and I say eyether, 
+               You say neether and I say nyther; 
+               Eether, eyether, neether, nyther - 
+               Let's call the whole thing off ! 
+<br>
+               You like potato and I like po-tah-to, 
+               You like tomato and I like to-mah-to; 
+               Potato, po-tah-to, tomato, to-mah-to - 
+               Let's call the whole thing off ! 
+</pre>
+<p>I love this song, especially the version with Louis Armstrong and Ella singing 
+  duet. It is all about how hard it is for two people in love to be compatible 
+  with each other. It's about compromise and finding a common ground, and that's 
+  what this article is all about. 
+<p>PHP is all about creating dynamic web-sites with the least fuss and the most 
+  fun. To create these websites we need to use databases to retrieve login information, 
+  to splash dynamic news onto the web page and store forum postings. So let's 
+  say we were using the popular MySQL database for this. Your company has done 
+  such a fantastic job that the Web site is more popular than your wildest dreams. 
+  You find that MySQL cannot scale to handle the workload; time to switch databases. 
+<p> Unfortunately in PHP every database is accessed slightly differently. To connect 
+  to MySQL, you would use <i>mysql_connect()</i>; when you decide to upgrade to 
+  Oracle or Microsoft SQL Server, you would use <i>ocilogon() </i>or <i>mssql_connect()</i> 
+  respectively. What is worse is that the parameters you use for the different 
+  connect functions are different also.. One database says po-tato, the other 
+  database says pota-to. Oh-oh. 
+<h3>Let's NOT call the whole thing off</h3>
+<p>A database wrapper library such as ADODB comes in handy when you need to ensure portability. It provides 
+  you with a common API to communicate with any supported database so you don't have to call things off. <p>
+
+<p>ADODB stands for Active Data Objects DataBase (sorry computer guys are sometimes 
+  not very original). ADODB currently supports MySQL, PostgreSQL, Oracle, Interbase, 
+  Microsoft SQL Server, Access, FoxPro, Sybase, ODBC and ADO. You can download 
+  ADODB from <a href=http://php.weblogs.com/adodb></a><a href="http://php.weblogs.com/adodb">http://php.weblogs.com/adodb</a>.
+<h3>MySQL Example</h3>
+<p>The most common database used with PHP is MySQL, so I guess you should be familiar 
+  with the following code. It connects to a MySQL server at <i>localhost</i>, 
+  database <i>mydb</i>, and executes an SQL select statement. The results are 
+  printed, one line per row. 
+<pre><font color="#666600">$db = <b>mysql_connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;);
+<b>mysql_select_db</b>(&quot;mydb&quot;,$db);</font>
+<font color="#660000">$result = <b>mysql_query</b>(&quot;SELECT * FROM employees&quot;,$db)</font><code><font color="#663300">;
+if ($result === false) die(&quot;failed&quot;);</font></code> 
+<font color="#006666"><b>while</b> ($fields =<b> mysql_fetch_row</b>($result)) &#123;
+ <b>for</b> ($i=0, $max=sizeof($fields); $i &lt; $max; $i++) &#123;
+               <b>print</b> $fields[$i].' ';
+ &#125;
+ <b>print</b> &quot;&lt;br&gt;\n&quot;;
+&#125;</font> 
+</pre>
+<p>The above code has been color-coded by section. The first section is the connection 
+  phase. The second is the execution of the SQL, and the last section is displaying 
+  the fields. The <i>while</i> loop scans the rows of the result, while the <i>for</i> 
+  loop scans the fields in one row.</p>
+<p>Here is the equivalent code in ADODB</p>
+<pre><b><font color="#666600"> include(&quot;adodb.inc.php&quot;);</font></b><font color="#666600">
+ $db = <b>NewADOConnection</b>('mysql');
+ $db-&gt;<b>Connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;mydb&quot;);</font>
+ <font color="#663300">$result = $db-&gt;<b>Execute</b>(&quot;SELECT * FROM employees&quot;);
+ </font><font color="#663300"></font><code><font color="#663300">if ($result === false) die(&quot;failed&quot;)</font></code><code><font color="#663300">;</font></code>  
+ <font color="#006666"><b>while</b> (!$result-&gt;EOF) &#123;
+       <b>for</b> ($i=0, $max=$result-&gt;<b>FieldCount</b>(); $i &lt; $max; $i++)
+                  <b>print</b> $result-&gt;fields[$i].' ';
+       $result-&gt;<b>MoveNext</b>();
+       <b>print</b> &quot;&lt;br&gt;\n&quot;;
+ &#125;</font> </pre>
+<p></p>
+<p>Now porting to Oracle is as simple as changing the second line to <code>NewADOConnection('oracle')</code>. 
+  Let's walk through the code...</p>
+<h3>Connecting to the Database</h3>
+<p></p>
+<pre><b><font color="#666600">include(&quot;adodb.inc.php&quot;);</font></b><font color="#666600">
+$db = <b>NewADOConnection</b>('mysql');
+$db-&gt;<b>Connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;mydb&quot;);</font></pre>
+<p>The connection code is a bit more sophisticated than MySQL's because our needs 
+  are more sophisticated. In ADODB, we use an object-oriented approach to managing 
+  the complexity of handling multiple databases. We have different classes to 
+  handle different databases. If you aren't familiar with object-oriented programing, 
+  don't worry -- the complexity is all hidden away in the<code> NewADOConnection()</code> 
+  function.</p>
+<p>To conserve memory, we only load the PHP code specific to the database you 
+  are connecting to. We do this by calling <code>NewADOConnection(databasedriver)</code>. 
+  Legal database drivers include <i>mysql, mssql, oracle, oci8, postgres, sybase, 
+  vfp, access, ibase </i>and many others.</p>
+<p>Then we create a new instance of the connection class by calling <code>NewADOConnection()</code>. 
+  Finally we connect to the database using <code>$db-&gt;Connect(). </code></p>
+<h3>Executing the SQL</h3>
+<p><code><font color="#663300">$result = $db-&gt;<b>Execute</b>(&quot;SELECT * 
+  FROM employees&quot;);<br>
+  if ($result === false) die(&quot;failed&quot;)</font></code><code><font color="#663300">;</font></code> 
+  <br>
+</p>
+<p>Sending the SQL statement to the server is straight forward. Execute() will 
+  return a recordset object on successful execution. You should check $result 
+  as we do above.
+<p>An issue that confuses beginners is the fact that we have two types of objects 
+  in ADODB, the connection object and the recordset object. When do we use each?
+<p>The connection object ($db) is responsible for connecting to the database, 
+  formatting your SQL and querying the database server. The recordset object ($result) 
+  is responsible for retrieving the results and formatting the reply as text or 
+  as an array.
+<p>The only thing I need to add is that ADODB provides several helper functions 
+  for making INSERT and UPDATE statements easier, which we will cover in the Advanced 
+  section. 
+<h3>Retrieving the Data<br>
+</h3>
+<pre><font color="#006666"><b>while</b> (!$result-&gt;EOF) &#123;
+   <b>for</b> ($i=0, $max=$result-&gt;<b>FieldCount</b>(); $i &lt; $max; $i++)
+          <b>print</b> $result-&gt;fields[$i].' ';
+   $result-&gt;<b>MoveNext</b>();
+   <b>print</b> &quot;&lt;br&gt;\n&quot;;
+&#125;</font></pre>
+<p>The paradigm for getting the data is that it's like reading a file. For every 
+  line, we check first whether we have reached the end-of-file (EOF). While not 
+  end-of-file, loop through each field in the row. Then move to the next line 
+  (MoveNext) and repeat. 
+<p>The <code>$result-&gt;fields[]</code> array is generated by the PHP database 
+  extension. Some database extensions do not index the array by field name. 
+  To force indexing by name - that is associative arrays - 
+  use the $ADODB_FETCH_MODE global variable. 
+<pre>
+       $<b>ADODB_FETCH_MODE</b> = ADODB_FETCH_NUM;
+       $rs1 = $db->Execute('select * from table');
+       $<b>ADODB_FETCH_MODE</b> = ADODB_FETCH_ASSOC;
+       $rs2 = $db->Execute('select * from table');
+       print_r($rs1->fields); // shows <i>array([0]=>'v0',[1] =>'v1')</i>
+       print_r($rs2->fields); // shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i>
+</pre>
+<p>
+As you can see in the above example, both recordsets store and use different fetch modes
+based on the $ADODB_FETCH_MODE setting when the recordset was created by Execute().</p>
+<h2>ADOConnection<a name="ADOConnection"></a></h2>
+<p>Object that performs the connection to the database, executes SQL statements 
+  and has a set of utility functions for standardising the format of SQL statements 
+  for issues such as concatenation and date formats.</p>
+  
+<h3>Other Useful Functions</h3>
+<p><code>$recordset-&gt;Move($pos)</code> scrolls to that particular row. ADODB supports forward 
+  scrolling for all databases. Some databases will not support backwards scrolling. 
+  This is normally not a problem as you can always cache records to simulate backwards 
+  scrolling. 
+<p><code>$recordset-&gt;RecordCount()</code> returns the number of records accessed by the 
+  SQL statement. Some databases will return -1 because it is not supported. 
+<p><code>$recordset-&gt;GetArray()</code> returns the result as an array. 
+<p><code>rs2html($recordset)</code> is a function that is generates a HTML table based on the 
+  $recordset passed to it. An example with the relevant lines in bold:
+<pre>   include('adodb.inc.php'); 
+   <b>include('tohtml.inc.php');</b> /* includes the rs2html function */
+   $conn = &amp;ADONewConnection('mysql'); 
+   $conn-&gt;PConnect('localhost','userid','password','database');
+   $rs = $conn-&gt;Execute('select * from table');
+  <b> rs2html($rs)</b>; /* recordset to html table */ </pre>
+<p>There are many other helper functions that are listed in the documentation available at <a href="http://php.weblogs.com/adodb_manual"></a><a href="http://php.weblogs.com/adodb_manual">http://php.weblogs.com/adodb_manual</a>. 
+<h2>Advanced Material</h2>
+<h3>Inserts and Updates </h3>
+<p>Let's say you want to insert the following data into a database. 
+<p><b>ID</b> = 3<br>
+  <b>TheDate</b>=mktime(0,0,0,8,31,2001) /* 31st August 2001 */<br>
+  <b>Note</b>= sugar why don't we call it off 
+<p>When you move to another database, your insert might no longer work.</p>
+<p>The first problem is that each database has a different default date format. 
+  MySQL expects YYYY-MM-DD format, while other databases have different defaults. 
+  ADODB has a function called DBDate() that addresses this issue by converting 
+  converting the date to the correct format.</p>
+<p>The next problem is that the <b>don't</b> in the Note needs to be quoted. In 
+  MySQL, we use <b>don\'t</b> but in some other databases (Sybase, Access, Microsoft 
+  SQL Server) we use <b>don''t. </b>The qstr() function addresses this issue.</p>
+<p>So how do we use the functions? Like this:</p>
+<pre>$sql = &quot;INSERT INTO table (id, thedate,note) values (&quot; 
+   . $<b>ID</b> . ','
+   . $db-&gt;DBDate($<b>TheDate</b>) .','
+   . $db-&gt;qstr($<b>Note</b>).&quot;)&quot;;
+$db-&gt;Execute($sql);</pre>
+<p>ADODB also supports <code>$connection-&gt;Affected_Rows()</code> (returns the 
+  number of rows affected by last update or delete) and <code>$recordset-&gt;Insert_ID()</code> 
+  (returns last autoincrement number generated by an insert statement). Be forewarned 
+  that not all databases support the two functions.<br>
+</p>
+<h3>MetaTypes</h3>
+<p>You can find out more information about each of the fields (I use the words 
+  fields and columns interchangebly) you are selecting by calling the recordset 
+  method <code>FetchField($fieldoffset)</code>. This will return an object with 
+  3 properties: name, type and max_length. 
+<pre>For example:</pre>
+<pre>$recordset = $conn-&gt;Execute(&quot;select adate from table&quot;);<br>$f0 = $recordset-&gt;FetchField(0);
+</pre>
+<p>Then <code>$f0-&gt;name</code> will hold <i>'adata'</i>, <code>$f0-&gt;type</code> 
+  will be set to '<i>date'</i>. If the max_length is unknown, it will be set to 
+  -1. 
+<p>One problem with handling different databases is that each database often calls 
+  the same type by a different name. For example a <i>timestamp</i> type is called 
+  <i>datetime</i> in one database and <i>time</i> in another. So ADODB has a special 
+  <code>MetaType($type, $max_length)</code> function that standardises the types 
+  to the following: 
+<p>C: character and varchar types<br>
+  X: text or long character (eg. more than 255 bytes wide).<br>
+  B: blob or binary image<br>
+  D: date<br>
+  T: timestamp<br>
+  L: logical (boolean)<br>
+  I: integer<br>
+  N: numeric (float, double, money) 
+<p>In the above date example, 
+<p><code>$recordset = $conn-&gt;Execute(&quot;select adate from table&quot;);<br>
+  $f0 = $recordset-&gt;FetchField(0);<br>
+  $type = $recordset-&gt;MetaType($f0-&gt;type, $f0-&gt;max_length);<br>
+  print $type; /* should print 'D'</code> */
+<p> 
+<p><b>Select Limit and Top Support</b> 
+<p>ADODB has a function called $connection->SelectLimit($sql,$nrows,$offset) that allows
+you to retrieve a subset of the recordset. This will take advantage of native
+SELECT TOP on Microsoft products and SELECT ... LIMIT with PostgreSQL and MySQL, and
+emulated if the database does not support it.
+<p><b>Caching Support</b> 
+<p>ADODB allows you to cache recordsets in your file system, and only requery the database
+server after a certain timeout period with $connection->CacheExecute($secs2cache,$sql) and 
+$connection->CacheSelectLimit($secs2cache,$sql,$nrows,$offset).
+<p><b>PHP4 Session Handler Support</b> 
+<p>ADODB also supports PHP4 session handlers. You can store your session variables 
+  in a database for true scalability using ADODB. For further information, visit 
+  <a href="http://php.weblogs.com/adodb-sessions"></a><a href="http://php.weblogs.com/adodb-sessions">http://php.weblogs.com/adodb-sessions</a>
+<h3>Commercial Use Encouraged</h3>
+<p>If you plan to write commercial PHP applications that you want to resell, you should consider ADODB. It has been released using the lesser GPL, which means you can legally include it in commercial applications, while keeping your code proprietary. Commercial use of ADODB is strongly encouraged! We are using it internally for this reason.<p>
+
+<h2>Conclusion</h2>
+<p>As a thank you for finishing this article, here are the complete lyrics for 
+  <i>let's call the whole thing off</i>.<br>
+  <br>
+<pre>
+   Refrain 
+<br>
+               You say eether and I say eyether, 
+               You say neether and I say nyther; 
+               Eether, eyether, neether, nyther - 
+               Let's call the whole thing off ! 
+<br>
+               You like potato and I like po-tah-to, 
+               You like tomato and I like to-mah-to; 
+               Potato, po-tah-to, tomato, to-mah-to - 
+               Let's call the whole thing off ! 
+<br>
+But oh, if we call the whole thing off, then we must part. 
+And oh, if we ever part, then that might break my heart. 
+<br>
+               So, if you like pajamas and I like pa-jah-mas, 
+               I'll wear pajamas and give up pa-jah-mas. 
+               For we know we 
+               Need each other, so we 
+               Better call the calling off off. 
+               Let's call the whole thing off ! 
+<br>
+   Second Refrain 
+<br>
+               You say laughter and I say lawfter, 
+               You say after and I say awfter; 
+               Laughter, lawfter, after, awfter - 
+               Let's call the whole thing off ! 
+<br>
+               You like vanilla and I like vanella, 
+               You, sa's'parilla and I sa's'parella; 
+               Vanilla, vanella, choc'late, strawb'ry - 
+               Let's call the whole thing off ! 
+<br>
+But oh, if we call the whole thing off, then we must part. 
+And oh, if we ever part, then that might break my heart. 
+<br>
+               So, if you go for oysters and I go for ersters, 
+               I'll order oysters and cancel the ersters. 
+               For we know we 
+               Need each other, so we 
+               Better call the calling off off. 
+               Let's call the whole thing off ! 
+  </pre>
+<p><font size=2>Song and lyrics by George and Ira Gershwin, introduced by Fred Astaire and Ginger Rogers
+in the film "Shall We Dance?"  </font><p>
+<p>
+(c)2001-2002 John Lim.
+
+</body>
+</html>
diff --git a/lib/adodb/xmlschema.dtd b/lib/adodb/xmlschema.dtd
new file mode 100644 (file)
index 0000000..083bc90
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<!DOCTYPE adodb_schema [
+<!ELEMENT schema (table*, sql*)>
+<!ATTLIST schema version CDATA #REQUIRED>
+<!ELEMENT table ((field+|DROP), constraint*, descr?, index*)>
+<!ELEMENT field ((NOTNULL|KEY|PRIMARY)?, (AUTO|AUTOINCREMENT)?, (DEFAULT|DEFDATE|DEFTIMESTAMP)?, NOQUOTE, constraint, descr?)>
+<!ELEMENT descr (#CDATA)>
+<!ELEMENT NOTNULL EMPTY>
+<!ELEMENT KEY EMPTY>
+<!ELEMENT PRIMARY EMPTY>
+<!ELEMENT AUTO EMPTY>
+<!ELEMENT AUTOINCREMENT EMPTY>
+<!ELEMENT DEFAULT EMPTY>
+<!ELEMENT DEFDATE EMPTY>
+<!ELEMENT DEFTIMESTAMP EMPTY>
+<!ELEMENT NOQUOTE EMPTY>
+<!ELEMENT DROP EMPTY>
+<!ELEMENT constraint (#CDATA)>
+<!ATTLIST table name CDATA #REQUIRED platform CDATA #IMPLIED version CDATA #IMPLIED>
+<!ATTLIST field name CDATA #REQUIRED type (C|C2|X|X2|B|D|T|L|I|F|N) #REQUIRED size CDATA #IMPLIED>
+<!ATTLIST DEFAULT value CDATA #REQUIRED>
+<!ELEMENT index ((col+|DROP), CLUSTERED?, BITMAP?, UNIQUE?, FULLTEXT?, HASH?, descr?)>
+<!ELEMENT col (#CDATA)>
+<!ELEMENT CLUSTERED EMPTY>
+<!ELEMENT BITMAP EMPTY>
+<!ELEMENT UNIQUE EMPTY>
+<!ELEMENT FULLTEXT EMPTY>
+<!ELEMENT HASH EMPTY>
+<!ATTLIST index name CDATA #REQUIRED>
+<!ELEMENT sql (query+, descr?)>
+<!ELEMENT query (#CDATA)>
+<!ATTLIST sql name CDATA #IMPLIED platform CDATA #IMPLIED, key CDATA, prefixmethod (AUTO|MANUAL|NONE) >
+] >
diff --git a/lib/adodb/xsl/convert-0.1-0.2.xsl b/lib/adodb/xsl/convert-0.1-0.2.xsl
new file mode 100644 (file)
index 0000000..8cd534f
--- /dev/null
@@ -0,0 +1,205 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version="1.0"
+       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+>
+       <xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="UTF-8"/>
+       
+       <!-- Schema -->
+       <xsl:template match="/">
+               <xsl:comment>
+ADODB XMLSchema
+http://adodb-xmlschema.sourceforge.net
+</xsl:comment>
+               
+               <xsl:element name="schema">
+                       <xsl:attribute name="version">0.2</xsl:attribute>
+                       
+                       <xsl:apply-templates select="schema/table|schema/sql"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Table -->
+       <xsl:template match="table">
+               <xsl:variable name="table_name" select="@name"/>
+               
+               <xsl:element name="table">
+                       <xsl:attribute name="name"><xsl:value-of select="$table_name"/></xsl:attribute>
+                       
+                       <xsl:if test="string-length(@platform) > 0">
+                               <xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:if test="string-length(@version) > 0">
+                               <xsl:attribute name="version"><xsl:value-of select="@version"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:apply-templates select="descr[1]"/>
+                       
+                       <xsl:choose>
+                               <xsl:when test="count(DROP) > 0">
+                                       <xsl:element name="DROP"/>
+                               </xsl:when>
+                               <xsl:otherwise>
+                                       <xsl:apply-templates select="field"/>
+                               </xsl:otherwise>
+                       </xsl:choose>
+                       
+                       <xsl:apply-templates select="constraint"/>
+                       
+                       <xsl:apply-templates select="../index[@table=$table_name]"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Field -->
+       <xsl:template match="field">
+               <xsl:element name="field">
+                       <xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+                       <xsl:attribute name="type"><xsl:value-of select="@type"/></xsl:attribute>
+                       
+                       <xsl:if test="string-length(@size) > 0">
+                               <xsl:attribute name="size"><xsl:value-of select="@size"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:choose>
+                               <xsl:when test="count(PRIMARY) > 0">
+                                       <xsl:element name="PRIMARY"/>
+                               </xsl:when>
+                               <xsl:when test="count(KEY) > 0">
+                                       <xsl:element name="KEY"/>
+                               </xsl:when>
+                               <xsl:when test="count(NOTNULL) > 0">
+                                       <xsl:element name="NOTNULL"/>
+                               </xsl:when>
+                       </xsl:choose>
+                       
+                       <xsl:choose>
+                               <xsl:when test="count(AUTO) > 0">
+                                       <xsl:element name="AUTO"/>
+                               </xsl:when>
+                               <xsl:when test="count(AUTOINCREMENT) > 0">
+                                       <xsl:element name="AUTOINCREMENT"/>
+                               </xsl:when>
+                       </xsl:choose>
+                       
+                       <xsl:choose>
+                               <xsl:when test="count(DEFAULT) > 0">
+                                       <xsl:element name="DEFAULT">
+                                               <xsl:attribute name="value">
+                                                       <xsl:value-of select="DEFAULT[1]/@value"/>
+                                               </xsl:attribute>
+                                       </xsl:element>
+                               </xsl:when>
+                               <xsl:when test="count(DEFDATE) > 0">
+                                       <xsl:element name="DEFDATE">
+                                               <xsl:attribute name="value">
+                                                       <xsl:value-of select="DEFDATE[1]/@value"/>
+                                               </xsl:attribute>
+                                       </xsl:element>
+                               </xsl:when>
+                               <xsl:when test="count(DEFTIMESTAMP) > 0">
+                                       <xsl:element name="DEFDTIMESTAMP">
+                                               <xsl:attribute name="value">
+                                                       <xsl:value-of select="DEFTIMESTAMP[1]/@value"/>
+                                               </xsl:attribute>
+                                       </xsl:element>
+                               </xsl:when>
+                       </xsl:choose>
+                       
+                       <xsl:if test="count(NOQUOTE) > 0">
+                               <xsl:element name="NOQUOTE"/>
+                       </xsl:if>
+                       
+                       <xsl:apply-templates select="constraint"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Constraint -->
+       <xsl:template match="constraint">
+               <xsl:element name="constraint">
+                       <xsl:value-of select="normalize-space(text())"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Index -->
+       <xsl:template match="index">
+               <xsl:element name="index">
+                       <xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+                       
+                       <xsl:apply-templates select="descr[1]"/>
+                       
+                       <xsl:if test="count(CLUSTERED) > 0">
+                               <xsl:element name="CLUSTERED"/>
+                       </xsl:if>
+                       
+                       <xsl:if test="count(BITMAP) > 0">
+                               <xsl:element name="BITMAP"/>
+                       </xsl:if>
+                       
+                       <xsl:if test="count(UNIQUE) > 0">
+                               <xsl:element name="UNIQUE"/>
+                       </xsl:if>
+                       
+                       <xsl:if test="count(FULLTEXT) > 0">
+                               <xsl:element name="FULLTEXT"/>
+                       </xsl:if>
+                       
+                       <xsl:if test="count(HASH) > 0">
+                               <xsl:element name="HASH"/>
+                       </xsl:if>
+                       
+                       <xsl:choose>
+                               <xsl:when test="count(DROP) > 0">
+                                       <xsl:element name="DROP"/>
+                               </xsl:when>
+                               <xsl:otherwise>
+                                       <xsl:apply-templates select="col"/>
+                               </xsl:otherwise>
+                       </xsl:choose>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Index Column -->
+       <xsl:template match="col">
+               <xsl:element name="col">
+                       <xsl:value-of select="normalize-space(text())"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- SQL QuerySet -->
+       <xsl:template match="sql">
+               <xsl:element name="sql">
+                       <xsl:if test="string-length(@platform) > 0">
+                               <xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:if test="string-length(@key) > 0">
+                               <xsl:attribute name="key"><xsl:value-of select="@key"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:if test="string-length(@prefixmethod) > 0">
+                               <xsl:attribute name="prefixmethod"><xsl:value-of select="@prefixmethod"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:apply-templates select="descr[1]"/>
+                       <xsl:apply-templates select="query"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Query -->
+       <xsl:template match="query">
+               <xsl:element name="query">
+                       <xsl:if test="string-length(@platform) > 0">
+                               <xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:value-of select="normalize-space(text())"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Description -->
+       <xsl:template match="descr">
+               <xsl:element name="descr">
+                       <xsl:value-of select="normalize-space(text())"/>
+               </xsl:element>
+       </xsl:template>
+</xsl:stylesheet>
\ No newline at end of file
diff --git a/lib/adodb/xsl/convert-0.2-0.1.xsl b/lib/adodb/xsl/convert-0.2-0.1.xsl
new file mode 100644 (file)
index 0000000..61841b4
--- /dev/null
@@ -0,0 +1,207 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet version="1.0"
+       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+>
+       <xsl:output method="xml" indent="yes" omit-xml-declaration="no" encoding="UTF-8"/>
+       
+       <!-- Schema -->
+       <xsl:template match="/">
+               <xsl:comment>
+ADODB XMLSchema
+http://adodb-xmlschema.sourceforge.net
+</xsl:comment>
+               
+               <xsl:element name="schema">
+                       <xsl:attribute name="version">0.1</xsl:attribute>
+                       
+                       <xsl:apply-templates select="schema/table|schema/sql"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Table -->
+       <xsl:template match="table">
+               <xsl:variable name="table_name" select="@name"/>
+               
+               <xsl:element name="table">
+                       <xsl:attribute name="name"><xsl:value-of select="$table_name"/></xsl:attribute>
+                       
+                       <xsl:if test="string-length(@platform) > 0">
+                               <xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:if test="string-length(@version) > 0">
+                               <xsl:attribute name="version"><xsl:value-of select="@version"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:apply-templates select="descr[1]"/>
+                       
+                       <xsl:choose>
+                               <xsl:when test="count(DROP) > 0">
+                                       <xsl:element name="DROP"/>
+                               </xsl:when>
+                               <xsl:otherwise>
+                                       <xsl:apply-templates select="field"/>
+                               </xsl:otherwise>
+                       </xsl:choose>
+                       
+                       <xsl:apply-templates select="constraint"/>
+                       
+               </xsl:element>
+               
+               <xsl:apply-templates select="index"/>
+       </xsl:template>
+       
+       <!-- Field -->
+       <xsl:template match="field">
+               <xsl:element name="field">
+                       <xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+                       <xsl:attribute name="type"><xsl:value-of select="@type"/></xsl:attribute>
+                       
+                       <xsl:if test="string-length(@size) > 0">
+                               <xsl:attribute name="size"><xsl:value-of select="@size"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:choose>
+                               <xsl:when test="count(PRIMARY) > 0">
+                                       <xsl:element name="PRIMARY"/>
+                               </xsl:when>
+                               <xsl:when test="count(KEY) > 0">
+                                       <xsl:element name="KEY"/>
+                               </xsl:when>
+                               <xsl:when test="count(NOTNULL) > 0">
+                                       <xsl:element name="NOTNULL"/>
+                               </xsl:when>
+                       </xsl:choose>
+                       
+                       <xsl:choose>
+                               <xsl:when test="count(AUTO) > 0">
+                                       <xsl:element name="AUTO"/>
+                               </xsl:when>
+                               <xsl:when test="count(AUTOINCREMENT) > 0">
+                                       <xsl:element name="AUTOINCREMENT"/>
+                               </xsl:when>
+                       </xsl:choose>
+                       
+                       <xsl:choose>
+                               <xsl:when test="count(DEFAULT) > 0">
+                                       <xsl:element name="DEFAULT">
+                                               <xsl:attribute name="value">
+                                                       <xsl:value-of select="DEFAULT[1]/@value"/>
+                                               </xsl:attribute>
+                                       </xsl:element>
+                               </xsl:when>
+                               <xsl:when test="count(DEFDATE) > 0">
+                                       <xsl:element name="DEFDATE">
+                                               <xsl:attribute name="value">
+                                                       <xsl:value-of select="DEFDATE[1]/@value"/>
+                                               </xsl:attribute>
+                                       </xsl:element>
+                               </xsl:when>
+                               <xsl:when test="count(DEFTIMESTAMP) > 0">
+                                       <xsl:element name="DEFDTIMESTAMP">
+                                               <xsl:attribute name="value">
+                                                       <xsl:value-of select="DEFTIMESTAMP[1]/@value"/>
+                                               </xsl:attribute>
+                                       </xsl:element>
+                               </xsl:when>
+                       </xsl:choose>
+                       
+                       <xsl:if test="count(NOQUOTE) > 0">
+                               <xsl:element name="NOQUOTE"/>
+                       </xsl:if>
+                       
+                       <xsl:apply-templates select="constraint"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Constraint -->
+       <xsl:template match="constraint">
+               <xsl:element name="constraint">
+                       <xsl:value-of select="normalize-space(text())"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Index -->
+       <xsl:template match="index">
+               <xsl:element name="index">
+                       <xsl:attribute name="name"><xsl:value-of select="@name"/></xsl:attribute>
+                       <xsl:attribute name="table"><xsl:value-of select="../@name"/></xsl:attribute>
+                       
+                       <xsl:apply-templates select="descr[1]"/>
+                       
+                       <xsl:if test="count(CLUSTERED) > 0">
+                               <xsl:element name="CLUSTERED"/>
+                       </xsl:if>
+                       
+                       <xsl:if test="count(BITMAP) > 0">
+                               <xsl:element name="BITMAP"/>
+                       </xsl:if>
+                       
+                       <xsl:if test="count(UNIQUE) > 0">
+                               <xsl:element name="UNIQUE"/>
+                       </xsl:if>
+                       
+                       <xsl:if test="count(FULLTEXT) > 0">
+                               <xsl:element name="FULLTEXT"/>
+                       </xsl:if>
+                       
+                       <xsl:if test="count(HASH) > 0">
+                               <xsl:element name="HASH"/>
+                       </xsl:if>
+                       
+                       <xsl:choose>
+                               <xsl:when test="count(DROP) > 0">
+                                       <xsl:element name="DROP"/>
+                               </xsl:when>
+                               <xsl:otherwise>
+                                       <xsl:apply-templates select="col"/>
+                               </xsl:otherwise>
+                       </xsl:choose>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Index Column -->
+       <xsl:template match="col">
+               <xsl:element name="col">
+                       <xsl:value-of select="normalize-space(text())"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- SQL QuerySet -->
+       <xsl:template match="sql">
+               <xsl:element name="sql">
+                       <xsl:if test="string-length(@platform) > 0">
+                               <xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:if test="string-length(@key) > 0">
+                               <xsl:attribute name="key"><xsl:value-of select="@key"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:if test="string-length(@prefixmethod) > 0">
+                               <xsl:attribute name="prefixmethod"><xsl:value-of select="@prefixmethod"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:apply-templates select="descr[1]"/>
+                       <xsl:apply-templates select="query"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Query -->
+       <xsl:template match="query">
+               <xsl:element name="query">
+                       <xsl:if test="string-length(@platform) > 0">
+                               <xsl:attribute name="platform"><xsl:value-of select="@platform"/></xsl:attribute>
+                       </xsl:if>
+                       
+                       <xsl:value-of select="normalize-space(text())"/>
+               </xsl:element>
+       </xsl:template>
+       
+       <!-- Description -->
+       <xsl:template match="descr">
+               <xsl:element name="descr">
+                       <xsl:value-of select="normalize-space(text())"/>
+               </xsl:element>
+       </xsl:template>
+</xsl:stylesheet>
\ No newline at end of file