adodb 최신버전으로 변경

<? 를 <?php 로 변경
This commit is contained in:
2018-01-11 19:28:35 +09:00
parent feff33715f
commit 7b3b674dee
450 changed files with 19425 additions and 32248 deletions
+17
View File
@@ -0,0 +1,17 @@
# ADOdb Documentation
ADOdb documentation is available in the following locations
- [Online](http://adodb.org/)
- [Download](https://sourceforge.net/projects/adodb/files/Documentation/) for offline use
## Legacy documentation
The old HTML files are available in
[GitHub](https://github.com/ADOdb/ADOdb/tree/8b8133771ecbe9c95e57abbe5dc3757f0226bfcd/docs),
or in the release zip/tarballs for version 5.20 and before on
[Sourceforge](https://sourceforge.net/projects/adodb/files/adodb-php5-only/).
## Changelog
The full historical [Changelog](changelog.md) is available on GitHub.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

+491
View File
@@ -0,0 +1,491 @@
# ADOdb Changelog - v5.x
Older changelogs:
[v4.x](changelog_v4.x.md),
[v3.x](changelog_v3.x.md),
[v2.x](changelog_v2.x.md).
## 5.20.9 - 21-Dec-2016
- mssql: fix syntax error in version matching regex #305
## 5.20.8 - 17-Dec-2016
- mssql: support MSSQL Server 2016 and later #294
- mssql: fix Find() returning no results. #298
- mssql: fix Sequence name forced to 'adodbseq'. #295, #300
- mssql: fix GenId() not returning next sequence value with SQL Server 2005/2008. #302
- mssql: fix drop/alter column with existing default constraint. #290
- mssql: fix PHP notice in MetaColumns(). #289
- oci8po: fix inconsistent variable binding in SelectLimit() #288
- oci8po: fix SelectLimit() with prepared statements #282
## 5.20.7 - 20-Sep-2016
- security: Fix SQL injection in PDO drivers qstr() method (CVE-2016-7405). #226
- oci8po: prevent segfault on PHP 7. #259
- pdo/mysql: Fix MetaTables() method. #275
## 5.20.6 - 31-Aug-2016
- security: Fix XSS vulnerability in old test script (CVE-2016-4855). #274
- adodb: Exit with error/exception when the ADOdb Extension is loaded. #269
- adodb: Fix truncated exception messages. #273
## 5.20.5 - 10-Aug-2016
- adodb: Fix fatal error when connecting with missing extension. #254
- adodb: Fix _adodb_getcount(). #236
- mssql: Destructor fails if recordset already closed. #268
- mssql: Use SQL server native data types if available. #234
- mysqli: Fix PHP notice in _close() method. #240
- pdo: Let driver handle SelectDB() and SQLDate() calls. #242
- xml: Fix PHP strict warning. #260
- xml: remove calls to 'unset($this)' (PHP 7.1 compatibility). #257
## 5.20.4 - 31-Mar-2016
- adodb: Fix BulkBind() param count validation. #199
- mysqli: fix PHP warning in recordset destructor. #217
- mysqli: cast port number to int when connecting (PHP7 compatibility). #218
## 5.20.3 - 01-Jan-2016
- mssql: PHP warning when closing recordset from destructor not fixed in v5.20.2. #180
## 5.20.2 - 27-Dec-2015
- adodb: Remove a couple leftover PHP 4.x constructors (PHP7 compatibility). #139
- db2ora: Remove deprecated preg_replace '/e' flag (PHP7 compatibility). #168
- mysql: MoveNext() now respects ADODB_ASSOC_CASE. #167
- mssql, mysql, informix: Avoid PHP warning when closing recordset from destructor. #170
## 5.20.1 - 06-Dec-2015
- adodb: Fix regression introduced in 5.20.0, causing a PHP Warning when
calling GetAssoc() on an empty recordset. See Github #162
- ADOConnection::Version() now handles SemVer. See Github #164
## 5.20.0 - 28-Nov-2015
- adodb: Fix regression introduced in v5.19, causing queries to return empty rows. See Github #20, #93, #95
- adodb: Fix regression introduced in v5.19 in GetAssoc() with ADODB_FETCH_ASSOC mode and '0' as data. See Github #102
- adodb: AutoExecute correctly handles empty result set in case of updates. See Github #13
- adodb: Fix regex in Version(). See Github #16
- adodb: Align method signatures to definition in parent class ADODB_DataDict. See Github #31
- adodb: Improve compatibility of ADORecordSet_empty, thanks to Sjan Evardsson. See Github #43
- adodb: fix ADODB_Session::open() failing after successful ADONewConnection() call, thanks to Sjan Evardsson. See Github #44
- adodb: Only include memcache library once for PHPUnit 4.x, thanks to Alan Farquharson. See Github #74
- adodb: Move() returns false when given row is < 0, thanks to Mike Benoit.
- adodb: Add support for pagination with complex queries, thanks to Mike Benoit. See Github #88
- adodb: Parse port out of hostname if specified in connection parameters, thanks to Andy Theuninck. See Github #63
- adodb: Fix inability to set values from 0 to null (and vice versa) with Active Record, thanks to Louis Johnson. See Github #71
- adodb: Fix PHP strict warning in ADODB_Active_Record::Reload(), thanks to Boštjan Žokš. See Github #75
- adodb: Add mssql's DATETIME2 type to ADOConnection::MetaType(), thanks to MarcelTO. See Github #80
- adodb: When flushing cache, initialize it if it is not set, thanks to Paul Haggart. See Github #57
- adodb: Define DB_AUTOQUERY_* constants in main include file. See Github #49
- adodb: Improve documentation of fetch mode and assoc case
- adodb: Improve logic to build the assoc case bind array
- adodb: Strict-standards compliance for function names. See Github #18, #142
- adodb: Remove old PHP 4.x constructors for compatibility with PHP 7. See Github #139
- adodb: Initialize charset in ADOConnection::SetCharSet. See Github #39
- adodb: Fix incorrect handling of input array in Execute(). See Github #146
- adodb: Release Recordset when raising exception. See Github #143
- adodb: Added new setConnectionParameter() method, currently implemented in mssqlnative driver only. See Github #158.
- adodb-lib: Optimize query pagination, thanks to Mike Benoit. See Github #110
- memcache: use include_once() to avoid issues with PHPUnit. See http://phplens.com/lens/lensforum/msgs.php?id=19489
- mssql_n: Allow use of prepared statements with driver. See Github #22
- mssqlnative: Use ADOConnection::outp instead of error_log. See Github #12
- mssqlnative: fix failure on Insert_ID() if the insert statement contains a semicolon in a value string, thanks to sketule. See Github #96
- mssqlnative: Fix "invalid parameter was passed to sqlsrv_configure" error, thanks to Ray Morris. See Github #103
- mssqlnative: Fix insert_ID() failing if server returns more than 1 row, thanks to gitjti. See Github #41
- mysql: prevent race conditions when creating/dropping sequences, thanks to MikeB. See Github #28
- mysql: Fix adodb_strip_order_by() bug causing SQL error for subqueries with order/limit clause, thanks to MikeB.
- mysql: workaround for HHVM behavior, thanks to Mike Benoit.
- mysqli: Fix qstr() when called without an active connection. See Github #11
- oci8: Fix broken quoting of table name in AddColumnSQL and AlterColumnSQL, thanks to Andreas Fernandez. see Github #67
- oci8: Allow oci8 driver to use lowercase field names in assoc mode. See Github #21
- oci8po: Prevent replacement of '?' within strings, thanks to Mark Newnham. See Github #132
- pdo: Added missing property (fixes PHP notices). see Github #56
- pdo: Align method signatures with parent class, thanks to Andy Theuninck. see Github #62
- pdo: new sqlsrv driver, thanks to MarcelTO. See Github #81
- pdo/mysql: New methods to make the driver behave more like mysql/mysqli, thanks to Andy Theuninck. see Github #40
- postgres: Stop using legacy function aliases
- postgres: Fix AlterColumnSQL when updating multiple columns, thanks to Jouni Ahto. See Github #72
- postgres: Fix support for HHVM 3.6, thanks to Mike Benoit. See Github #87
- postgres: Noblob optimization, thanks to Mike Benoit. See Github #112
- postgres7: fix system warning in MetaColumns() with schema. See http://phplens.com/lens/lensforum/msgs.php?id=19481
- sqlite3: ServerInfo() now returns driver's version
- sqlite3: Fix wrong connection parameter in _connect(), thanks to diogotoscano. See Github #51
- sqlite3: Fix FetchField, thanks to diogotoscano. See Github #53
- sqlite3: Fix result-less SQL statements executed twice. See Github #99
- sqlite3: use -1 for _numOfRows. See Github #151
- xmlschema: Fix ExtractSchema() when given $prefix and $stripprefix parameters, thanks to peterdd. See Github #92
- Convert languages files to UTF-8, thanks to Marc-Etienne Vargenau. See Github #32.
## 5.19 - 23-Apr-2014
**NOTE:**
This release suffers from a [known issue with Associative Fetch Mode](https://github.com/ADOdb/ADOdb/issues/20)
(i.e. when $ADODB_FETCH_MODE is set to ADODB_FETCH_ASSOC).
It causes recordsets to return empty strings (no data) when using some database drivers.
The problem has been reported on MSSQL, Interbase and Foxpro, but possibly affects
other database types as well; all drivers derived from the above are also impacted.
- adodb: GetRowAssoc will return null as required. See http://phplens.com/lens/lensforum/msgs.php?id=19289
- adodb: Fix GetRowAssoc bug introduced in 5.17, causing function to return data from previous fetch for NULL fields. See http://phplens.com/lens/lensforum/msgs.php?id=17539
- adodb: GetAssoc will return a zero-based array when 2nd column is null. See https://sourceforge.net/p/adodb/bugs/130/
- adodb: Execute no longer ignores single parameters evaluating to false. See https://sourceforge.net/p/adodb/patches/32/
- adodb: Fix LIMIT 1 clause in subquery gets stripped off. See http://phplens.com/lens/lensforum/msgs.php?id=17813
- adodb-lib: Fix columns quoting bug. See https://sourceforge.net/p/adodb/bugs/127/
- Added new ADODB_ASSOC_CASE_* constants. Thx to Damien Regad.
- sessions: changed lob handling to detect all variations of oci8 driver.
- ads: clear fields before fetching. See http://phplens.com/lens/lensforum/msgs.php?id=17539
- mssqlnative: fixed many FetchField compat issues. See http://phplens.com/lens/lensforum/msgs.php?id=18464. Also date format changed to remove timezone.
- mssqlnative: Numerous fixes and improvements by Mark Newnham
- Driver supports SQL Server 2005, 2008 and 2012
- Bigint data types mapped to I8 instead of I
- Reintroduced MetaColumns function
- On SQL Server 2012, makes use of new CREATE SEQUENCE statement
- FetchField caches metadata at initialization to improve performance
- etc.
- mssqlnative: Fix Insert ID on prepared statement, thanks to Mike Parks. See http://phplens.com/lens/lensforum/msgs.php?id=19079
- mssql: timestamp format changed to `Y-m-d\TH:i:s` (ISO 8601) to make them independent from DATEFORMAT setting, as recommended on
[Microsoft TechNet](http://technet.microsoft.com/en-us/library/ms180878%28v=sql.105%29.aspx#StringLiteralDateandTimeFormats).
- mysql/mysqli: Fix ability for MetaTables to filter by table name, broken since 5.15. See http://phplens.com/lens/lensforum/msgs.php?id=19359
- odbc: Fixed MetaTables and MetaPrimaryKeys definitions in odbc driver to match adoconnection class.
- odbc: clear fields before fetching. See http://phplens.com/lens/lensforum/msgs.php?id=17539
- oci8: GetRowAssoc now works in ADODB_FETCH_ASSOC fetch mode
- oci8: MetaType and MetaForeignKeys argument count are now strict-standards compliant
- oci8: Added trailing `;` on trigger creation for sequence fields, prevents occurence of ORA-24344
- oci8quercus: new oci8 driver with support for quercus jdbc data types.
- pdo: Fixed concat recursion bug in 5.3. See http://phplens.com/lens/lensforum/msgs.php?id=19285
- pgsql: Default driver (postgres/pgsql) is now postgres8
- pgsql: Fix output of BLOB (bytea) columns with PostgreSQL >= 9.0
- pgsql: Fix handling of DEFAULT NULL columns in AlterColumnSQL
- pgsql: Fix mapping of error message to ADOdb error codes
- pgsql: Reset parameter number in Param() method when $name == false
- postgres8: New class/type with correct behavior for _insertid(). See Github #8
- postgres9: Fixed assoc problem. See http://phplens.com/lens/lensforum/msgs.php?id=19296
- sybase: Removed redundant sybase_connect() call in _connect(). See Github #3
- sybase: Allow connection on custom port. See Github #9
- sybase: Fix null values returned with ASSOC fetch mode. See Github #10
- Added Composer support. See Github #7
## 5.18 - 3 Sep 2012
- datadict-postgres: Fixes bug in ALTER COL. See http://phplens.com/lens/lensforum/msgs.php?id=19202.
- datadict-postgres: fixed bugs in MetaType() checking $fieldobj properties.
- GetRowAssoc did not work with null values. Bug in 5.17.
- postgres9: New driver to better support PostgreSQL 9. Thx Glenn Herteg and Cacti team.
- sqlite3: Modified to support php 5.4. Thx Günter Weber [built.development#googlemail.com]
- adodb: When fetch mode is ADODB_FETCH_ASSOC, and we execute `$db->GetAssoc("select 'a','0'");` we get an error. Fixed. See http://phplens.com/lens/lensforum/msgs.php?id=19190
- adodb: Caching directory permissions now configurable using global variable $ADODB_CACHE_PERMS. Default value is 0771.
- mysqli: SetCharSet() did not return true (success) or false (fail) correctly. Fixed.
- mysqli: changed dataProvider to 'mysql' so that MetaError and other shared functions will work.
- mssqlnative: Prepare() did not work previously. Now calling Prepare() will work but the sql is not actually compiled. Unfortunately bind params are passed to sqlsrv_prepare and not to sqlsrv_execute. make Prepare() and empty function, and we still execute the unprepared stmt.
- mysql: FetchField(-1), turns it is is not possible to retrieve the max_length. Set to -1.
- mysql-perf: Fixed "SHOW INNODB STATUS". Change to "SHOW ENGINE INNODB STATUS"
## 5.17 - 18 May 2012
- Active Record: Removed trailing whitespace from adodb-active-record.inc.php.
- odbc: Added support for $database parameter in odbc Connect() function. E.g. $DB->Connect($dsn_without_db, $user, $pwd, $database).
Previously $database had to be left blank and the $dsn was used to pass in this parameter.
- oci8: Added better empty($rs) error handling to metaindexes().
- oci8: Changed to use newer oci API to support PHP 5.4.
- adodb.inc.php: Changed GetRowAssoc to more generic code that will work in all scenarios.
## 5.16 - 26 March 2012
- mysqli: extra mysqli_next_result() in close() removed. See http://phplens.com/lens/lensforum/msgs.php?id=19100
- datadict-oci8: minor typo in create sequence trigger fixed. See http://phplens.com/lens/lensforum/msgs.php?id=18879.
- security: safe date parsing changes. Does not impact security, these are code optimisations. Thx Saithis.
- postgres, oci8, oci8po, db2oci: Param() function parameters inconsistent with base class. $type='C' missing. Fixed.
- active-record: locked bug fixed. http://phplens.com/lens/lensforum/msgs.php?phplens_forummsg=new&id=19073
- mysql, mysqli and informix: added MetaProcedures. Metaprocedures allows to retrieve an array list of all procedures in database. http://phplens.com/lens/lensforum/msgs.php?id=18414
- Postgres7: added support for serial data type in MetaColumns().
## 5.15 - 19 Jan 2012
- pdo: fix ErrorMsg() to detect errors correctly. Thx Jens.
- mssqlnative: added another check for $this->fields array exists.
- mssqlnative: bugs in FetchField() fixed. See http://phplens.com/lens/lensforum/msgs.php?id=19024
- DBDate and DBTimeStamp had sql injection bug. Fixed. Thx Saithis
- mysql and mysqli: MetaTables() now identifies views and tables correctly.
- Added function adodb_time() to adodb-time.inc.php. Generates current time in unsigned integer format.
## 5.14 - 8 Sep 2011
- mysqli: fix php compilation bug.
- postgres: bind variables did not work properly. Fixed.
- postgres: blob handling bug in _decode. Fixed.
- ActiveRecord: if a null field was never updated, activerecord would still update the record. Fixed.
- ActiveRecord: 1 char length string never quoted. Fixed.
- LDAP: Connection string ldap:// and ldaps:// did not work. Fixed.
## 5.13 - 15 Aug 2011
- Postgres: Fix in 5.12 was wrong. Uses pg_unescape_bytea() correctly now in _decode.
- GetInsertSQL/GetUpdateSQL: Now $ADODB_QUOTE_FIELDNAMES allows you to define 'NATIVE', 'UPPER', 'LOWER'. If set to true, will default to 'UPPER'.
- mysqli: added support for persistent connections 'p:'.
- mssqlnative: ADODB_FETCH_BOTH did not work properly. Fixed.
- mssqlnative: return values for stored procedures where not returned! Fixed. See http://phplens.com/lens/lensforum/msgs.php?id=18919
- mssqlnative: timestamp and fetchfield bugs fixed. http ://phplens.com/lens/lensforum/msgs.php?id=18453
## 5.12 - 30 June 2011
- Postgres: Added information_schema support for postgresql.
- Postgres: Use pg_unescape_bytea() in _decode.
- Fix bulk binding with oci8. http://phplens.com/lens/lensforum/msgs.php?id=18786
- oci8 perf: added wait evt monitoring. Also db cache advice now handles multiple buffer pools properly.
- sessions2: Fixed setFetchMode problem.
- sqlite: Some DSN connection settings were not parsed correctly.
- mysqli: now GetOne obeys $ADODB_GETONE_EOF;
- memcache: compress option did not work. Fixed. See http://phplens.com/lens/lensforum/msgs.php?id=18899
## 5.11 - 5 May 2010
- mysql: Fixed GetOne() to return null if no records returned.
- oci8 perf: added stats on sga, rman, memory usage, and flash in performance tab.
- odbtp: Now you can define password in $password field of Connect()/PConnect(), and it will add it to DSN.
- Datadict: altering columns did not consider the scale of the column. Now it does.
- mssql: Fixed problem with ADODB_CASE_ASSOC causing multiple versions of column name appearing in recordset fields.
- oci8: Added missing & to refLob.
- oci8: Added obj->scale to FetchField().
- oci8: Now you can get column info of a table in a different schema, e.g. MetaColumns("schema.table") is supported.
- odbc_mssql: Fixed missing $metaDatabasesSQL.
- xmlschema: Changed declaration of create() to create($xmls) to fix compat problems. Also changed constructor adoSchema() to pass in variable instead of variable reference.
- ado5: Fixed ado5 exceptions to only display errors when $this->debug=true;
- Added DSN support to sessions2.inc.php.
- adodb-lib.inc.php. Fixed issue with _adodb_getcount() not using $secs2cache parameter.
- adodb active record. Fixed caching bug. See http://phplens.com/lens/lensforum/msgs.php?id=18288.
- db2: fixed ServerInfo().
- adodb_date: Added support for format 'e' for TZ as in adodb_date('e')
- Active Record: If you have a field which is a string field (with numbers in) and you add preceding 0's to it the adodb library does not pick up the fact that the field has changed because of the way php's == works (dodgily). The end result is that it never gets updated into the database - fix by Matthew Forrester (MediaEquals). [matthew.forrester#mediaequals.com]
- Fixes RowLock() and MetaIndexes() inconsistencies. See http://phplens.com/lens/lensforum/msgs.php?id=18236
- Active record support for postgrseql boolean. See http://phplens.com/lens/lensforum/msgs.php?id=18246
- By default, Execute 2D array is disabled for security reasons. Set $conn->bulkBind = true to enable. See http://phplens.com/lens/lensforum/msgs.php?id=18270. Note this breaks backward compat.
- MSSQL: fixes for 5.2 compat. http://phplens.com/lens/lensforum/msgs.php?id=18325
- Changed Version() to return a string instead of a float so it correctly returns 5.10 instead of 5.1.
## 5.10 - 10 Nov 2009
- Fixed memcache to properly support $rs->timeCreated.
- adodb-ado.inc.php: Added BigInt support for PHP5. Will return float instead to support large numbers. Thx nasb#mail.goo.ne.jp.
- adodb-mysqli.inc.php: mysqli_multi_query is now turned off by default. To turn it on, use $conn->multiQuery = true; This is because of the risks of sql injection. See http://phplens.com/lens/lensforum/msgs.php?id=18144
- New db2oci driver for db2 9.7 when using PL/SQL mode. Allows oracle style :0, :1, :2 bind parameters which are remapped to ? ? ?.
- adodb-db2.inc.php: fixed bugs in MetaTables. SYS owner field not checked properly. Also in $conn->Connect($dsn, null, null, $schema) and PConnect($dsn, null, null, $schema), we do a SET SCHEMA=$schema if successful connection.
- adodb-mysqli.inc.php: Now $rs->Close() closes all pending next resultsets. Thx Clifton mesmackgod#gmail.com
- Moved _CreateCache() from PConnect()/Connect() to CacheExecute(). Suggested by Dumka.
- Many bug fixes to adodb-pdo_sqlite.inc.php and new datadict-sqlite.inc.php. Thx Andrei B. [andreutz#mymail.ro]
- Removed usage of split (deprecated in php 5.3). Thx david#horizon-nigh.org.
- Fixed RowLock() parameters to comply with PHP5 strict mode in multiple drivers.
## 5.09 - 25 June 2009
- Active Record: You can force column names to be quoted in INSERT and UPDATE statements, typically because you are using reserved words as column names by setting ADODB_Active_Record::$_quoteNames = true;
- Added memcache and cachesecs to DSN. e.g.
``` php
# we have a memcache servers mem1,mem2 on port 8888, compression=off and cachesecs=120
$dsn = 'mysql://user:pwd@localhost/mydb?memcache=mem1,mem2:8888:0&cachesecs=120';
```
- Fixed up MetaColumns and MetaPrimaryIndexes() for php 5.3 compat. Thx http://adodb.pastebin.com/m52082b16
- The postgresql driver's OffsetDate() apparently does not work with postgres 8.3. Fixed.
- Added support for magic_quotes_sybase in qstr() and addq(). Thanks Eloy and Sam Moffat.
- The oci8 driver did not handle LOBs properly when binding. Fixed. See http://phplens.com/lens/lensforum/msgs.php?id=17991.
- Datadict: In order to support TIMESTAMP with subsecond accuracy, added to datadict the new TS type. Supported by mssql, postgresql and oci8 (oracle). Also changed oci8 $conn->sysTimeStamp to use 'SYSTIMESTAMP' instead of 'SYSDATE'. Should be backwards compat.
- Added support for PHP 5.1+ DateTime objects in DBDate and DBTimeStamp. This means that dates and timestamps will be managed by DateTime objects if you are running PHP 5.1+.
- Added new property to postgres64 driver to support returning I if type is unique int called $db->uniqueIisR, defaulting to true. See http://phplens.com/lens/lensforum/msgs.php?id=17963
- Added support for bindarray in adodb_GetActiveRecordsClass with SelectLimit in adodb-active-record.inc.php.
- Transactions now allowed in ado_access driver. Thx to petar.petrov.georgiev#gmail.com.
- Sessions2 garbage collection is now much more robust. We perform ORDER BY to prevent deadlock in adodb-sessions2.inc.php.
- Fixed typo in pdo_sqlite driver.
## 5.08a - 17 Apr 2009
- Fixes wrong version number string.
- Incorrect + in adodb-datadict.inc.php removed.
- Fixes missing OffsetDate() function in pdo. Thx paul#mantisforge.org.
## 5.08 - 17 Apr 2009
- adodb-sybase.inc.php driver. Added $conn->charSet support. Thx Luis Henrique Mulinari (luis.mulinari#gmail.com)
- adodb-ado5.inc.php. Fixed some bind param issues. Thx Jirka Novak.
- adodb-ado5.inc.php. Now has improved error handling.
- Fixed typo in adodb-xmlschema03.inc.php. See XMLS_EXISTING_DATA, line 1501. Thx james johnson.
- Made $inputarr optional for _query() in all drivers.
- Fixed spelling mistake in flushall() in adodb.inc.ophp.
- Fixed handling of quotes in adodb_active_record::doquote. Thx Jonathan Hohle (jhohle#godaddy.com).
- Added new index parameter to adodb_active_record::setdatabaseadaptor. Thx Jonathan Hohle
- Fixed & readcache() reference compat problem with php 5.3 in adodb.Thx Jonathan Hohle.
- Some minor $ADODB_CACHE_CLASS definition issues in adodb.inc.php.
- Added Reset() function to adodb_active_record. Thx marcus.
- Minor dsn fix for pdo_sqlite in adodb.inc.php. Thx Sergey Chvalyuk.
- Fixed adodb-datadict _CreateSuffix() inconsistencies. Thx Chris Miller.
- Option to delete old fields $dropOldFlds in datadict ChangeTableSQL($table, $flds, $tableOptions, $dropOldFlds=false) added. Thx Philipp Niethammer.
- Memcache caching did not expire properly. Fixed.
- MetaForeignKeys for postgres7 driver changed from adodb_movenext to $rs->MoveNext (also in 4.99)
- Added support for ldap and ldaps url format in ldap driver. E.g. ldap://host:port/dn?attributes?scope?filter?extensions
## 5.07 - 26 Dec 2008
- BeginTrans/CommitTrans/RollbackTrans return true/false correctly on success/failure now for mssql, odbc, oci8, mysqlt, mysqli, postgres, pdo.
- Replace() now quotes all non-null values including numeric ones.
- Postgresql qstr() now returns booleans as *true* and *false* without quotes.
- MetaForeignKeys in mysql and mysqli drivers had this problem: A table can have two foreign keys pointing to the same column in the same table. The original code will incorrectly report only the last column. Fixed. https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
- Passing in full ado connection string in $argHostname with ado drivers was failing in adodb5 due to bug. Fixed.
- Fixed memcachelib flushcache and flushall bugs. Also fixed possible timeCreated = 0 problem in readcache. (Also in adodb 4.992). Thanks AlexB_UK (alexbarnes#hotmail.com).
- Fixed a notice in adodb-sessions2.inc.php, in _conn(). Thx bober m.derlukiewicz#rocktech.remove_me.pl;
- ADOdb Active Record: Fixed some issues with incompatible fetch modes (ADODB_FETCH_ASSOC) causing problems in UpdateActiveTable().
- ADOdb Active Record: Added support for functions that support predefining one-to-many relationships:
_ClassHasMany ClassBelongsTo TableHasMany TableBelongsTo TableKeyHasMany TableKeyBelongsTo_.
- You can also define your child/parent class in these functions, instead of the default ADODB_Active_Record. Thx Arialdo Martini & Chris R for idea.
- ADOdb Active Record: HasMany hardcoded primary key to "id". Fixed.
- Many pdo and pdo-sqlite fixes from Sid Dunayer [sdunayer#interserv.com].
- CacheSelectLimit not working for mssql. Fixed. Thx AlexB.
- The rs2html function did not display hours in timestamps correctly. Now 24hr clock used.
- Changed ereg* functions to use preg* functions as ereg* is deprecated in PHP 5.3. Modified sybase and postgresql drivers.
## 5.06 - 16 Oct 2008
- Added driver adodb-pdo_sqlite.inc.php. Thanks Diogo Toscano (diogo#scriptcase.net) for the code.
- Added support for [one-to-many relationships](docs-active-record.htm#onetomany) with BelongsTo() and HasMany() in adodb_active_record.
- Added BINARY type to mysql.inc.php (also in 4.991).
- Added support for SelectLimit($sql,-1,100) in oci8. (also in 4.991).
- New $conn->GetMedian($table, $field, $where='') to get median account no. (also in 4.991)
- The rs2html() function in tohtml.inc.php did not handle dates with ':' in it properly. Fixed. (also in 4.991)
- Added support for connecting to oci8 using `$DB->Connect($ip, $user, $pwd, "SID=$sid");` (also in 4.991)
- Added mysql type 'VAR_STRING' to MetaType(). (also in 4.991)
- The session and session2 code supports setfetchmode assoc properly now (also in 4.991).
- Added concat support to pdo. Thx Andrea Baron.
- Changed db2 driver to use format `Y-m-d H-i-s` for datetime instead of `Y-m-d-H-i-s` which was legacy from odbc_db2 conversion.
- Removed vestigal break on adodb_tz_offset in adodb-time.inc.php.
- MetaForeignKeys did not work for views in MySQL 5. Fixed.
- Changed error handling in GetActiveRecordsClass.
- Added better support for using existing driver when $ADODB_NEWCONNECTION function returns false.
- In _CreateSuffix in adodb-datadict.inc.php, adding unsigned variable for mysql.
- In adodb-xmlschema03.inc.php, changed addTableOpt to include db name.
- If bytea blob in postgresql is null, empty string was formerly returned. Now null is returned.
- Changed db2 driver CreateSequence to support $start parameter.
- rs2html() now does not add nbsp to end if length of string > 0
- The oci8po FetchField() now only lowercases field names if ADODB_ASSOC_CASE is set to 0.
- New mssqlnative drivers for php. TQ Garrett Serack of M'soft. [Download](http://www.microsoft.com/downloads/details.aspx?FamilyId=61BF87E0-D031-466B-B09A-6597C21A2E2A&displaylang=en) mssqlnative extension. Note that this is still in beta.
- Fixed bugs in memcache support.
- You can now change the return value of GetOne if no records are found using the global variable $ADODB_GETONE_EOF. The default is null. To change it back to the pre-4.99/5.00 behaviour of false, set $ADODB_GETONE_EOF = false;
- In Postgresql 8.2/8.3 MetaForeignkeys did not work. Fixed William Kolodny William.Kolodny#gt-t.net
## 5.05 - 11 Jul 2008
Released together with [v4.990](changelog_v4.x.md#4990---11-jul-2008)
- Added support for multiple recordsets in mysqli , thanks to Geisel Sierote geisel#4up.com.br. See http://phplens.com/lens/lensforum/msgs.php?id=15917
- Malcolm Cook added new Reload() function to Active Record. See http://phplens.com/lens/lensforum/msgs.php?id=17474
- Thanks Zoltan Monori (monzol#fotoprizma.hu) for bug fixes in iterator, SelectLimit, GetRandRow, etc.
- Under heavy loads, the performance monitor for oci8 disables Ixora views.
- Fixed sybase driver SQLDate to use str_replace(). Also for adodb5, changed sybase driver UnixDate and UnixTimeStamp calls to static.
- Changed oci8 lob handler to use & reference `$this->_refLOBs[$numlob]['VAR'] = &$var`.
- We now strtolower the get_class() function in PEAR::isError() for php5 compat.
- CacheExecute did not retrieve cache recordsets properly for 5.04 (worked in 4.98). Fixed.
- New ADODB_Cache_File class for file caching defined in adodb.inc.php.
- Farsi language file contribution by Peyman Hooshmandi Raad (phooshmand#gmail.com)
- New API for creating your custom caching class which is stored in $ADODB_CACHE:
``` php
include "/path/to/adodb.inc.php";
$ADODB_CACHE_CLASS = 'MyCacheClass';
class MyCacheClass extends ADODB_Cache_File
{
function writecache($filename, $contents,$debug=false) {...}
function &readcache($filename, &$err, $secs2cache, $rsClass) { ...}
:
}
$DB = NewADOConnection($driver);
$DB->Connect(...); ## MyCacheClass created here and stored in $ADODB_CACHE global variable.
$data = $rs->CacheGetOne($sql); ## MyCacheClass is used here for caching...
```
- Memcache supports multiple pooled hosts now. Only if none of the pooled servers
can be contacted will a connect error be generated. Usage example below:
``` php
$db = NewADOConnection($driver);
$db->memCache = true; /// should we use memCache instead of caching in files
$db->memCacheHost = array($ip1, $ip2, $ip3); /// $db->memCacheHost = $ip1; still works
$db->memCachePort = 11211; /// this is default memCache port
$db->memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
$db->Connect(...);
$db->CacheExecute($sql);
```
## 5.04 - 13 Feb 2008
Released together with [v4.98](changelog_v4.x.md#498---13-feb-2008)
- Fixed adodb_mktime problem which causes a performance bottleneck in $hrs.
- Added mysqli support to adodb_getcount().
- Removed MYSQLI_TYPE_CHAR from MetaType().
## 5.03 - 22 Jan 2008
Released together with [v4.97](changelog_v4.x.md#497---22-jan-2008)
- Active Record: $ADODB_ASSOC_CASE=1 did not work properly. Fixed.
- Modified Fields() in recordset class to support display null fields in FetchNextObject().
- In ADOdb5, active record implementation, we now support column names with spaces in them - we autoconvert the spaces to _ using __set(). Thx Daniel Cook. http://phplens.com/lens/lensforum/msgs.php?id=17200
- Removed $arg3 from mysqli SelectLimit. See http://phplens.com/lens/lensforum/msgs.php?id=16243. Thx Zsolt Szeberenyi.
- Changed oci8 FetchField, which returns the max_length of BLOB/CLOB/NCLOB as 4000 (incorrectly) to -1.
- CacheExecute would sometimes return an error on Windows if it was unable to lock the cache file. This is harmless and has been changed to a warning that can be ignored. Also adodb_write_file() code revised.
- ADOdb perf code changed to only log sql if execution time >= 0.05 seconds. New $ADODB_PERF_MIN variable holds min sql timing. Any SQL with timing value below this and is not causing an error is not logged.
- Also adodb_backtrace() now traces 1 level deeper as sometimes actual culprit function is not displayed.
- Fixed a group by problem with adodb_getcount() for db's which are not postgres/oci8 based.
- Changed mssql driver Parameter() from SQLCHAR to SQLVARCHAR: case 'string': $type = SQLVARCHAR; break.
- Problem with mssql driver in php5 (for adodb 5.03) because some functions are not static. Fixed.
## 5.02 - 24 Sept 2007
Released together with [v4.96](changelog_v4.x.md#496---24-sept-2007)
- ADOdb perf for oci8 now has non-table-locking code when clearing the sql. Slower but better transparency. Added in 4.96a and 5.02a.
- Fix adodb count optimisation. Preg_match did not work properly. Also rewrote the ORDER BY stripping code in _adodb_getcount(), adodb-lib.inc.php.
- SelectLimit for oci8 not optimal for large recordsets when offset=0. Changed $nrows check.
- Active record optimizations. Added support for assoc arrays in Set().
- Now GetOne returns null if EOF (no records found), and false if error occurs. Use ErrorMsg()/ErrorNo() to get the error.
- Also CacheGetRow and CacheGetCol will return false if error occurs, or empty array() if EOF, just like GetRow and GetCol.
- Datadict now allows changing of types which are not resizable, eg. VARCHAR to TEXT in ChangeTableSQL. -- Mateo Tibaquirá
- Added BIT data type support to adodb-ado.inc.php and adodb-ado5.inc.php.
- Ldap driver did not return actual ldap error messages. Fixed.
- Implemented GetRandRow($sql, $inputarr). Optimized for Oci8.
- Changed adodb5 active record to use static SetDatabaseAdapter() and removed php4 constructor. Bas van Beek bas.vanbeek#gmail.com.
- Also in adodb5, changed adodb-session2 to use static function declarations in class. Thx Daniel Berlin.
- Added "Clear SQL Log" to bottom of Performance screen.
- Sessions2 code echo'ed directly to the screen in debug mode. Now uses ADOConnection::outp().
- In mysql/mysqli, qstr(null) will return the string `null` instead of empty quoted string `''`.
- postgresql optimizeTable in perf-postgres.inc.php added by Daniel Berlin (mail#daniel-berlin.de)
- Added 5.2.1 compat code for oci8.
- Changed @@identity to SCOPE_IDENTITY() for multiple mssql drivers. Thx Stefano Nari.
- Code sanitization introduced in 4.95 caused problems in European locales (as float 3.2 was typecast to 3,2). Now we only sanitize if is_numeric fails.
- Added support for customizing ADORecordset_empty using $this->rsPrefix.'empty'. By Josh Truwin.
- Added proper support for ALterColumnSQL for Postgresql in datadict code. Thx. Josh Truwin.
- Added better support for MetaType() in mysqli when using an array recordset.
- Changed parser for pgsql error messages in adodb-error.inc.php to case-insensitive regex.
## 5.01 - 17 May 2007
Released together with [v4.95](changelog_v4.x.md#495---17-may-2007)
- CacheFlush debug outp() passed in invalid parameters. Fixed.
- Added Thai language file for adodb. Thx Trirat Petchsingh rosskouk#gmail.com and Marcos Pont
- Added zerofill checking support to MetaColumns for mysql and mysqli.
- CacheFlush no longer deletes all files/directories. Only *.cache files deleted.
- DB2 timestamp format changed to `var $fmtTimeStamp = "'Y-m-d-H:i:s'";`
- Added some code sanitization to AutoExecute in adodb-lib.inc.php.
- Due to typo, all connections in adodb-oracle.inc.php would become persistent, even non-persistent ones. Fixed.
- Oci8 DBTimeStamp uses 24 hour time for input now, so you can perform string comparisons between 2 DBTimeStamp values.
- Some PHP4.4 compat issues fixed in adodb-session2.inc.php
- For ADOdb 5.01, fixed some adodb-datadict.inc.php MetaType compat issues with PHP5.
- The $argHostname was wiped out in adodb-ado5.inc.php. Fixed.
- Adodb5 version, added iterator support for adodb_recordset_empty.
- Adodb5 version,more error checking code now will use exceptions if available.
+531
View File
@@ -0,0 +1,531 @@
# ADOdb old Changelog - v2.x and older
See the [Current Changelog](changelog.md).
## 2.91 - 3 Jan 2003
- Revised PHP version checking to use $ADODB_PHPVER with legal values 0x4000, 0x4050, 0x4200, 0x4300.
- Added support for bytea fields and oid blobs in postgres by allowing BlobDecode() to detect and convert non-oid fields. Also added BlobEncode to postgres when you want to encode oid blobs.
- Added blobEncodeType property for connections to inform phpLens what encoding method to use for blobs.
- Added BlobDecode() and BlobEncode() to base ADOConnection class.
- Added umask() to _gencachename() when creating directories.
- Added charPage for ado drivers, so you can set the code page.
```
$conn->charPage = CP_UTF8;
$conn->Connect($dsn);
```
- Modified _seek in mysql to check for num rows=0.
- Added to metatypes new informix types for IDS 9.30\. Thx Fernando Ortiz.
- _maxrecordcount returned in CachePageExecute $rsreturn
- Fixed sybase cacheselectlimit( ) problems
- MetaColumns() max_length should use precision for types X and C for ms access. Fixed.
- Speedup of odbc non-SELECT sql statements.
- Added support in MetaColumns for Wide Char types for ODBC. We halve max_length if unicode/wide char.
- Added 'B' to types handled by GetUpdateSQL/GetInsertSQL.
- Fixed warning message in oci8 driver with $persist variable when using PConnect.
## 2.90 - 11 Dec 2002
- Mssql and mssqlpo and oci8po now support ADODB_ASSOC_CASE.
- Now MetaType() can accept a field object as the first parameter.
- New $arr = $db->ServerInfo( ) function. Returns $arr['description'] which is the string description, and $arr['version'].
- PostgreSQL and MSSQL speedups for insert/updates.
- Implemented new SetFetchMode() that removes the need to use $ADODB_FETCH_MODE. Each connection has independant fetchMode.
- ADODB_ASSOC_CASE now defaults to 2, use native defaults. This is because we would break backward compat for too many applications otherwise.
- Patched encrypted sessions to use replace()
- The qstr function supports quoting of nulls when escape character is \
- Rewrote bits and pieces of session code to check for time synch and improve reliability.
- Added property ADOConnection::hasTransactions = true/false;
- Added CreateSequence and DropSequence functions
- Found misplaced MoveNext() in adodb-postgres.inc.php. Fixed.
- Sybase SelectLimit not reliable because 'set rowcount' not cached - fixed.
- Moved ADOConnection to adodb-connection.inc.php and ADORecordSet to adodb-recordset.inc.php. This allows us to use doxygen to generate documentation. Doxygen doesn't like the classes in the main adodb.inc.php file for some mysterious reason.
## 2.50 - 14 Nov 2002
- Added transOff and transCnt properties for disabling (transOff = true) and tracking transaction status (transCnt>0).
- Added inputarray handling into _adodb_pageexecute_all_rows - "Ross Smith" RossSmith#bnw.com.
- Fixed postgresql inconsistencies in date handling.
- Added support for mssql_fetch_assoc.
- Fixed $ADODB_FETCH_MODE bug in odbc MetaTables() and MetaPrimaryKeys().
- Accidentally declared UnixDate() twice, making adodb incompatible with php 4.3.0\. Fixed.
- Fixed pager problems with some databases that returned -1 for _currentRow on MoveLast() by switching to MoveNext() in adodb-lib.inc.php.
- Also fixed uninited $discard in adodb-lib.inc.php.
## 2.43 - 25 Oct 2002
- Added ADODB_ASSOC_CASE constant to better support ibase and odbc field names.
- Added support for NConnect() for oracle OCINLogin.
- Fixed NumCols() bug.
- Changed session handler to use Replace() on write.
- Fixed oci8 SelectLimit aggregate function bug again.
- Rewrote pivoting code.
## 2.42 - 4 Oct 2002
- Fixed ibase_fetch() problem with nulls. Also interbase now does automatic blob decoding, and is backward compatible. Suggested by Heinz Hombergs heinz#hhombergs.de.
- Fixed postgresql MoveNext() problems when called repeatedly after EOF. Also suggested by Heinz Hombergs.
- PageExecute() does not rewrite queries if SELECT DISTINCT is used. Requested by hans#velum.net
- Added additional fixes to oci8 SelectLimit handling with aggregate functions - thx to Christian Bugge for reporting the problem.
## 2.41 - 2 Oct 2002
- Fixed ADODB_COUNTRECS bug in odbc. Thx to Joshua Zoshi jzoshi#hotmail.com.
- Increased buffers for adodb-csvlib.inc.php for extremely long sql from 8192 to 32000.
- Revised pivottable.inc.php code. Added better support for aggregate fields.
- Fixed mysql text/blob types problem in MetaTypes base class - thx to horacio degiorgi.
- Added SQLDate($fmt,$date) function, which allows an sql date format string to be generated - useful for group by's.
- Fixed bug in oci8 SelectLimit when offset>100.
## 2.40 - 4 Sept 2002
- Added new NLS_DATE_FORMAT property to oci8\. Suggested by Laurent NAVARRO ln#altidev.com
- Now use bind parameters in oci8 selectlimit for better performance.
- Fixed interbase replaceQuote for dialect != 1\. Thx to "BEGUIN Pierre-Henri - INFOCOB" phb#infocob.com.
- Added white-space check to QA.
- Changed unixtimestamp to support fractional seconds (we always round down/floor the seconds). Thanks to beezly#beezly.org.uk.
- Now you can set the trigger_error type your own user-defined type in adodb-errorhandler.inc.php. Suggested by Claudio Bustos clbustos#entelchile.net.
- Added recordset filters with rsfilter.inc.php.
$conn->_rs2rs does not create a new recordset when it detects it is of type array. Some trickery there as there seems to be a bug in Zend Engine
- Added render_pagelinks to adodb-pager.inc.php. Code by "Pablo Costa" pablo#cbsp.com.br.
- MetaType() speedup in adodb.inc.php by using hashing instead of switch. Best performance if constant arrays are supported, as they are in PHP5.
- adodb-session.php now updates only the expiry date if the crc32 check indicates that the data has not been modified.
## 2.31 - 20 Aug 2002
- Made changes to pivottable.inc.php due to daniel lucuzaeu's suggestions (we sum the pivottable column if desired).
- Fixed ErrorNo() in postgres so it does not depend on _errorMsg property.
- Robert Tuttle added support for oracle cursors. See ExecuteCursor().
- Fixed Replace() so it works with mysql when updating record where data has not changed. Reported by Cal Evans (cal#calevans.com).
## 2.30 - 1 Aug 2002
- Added pivottable.inc.php. Thanks to daniel.lucazeau#ajornet.com for the original concept.
- Added ADOConnection::outp($msg,$newline) to output error and debugging messages. Now you can override this using the ADODB_OUTP constant and use your own output handler.
- Changed == to === for 'null' comparison. Reported by ericquil#yahoo.com
- Fixed mssql SelectLimit( ) bug when distinct used.
## 2.30 - 1 Aug 2002
- New GetCol() and CacheGetCol() from ross#bnw.com that returns the first field as a 1 dim array.
- We have an empty recordset, but RecordCount() could return -1\. Fixed. Reported by "Jonathan Polansky" jonathan#polansky.com.
- We now check for session variable changes using strlen($sessval).crc32($sessval). Formerly we only used crc32().
- Informix SelectLimit() problem with $ADODB_COUNTRECS fixed.
- Fixed informix SELECT FIRST x DISTINCT, and not SELECT DISTINCT FIRST x - reported by F Riosa
- Now default adodb error handlers ignores error if @ used.
- If you set $conn->autoRollback=true, we auto-rollback persistent connections for odbc, mysql, oci8, mssql. Default for autoRollback is false. No need to do so for postgres. As interbase requires a transaction id (what a flawed api), we don't do it for interbase.
- Changed PageExecute() to use non-greedy preg_match when searching for "FROM" keyword.
## 2.20 - 9 July 2002
- Added CacheGetOne($secs2cache,$sql), CacheGetRow($secs2cache,$sql), CacheGetAll($secs2cache,$sql).
- Added $conn->OffsetDate($dayFraction,$date=false) to generate sql that calcs date offsets. Useful for scheduling appointments.
- Added connection properties: leftOuter, rightOuter that hold left and right outer join operators.
- Added connection property: ansiOuter to indicate whether ansi outer joins supported.
- New driver _mssqlpo_, the portable mssql driver, which converts string concat operator from || to +.
- Fixed ms access bug - SelectLimit() did not support ties - fixed.
- Karsten Kraus (Karsten.Kraus#web.de), contributed error-handling code to ADONewConnection. Unfortunately due to backward compat problems, had to rollback most of the changes.
- Added new parameter to GetAssoc() to allow returning an array of key-value pairs, ignoring any additional columns in the recordset. Off by default.
- Corrected mssql $conn->sysDate to return only date using convert().
- CacheExecute() improved debugging output.
- Changed rs2html() so newlines are converted to BR tags. Also optimized rs2html() based on feedback by "Jerry Workman" jerry#mtncad.com.
- Added support for Replace() with Interbase, using DELETE and INSERT.
- Some minor optimizations (mostly removing & references when passing arrays).
- Changed GenID() to allows id's larger than the size of an integer.
- Added force_session property to oci8 for better updateblob() support.
- Fixed PageExecute() which did not work properly with sql containing GROUP BY.
## 2.12 - 12 June 2002
- Added toexport.inc.php to export recordsets in CSV and tab-delimited format.
- CachePageExecute() does not work - fixed - thx John Huong.
- Interbase aliases not set properly in FetchField() - fixed. Thx Stefan Goethals.
- Added cache property to adodb pager class. The number of secs to cache recordsets.
- SQL rewriting bug in pageexecute() due to skipping of newlines due to missing /s modifier. Fixed.
- Max size of cached recordset due to a bug was 256000 bytes. Fixed.
- Speedup of 1st invocation of CacheExecute() by tuning code.
- We compare $rewritesql with $sql in pageexecute code in case of rewrite failure.
## 2.11 - 7 June 2002
- Fixed PageExecute() rewrite sql problem - COUNT(*) and ORDER BY don't go together with mssql, access and postgres. Thx to Alexander Zhukov alex#unipack.ru
- DB2 support for CHARACTER type added - thx John Huong huongch#bigfoot.com
- For ado, $argProvider not properly checked. Fixed - kalimero#ngi.it
- Added $conn->Replace() function for update with automatic insert if the record does not exist. Supported by all databases except interbase.
## 2.10 - 4 June 2002
- Added uniqueSort property to indicate mssql ORDER BY cols must be unique.
- Optimized session handler by crc32 the data. We only write if session data has changed.
- adodb_sess_read in adodb-session.php now returns ''correctly - thanks to Jorma Tuomainen, webmaster#wizactive.com
- Mssql driver did not throw EXECUTE errors correctly because ErrorMsg() and ErrorNo() called in wrong order. Pointed out by Alexios Fakos. Fixed.
- Changed ado to use client cursors. This fixes BeginTran() problems with ado.
- Added handling of timestamp type in ado.
- Added to ado_mssql support for insert_id() and affected_rows().
- Added support for mssql.datetimeconvert=0, available since php 4.2.0.
- Made UnixDate() less strict, so that the time is ignored if present.
- Changed quote() so that it checks for magic_quotes_gpc.
- Changed maxblobsize for odbc to default to 64000.
## 2.00 - 13 May 2002
- Added drivers _informix72_ for pre-7.3 versions, and _oci805_ for oracle 8.0.5, and postgres64 for postgresql 6.4 and earlier. The postgres and postgres7 drivers are now identical.
- Interbase now partially supports ADODB_FETCH_BOTH, by defaulting to ASSOC mode.
- Proper support for blobs in mssql. Also revised blob support code is base class. Now UpdateBlobFile() calls UpdateBlob() for consistency.
- Added support for changed odbc_fetch_into api in php 4.2.0 with $conn->_has_stupid_odbc_fetch_api_change.
- Fixed spelling of tablock locking hint in GenID( ) for mssql.
- Added RowLock( ) to several databases, including oci8, informix, sybase, etc. Fixed where error in mssql RowLock().
- Added sysDate and sysTimeStamp properties to most database drivers. These are the sql functions/constants for that database that return the current date and current timestamp, and are useful for portable inserts and updates.
- Support for RecordCount() caused date handling in sybase and mssql to break. Fixed, thanks to Toni Tunkkari, by creating derived classes for ADORecordSet_array for both databases. Generalized using arrayClass property. Also to support RecordCount(), changed metatype handling for ado drivers. Now the type returned in FetchField is no longer a number, but the 1-char data type returned by MetaType. At the same time, fixed a lot of date handling. Now mssql support dmy and mdy date formats. Also speedups in sybase and mssql with preg_match and ^ in date/timestamp handling. Added support in sybase and mssql for 24 hour clock in timestamps (no AM/PM).
- Extensive revisions to informix driver - thanks to Samuel CARRIERE samuel_carriere#hotmail.com
- Added $ok parameter to CommitTrans($ok) for easy rollbacks.
- Fixed odbc MetaColumns and MetaTables to save and restore $ADODB_FETCH_MODE.
- Some odbc drivers did not call the base connection class constructor. Fixed.
- Fixed regex for GetUpdateSQL() and GetInsertSQL() to support more legal character combinations.
## 1.99 - 21 April 2002
- Added emulated RecordCount() to all database drivers if $ADODB_COUNTRECS = true (which it is by default). Inspired by Cristiano Duarte (cunha17#uol.com.br).
- Unified stored procedure support for mssql and oci8\. Parameter() and PrepareSP() functions implemented.
- Added support for SELECT FIRST in informix, modified hasTop property to support this.
- Changed csv driver to handle updates/deletes/inserts properly (when Execute() returns true). Bind params also work now, and raiseErrorFn with csv driver. Added csv driver to QA process.
- Better error checking in oci8 UpdateBlob() and UpdateBlobFile().
- Added TIME type to MySQL - patch by Manfred h9125297#zechine.wu-wien.ac.at
- Prepare/Execute implemented for Interbase/Firebird
- Changed some regular expressions to be anchored by /^ $/ for speed.
- Added UnixTimeStamp() and UnixDate() to ADOConnection(). Now these functions are in both ADOConnection and ADORecordSet classes.
- Empty recordsets were not cached - fixed.
- Thanks to Gaetano Giunta (g.giunta#libero.it) for the oci8 code review. We didn't agree on everything, but i hoped we agreed to disagree!
## 1.90 - 6 April 2002
- Now all database drivers support fetch modes ADODB_FETCH_NUM and ADODB_FETCH_ASSOC, though still not fully tested. Eg. Frontbase, Sybase, Informix.
- NextRecordSet() support for mssql. Contributed by "Sven Axelsson" sven.axelsson#bokochwebb.se
- Added blob support for SQL Anywhere. Contributed by Wade Johnson wade#wadejohnson.de
- Fixed some security loopholes in server.php. Server.php also supports fetch mode.
- Generalized GenID() to support odbc and mssql drivers. Mssql no longer generates GUID's.
- Experimental RowLock($table,$where) for mssql.
- Properly implemented Prepare() in oci8 and ODBC.
- Added Bind() support to oci8 to support Prepare().
- Improved error handler. Catches CacheExecute() and GenID() errors now.
- Now if you are running php from the command line, debugging messages do not output html formating. Not 100% complete, but getting there.
## 1.81 - 22 March 2002
- Restored default $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT for backward compatibility.
- SelectLimit for oci8 improved - Our FIRST_ROWS optimization now does not overwrite existing hint.
- New Sybase SQL Anywhere driver. Contributed by Wade Johnson wade#wadejohnson.de
## 1.80 - 15 March 2002
- Redesigned directory structure of ADOdb files. Added new driver directory where all database drivers reside.
- Changed caching algorithm to create subdirectories. Now we scale better.
- Informix driver now supports insert_id(). Contribution by "Andrea Pinnisi" pinnisi#sysnet.it
- Added experimental ISO date and FetchField support for informix.
- Fixed a quoting bug in Execute() with bind parameters, causing problems with blobs.
- Mssql driver speedup by 10-15%.
- Now in CacheExecute($secs2cache,$sql,...), $secs2cache is optional. If missing, it will take the value defined in $connection->cacheSecs (default is 3600 seconds). Note that CacheSelectLimit(), the secs2cache is still compulsory - sigh.
- Sybase SQL Anywhere driver (using ODBC) contributed by Wade Johnson wade#wadejohnson.de
## 1.72 - 8 March 2002
- Added @ when returning Fields() to prevent spurious error - "Michael William Miller" mille562#pilot.msu.edu
- MetaDatabases() for postgres contributed by Phil pamelant#nerim.net
- Mitchell T. Young (mitch#youngfamily.org) contributed informix driver.
- Fixed rs2html() problem. I cannot reproduce, so probably a problem with pre PHP 4.1.0 versions, when supporting new ADODB_FETCH_MODEs.
- Mattia Rossi (mattia#technologist.com) contributed BlobDecode() and UpdateBlobFile() for postgresql using the postgres specific pg_lo_import()/pg_lo_open() - i don't use them but hopefully others will find this useful. See [this posting](http://phplens.com/lens/lensforum/msgs.php?id=1262) for an example of usage.
- Added UpdateBlobFile() for uploading files to a database.
- Made UpdateBlob() compatible with oci8po driver.
- Added noNullStrings support to oci8 driver. Oracle changes all ' ' strings to nulls, so you need to set strings to ' ' to prevent the nullifying of strings. $conn->noNullStrings = true; will do this for you automatically. This is useful when you define a char column as NOT NULL.
- Fixed UnixTimeStamp() bug - wasn't setting minutes and seconds properly. Patch from Agusti Fita i Borrell agusti#anglatecnic.com.
- Toni Tunkkari added patch for sybase dates. Problem with spaces in day part of date fixed.
## 1.71 - 18 Jan 2002
- Sequence start id support. Now $conn->Gen_ID('seqname', 50) to start sequence from 50.
- CSV driver fix for selectlimit, from Andreas - akaiser#vocote.de.
- Gam3r spotted that a global variable was undefined in the session handler.
- Mssql date regex had error. Fixed - reported by Minh Hoang vb_user#yahoo.com.
- DBTimeStamp() and DBDate() now accept iso dates and unix timestamps. This means that the PostgreSQL handling of dates in GetInsertSQL() and GetUpdateSQL() can be removed. Also if these functions are passed '' or null or false, we return a SQL null.
- GetInsertSQL() and GetUpdateSQL() now accept a new parameter, $magicq to indicate whether quotes should be inserted based on magic quote settings - suggested by dj#4ict.com.
- Reformated docs slightly based on suggestions by Chris Small.
## 1.65 - 28 Dec 2001
- Fixed borland_ibase class naming bug.
- Now instead of using $rs->fields[0] internally, we use reset($rs->fields) so that we are compatible with ADODB_FETCH_ASSOC mode. Reported by Nico S.
- Changed recordset constructor and _initrs() for oci8 so that it returns the field definitions even if no rows in the recordset. Reported by Rick Hickerson (rhickers#mv.mv.com).
- Improved support for postgresql in GetInsertSQL and GetUpdateSQL by "mike" mike#partner2partner.com and "Ryan Bailey" rebel#windriders.com
## 1.64 - 20 Dec 2001
- Danny Milosavljevic <danny.milo#gmx.net> added some patches for MySQL error handling and displaying default values.
- Fixed some ADODB_FETCH_BOTH inconsistencies in odbc and interbase.
- Added more tests to test suite to cover ADODB_FETCH_* and ADODB_ERROR_HANDLER.
- Added firebird (ibase) driver
- Added borland_ibase driver for interbase 6.5
## 1.63 - 13 Dec 2001
- Absolute to the adodb-lib.inc.php file not set properly. Fixed.
## 1.62 - 11 Dec 2001
- Major speedup of ADOdb for low-end web sites by reducing the php code loading and compiling cycle. We conditionally compile not so common functions. Moved csv code to adodb-csvlib.inc.php to reduce adodb.inc.php parsing. This file is loaded only when the csv/proxy driver is used, or CacheExecute() is run. Also moved PageExecute(), GetSelectSQL() and GetUpdateSQL() core code to adodb-lib.inc.php. This reduced the 70K main adodb.inc.php file to 55K, and since at least 20K of the file is comments, we have reduced 50K of code in adodb.inc.php to 35K. There should be 35% reduction in memory and thus 35% speedup in compiling the php code for the main adodb.inc.php file.
- Highly tuned SelectLimit() for oci8 for massive speed improvements on large files. Selecting 20 rows starting from the 20,000th row of a table is now 7 times faster. Thx to Tomas V V Cox.
- Allow . and # in table definitions in GetInsertSQL and GetUpdateSQL. See ADODB_TABLE_REGEX constant. Thx to Ari Kuorikoski.
- Added ADODB_PREFETCH_ROWS constant, defaulting to 10\. This determines the number of records to prefetch in a SELECT statement. Only used by oci8.
- Added high portability Oracle class called oci8po. This uses ? for bind variables, and lower cases column names.
- Now all database drivers support $ADODB_FETCH_MODE, including interbase, ado, and odbc: ADODB_FETCH_NUM and ADODB_FETCH_ASSOC. ADODB_FETCH_BOTH is not fully implemented for all database drivers.
## 1.61 - Nov 2001
- Added PO_RecordCount() and PO_Insert_ID(). PO stands for portable. Pablo Roca [pabloroca#mvps.org]
- GenID now returns 0 if not available. Safer is that you should check $conn->hasGenID for availability.
- M'soft ADO we now correctly close recordset in _close() peterd#telephonetics.co.uk
- MSSQL now supports GenID(). It generates a 16-byte GUID from mssql newid() function.
- Changed ereg_replace to preg_replace in SelectLimit. This is a fix for mssql. Ereg doesn't support t or n! Reported by marino Carlos xaplo#postnuke-espanol.org
- Added $recordset->connection. This is the ADOConnection object for the recordset. Works with cached and normal recordsets. Surprisingly, this had no affect on performance!
## 1.54 - 15 Nov 2001
- Fixed some more bugs in PageExecute(). I am getting sick of bug in this and will have to reconsider my QA here. The main issue is that I don't use PageExecute() and to check whether it is working requires a visual inspection of the html generated currently. It is possible to write a test script but it would be quite complicated :(
- More speedups of SelectLimit() for DB2, Oci8, access, vfp, mssql.
## 1.53 - 7 Nov 2001
- Added support for ADODB_FETCH_ASSOC for ado and odbc drivers.
- Tuned GetRowAssoc(false) in postgresql and mysql.
- Stephen Van Dyke contributed ADOdb icon, accepted with some minor mods.
- Enabled Affected_Rows() for postgresql
- Speedup for Concat() using implode() - Benjamin Curtis ben_curtis#yahoo.com
- Fixed some more bugs in PageExecute() to prevent infinite loops
## 1.52 - 5 Nov 2001
- Spelling error in CacheExecute() caused it to fail. $ql should be $sql in line 625!
- Added fixes for parsing [ and ] in GetUpdateSQL().
## 1.51 - 5 Nov 2001
- Oci8 SelectLimit() speedup by using OCIFetch().
- Oci8 was mistakenly reporting errors when $db->debug = true.
- If a connection failed with ODBC, it was not correctly reported - fixed.
- _connectionID was inited to -1, changed to false.
- Added $rs->FetchRow(), to simplify API, ala PEAR DB
- Added PEAR DB compat mode, which is still faster than PEAR! See adodb-pear.inc.php.
- Removed postgres pconnect debugging statement.
## 1.50 - 31 Oct 2001
- ADOdbConnection renamed to ADOConnection, and ADOdbFieldObject to ADOFieldObject.
- PageExecute() now checks for empty $rs correctly, and the errors in the docs on this subject have been fixed.
- odbc_error() does not return 6 digit error correctly at times. Implemented workaround.
- Added ADORecordSet_empty class. This will speedup INSERTS/DELETES/UPDATES because the return object created is much smaller.
- Added Prepare() to odbc, and oci8 (but doesn't work properly for oci8 still).
- Made pgsql a synonym for postgre7, and changed SELECT LIMIT to use OFFSET for compat with postgres 7.2.
- Revised adodb-cryptsession.php thanks to Ari.
- Set resources to false on _close, to force freeing of resources.
- Added adodb-errorhandler.inc.php, adodb-errorpear.inc.php and raiseErrorFn on Freek's urging.
- GetRowAssoc($toUpper=true): $toUpper added as default.
- Errors when connecting to a database were not captured formerly. Now we do it correctly.
## 1.40 - 19 September 2001
- PageExecute() to implement page scrolling added. Code and idea by Iván Oliva.
- Some minor postgresql fixes.
- Added sequence support using GenID() for postgresql, oci8, mysql, interbase.
- Added UpdateBlob support for interbase (untested).
- Added encrypted sessions (see adodb-cryptsession.php). By Ari Kuorikoski <kuoriari#finebyte.com>
## 1.31 - 21 August 2001
- Many bug fixes thanks to "GaM3R (Cameron)" <gamr#outworld.cx>. Some session changes due to Gam3r.
- Fixed qstr() to quote also.
- rs2html() now pretty printed.
- Jonathan Younger <jyounger#unilab.com> contributed the great idea GetUpdateSQL() and GetInsertSQL() which generates SQL to update and insert into a table from a recordset. Modify the recordset fields array, then can this function to generate the SQL (the SQL is not executed).
- Nicola Fankhauser <nicola.fankhauser#couniq.com> found some bugs in date handling for mssql.
- Added minimal Oracle support for LOBs. Still under development.
- Added $ADODB_FETCH_MODE so you can control whether recordsets return arrays which are numeric, associative or both. This is a global variable you set. Currently only MySQL, Oci8, Postgres drivers support this.
- PostgreSQL properly closes recordsets now. Reported by several people.
- Added UpdateBlob() for Oracle. A hack to make it easier to save blobs.
- Oracle timestamps did not display properly. Fixed.
## 1.20 - 6 June 2001
- Now Oracle can connect using tnsnames.ora or server and service name
- Extensive Oci8 speed optimizations. Oci8 code revised to support variable binding, and /*+ FIRST_ROWS */ hint.
- Worked around some 4.0.6 bugs in odbc_fetch_into().
- Paolo S. Asioli paolo.asioli#libero.it suggested GetRowAssoc().
- Escape quotes for oracle wrongly set to '. Now '' is used.
- Variable binding now works in ODBC also.
- Jumped to version 1.20 because I don't like 13 :-)
## 1.12 - 6 June 2001
- Changed $ADODB_DIR to ADODB_DIR constant to plug a security loophole.
- Changed _close() to close persistent connections also. Prevents connection leaks.
- Major revision of oracle and oci8 drivers. Added OCI_RETURN_NULLS and OCI_RETURN_LOBS to OCIFetchInto(). BLOB, CLOB and VARCHAR2 recognition in MetaType() improved. MetaColumns() returns columns in correct sort order.
- Interbase timestamp input format was wrong. Fixed.
## 1.11 - 20 May 2001
- Improved file locking for Windows.
- Probabilistic flushing of cache to avoid avalanche updates when cache timeouts.
- Cached recordset timestamp not saved in some scenarios. Fixed.
## 1.10 - 19 May 2001
- Added caching. CacheExecute() and CacheSelectLimit().
- Added csv driver. See [http://php.weblogs.com/ADODB_csv](http://php.weblogs.com/adodb_csv).
- Fixed SelectLimit(), SELECT TOP not working under certain circumstances.
- Added better Frontbase support of MetaTypes() by Frank M. Kromann.
## 1.01 - 24 April 2001
- Fixed SelectLimit bug. not quoted properly.
- SelectLimit: SELECT TOP -1 * FROM TABLE not support by Microsoft. Fixed.
- GetMenu improved by glen.davies#cce.ac.nz to support multiple hilited items
- FetchNextObject() did not work with only 1 record returned. Fixed bug reported by $tim#orotech.net
- Fixed mysql field max_length problem. Fix suggested by Jim Nicholson (jnich#att.com)
## 1.00 - 16 April 2001
- Given some brilliant suggestions on how to simplify ADOdb by akul. You no longer need to setup $ADODB_DIR yourself, and ADOLoadCode() is automatically called by ADONewConnection(), simplifying the startup code.
- FetchNextObject() added. Suggested by Jakub Marecek. This makes FetchObject() obsolete, as this is more flexible and powerful.
- Misc fixes to SelectLimit() to support Access (top must follow distinct) and Fields() in the array recordset. From Reinhard Balling.
## 0.96 - 27 Mar 2001
- ADOConnection Close() did not return a value correctly. Thanks to akul#otamedia.com.
- When the horrible magic_quotes is enabled, back-slash () is changed to double-backslash (\). This doesn't make sense for Microsoft/Sybase databases. We fix this in qstr().
- Fixed Sybase date problem in UnixDate() thanks to Toni Tunkkari. Also fixed MSSQL problem in UnixDate() - thanks to milhouse31#hotmail.com.
- MoveNext() moved to leaf classes for speed in MySQL/PostgreSQL. 10-15% speedup.
- Added null handling in bindInputArray in Execute() -- Ron Baldwin suggestion.
- Fixed some option tags. Thanks to john#jrmstudios.com.
## 0.95 - 13 Mar 2001
- Added postgres7 database driver which supports LIMIT and other version 7 stuff in the future.
- Added SelectLimit to ADOConnection to simulate PostgreSQL's "select * from table limit 10 offset 3". Added helper function GetArrayLimit() to ADORecordSet.
- Fixed mysql metacolumns bug. Thanks to Freek Dijkstra (phpeverywhere#macfreek.com).
- Also many PostgreSQL changes by Freek. He almost rewrote the whole PostgreSQL driver!
- Added fix to input parameters in Execute for non-strings by Ron Baldwin.
- Added new metatype, X for TeXt. Formerly, metatype B for Blob also included text fields. Now 'B' is for binary/image data. 'X' for textual data.
- Fixed $this->GetArray() in GetRows().
- Oracle and OCI8: 1st parameter is always blank -- now warns if it is filled.
- Now _hasLimit_ and _hasTop_ added to indicate whether SELECT * FROM TABLE LIMIT 10 or SELECT TOP 10 * FROM TABLE are supported.
## 0.94 - 04 Feb 2001
- Added ADORecordSet::GetRows() for compatibility with Microsoft ADO. Synonym for GetArray().
- Added new metatype 'R' to represent autoincrement numbers.
- Added ADORecordSet.FetchObject() to return a row as an object.
- Finally got a Linux box to test PostgreSql. Many fixes.
- Fixed copyright misspellings in 0.93.
- Fixed mssql MetaColumns type bug.
- Worked around odbc bug in PHP4 for sessions.
- Fixed many documentation bugs (affected_rows, metadatabases, qstr).
- Fixed MySQL timestamp format (removed comma).
- Interbase driver did not call ibase_pconnect(). Fixed.
## 0.93 - 18 Jan 2002
- Fixed GetMenu bug.
- Simplified Interbase commit and rollback.
- Default behaviour on closing a connection is now to rollback all active transactions.
- Added field object handling for array recordset for future XML compatibility.
- Added arr2html() to convert array to html table.
## 0.92 - 2 Jan 2002
- Interbase Commit and Rollback should be working again.
- Changed initialisation of ADORecordSet. This is internal and should not affect users. We are doing this to support cached recordsets in the future.
- Implemented ADORecordSet_array class. This allows you to simulate a database recordset with an array.
- Added UnixDate() and UnixTimeStamp() to ADORecordSet.
## 0.91 - 21 Dec 2000
- Fixed ODBC so ErrorMsg() is working.
- Worked around ADO unrecognised null (0x1) value problem in COM.
- Added Sybase support for FetchField() type
- Removed debugging code and unneeded html from various files
- Changed to javadoc style comments to adodb.inc.php.
- Added maxsql as synonym for mysqlt
- Now ODBC downloads first 8K of blob by default
## 0.90 - 15 Nov 2000
- Lots of testing of Microsoft ADO. Should be more stable now.
- Added $ADODB_COUNTREC. Set to false for high speed selects.
- Added Sybase support. Contributed by Toni Tunkkari (toni.tunkkari#finebyte.com). Bug in Sybase API: GetFields is unable to determine date types.
- Changed behaviour of RecordSet.GetMenu() to support size parameter (listbox) properly.
- Added emptyDate and emptyTimeStamp to RecordSet class that defines how to represent empty dates.
- Added MetaColumns($table) that returns an array of ADOFieldObject's listing the columns of a table.
- Added transaction support for PostgresSQL -- thanks to "Eric G. Werk" egw#netguide.dk.
- Added adodb-session.php for session support.
## 0.80 - 30 Nov 2000
- Added support for charSet for interbase. Implemented MetaTables for most databases. PostgreSQL more extensively tested.
## 0.71 - 22 Nov 2000
- Switched from using require_once to include/include_once for backward compatability with PHP 4.02 and earlier.
## 0.70 - 15 Nov 2000
- Calls by reference have been removed (call_time_pass_reference=Off) to ensure compatibility with future versions of PHP, except in Oracle 7 driver due to a bug in php_oracle.dll.
- PostgreSQL database driver contributed by Alberto Cerezal (acerezalp#dbnet.es).
- Oci8 driver for Oracle 8 contributed by George Fourlanos (fou#infomap.gr).
- Added _mysqlt_ database driver to support MySQL 3.23 which has transaction support.
- Oracle default date format (DD-MON-YY) did not match ADOdb default date format (which is YYYY-MM-DD). Use ALTER SESSION to force the default date.
- Error message checking is now included in test suite.
- MoveNext() did not check EOF properly -- fixed.
## 0.60 - 8 Nov 2000
- Fixed some constructor bugs in ODBC and ADO. Added ErrorNo function to ADOConnection class.
## 0.51 - 18 Oct 2000
- Fixed some interbase bugs.
## 0.50 - 16 Oct 2000
- Interbase commit/rollback changed to be compatible with PHP 4.03\.
- CommitTrans( ) will now return true if transactions not supported.
- Conversely RollbackTrans( ) will return false if transactions not supported.
## 0.46 - 12 Oct 2000
- Many Oracle compatibility issues fixed.
## 0.40 - 26 Sept 2000
- Many bug fixes
- Now Code for BeginTrans, CommitTrans and RollbackTrans is working. So is the Affected_Rows and Insert_ID. Added above functions to test.php.
- ADO type handling was busted in 0.30\. Fixed.
- Generalised Move( ) so it works will all databases, including ODBC.
## 0.30 - 18 Sept 2000
- Renamed ADOLoadDB to ADOLoadCode. This is clearer.
- Added BeginTrans, CommitTrans and RollbackTrans functions.
- Added Affected_Rows() and Insert_ID(), _affectedrows() and _insertID(), ListTables(), ListDatabases(), ListColumns().
- Need to add New_ID() and hasInsertID and hasAffectedRows, autoCommit
## 0.20 - 12 Sept 2000
- Added support for Microsoft's ADO.
- Added new field to ADORecordSet -- canSeek
- Added new parameter to _fetch($ignore_fields = false). Setting to true will not update fields array for faster performance.
- Added new field to ADORecordSet/ADOConnection -- dataProvider to indicate whether a class is derived from odbc or ado.
- Changed class ODBCFieldObject to ADOFieldObject -- not documented currently.
- Added benchmark.php and testdatabases.inc.php to the test suite.
- Added to ADORecordSet FastForward( ) for future high speed scrolling. Not documented.
- Realised that ADO's Move( ) uses relative positioning. ADOdb uses absolute.
## 0.10 - 9 Sept 2000
- First release
+242
View File
@@ -0,0 +1,242 @@
# ADOdb old Changelog - v3.x
See the [Current Changelog](changelog.md).
Older changelogs:
[v2.x](changelog_v2.x.md).
## 3.94 - 11 Oct 2003
- Create trigger in datadict-oci8.inc.php did not work, because all cr/lf's must be removed.
- ErrorMsg()/ErrorNo() did not work for many databases when logging enabled. Fixed.
- Removed global variable $ADODB_LOGSQL as it does not work properly with multiple connections.
- Added SQLDate support for sybase. Thx to Chris Phillipson
- 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.
- Added support for NConnect for postgresql.
- Added Sybase data dict support. Thx to Chris Phillipson
- Extensive improvements in $perf->UI(), eg. Explain now opens in new window, we show scripts which call sql, etc.
- Perf Monitor UI works with magic quotes enabled.
- rsPrefix was declared twice. Removed.
- Oci8 stored procedure support, eg. "begin func(); end;" was incorrect in _query. Fixed.
- Tiraboschi Massimiliano contributed italian language file.
- Fernando Ortiz, fortiz#lacorona.com.mx, contributed informix performance monitor.
- Added _varchar (varchar arrays) support for postgresql. Reported by PREVOT Stéphane.
## 3.92 - 22 Sept 2003
- Added GetAssoc and CacheGetAssoc to connection object.
- Removed TextMax and CharMax functions from adodb.inc.php.
- HasFailedTrans() returned false when trans failed. Fixed.
- Moved perf driver classes into adodb/perf/*.php.
- Misc improvements to performance monitoring, including UI().
- RETVAL in mssql Parameter(), we do not append @ now.
- Added Param($name) to connection class, returns '?' or ":$name", for defining bind parameters portably.
- LogSQL traps affected_rows() and saves its value properly now. Also fixed oci8 _stmt and _affectedrows() bugs.
- 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.
- Fixed bugs in adodb-cryptsession.inc.php and adodb-session-clob.inc.php.
- Fixed misc bugs in adodb_key_exists, GetInsertSQL() and GetUpdateSQL().
- Tuned include_once handling to reduce file-system checking overhead.
## 3.91 - 9 Sept 2003
- Only released to InterAkt
- Added LogSQL() for sql logging and $ADODB_NEWCONNECTION to override factory for driver instantiation.
- Added IfNull($field,$ifNull) function, thx to johnwilk#juno.com
- Added portable substr support.
- Now rs2html() has new parameter, $echo. Set to false to return $html instead of echoing it.
## 3.90 - 5 Sept 2003
- First beta of performance monitoring released.
- MySQL supports MetaTable() masking.
- Fixed key_exists() bug in adodb-lib.inc.php
- Added sp_executesql Prepare() support to mssql.
- Added bind support to db2.
- Added swedish language file - Christian Tiberg" christian#commsoft.nu
- Bug in drop index for mssql data dict fixed. Thx to Gert-Rainer Bitterlich.
- Left join setting for oci8 was wrong. Thx to johnwilk#juno.com
## 3.80 - 27 Aug 2003
- Patch for PHP 4.3.3 cached recordset csv2rs() fread loop incompatibility.
- Added matching mask for MetaTables. Only for oci8, mssql and postgres currently.
- Rewrite of "oracle" driver connection code, merging with "oci8", by Gaetano.
- Added better debugging for Smart Transactions.
- Postgres DBTimeStamp() was wrongly using TO_DATE. Changed to TO_TIMESTAMP.
- ADODB_FETCH_CASE check pushed to ADONewConnection to allow people to define it after including adodb.inc.php.
- Added portugese (brazilian) to languages. Thx to "Levi Fukumori".
- Removed arg3 parameter from Execute/SelectLimit/Cache* functions.
- Execute() now accepts 2-d array as $inputarray. Also changed docs of fnExecute() to note change in sql query counting with 2-d arrays.
- Added MONEY to MetaType in PostgreSQL.
- Added more debugging output to CacheFlush().
## 3.72 - 9 Aug 2003
- Added qmagic($str), which is a qstr($str) that auto-checks for magic quotes and does the right thing...
- Fixed CacheFlush() bug - Thx to martin#gmx.de
- Walt Boring contributed MetaForeignKeys for postgres7.
- _fetch() called _BlobDecode() wrongly in interbase. Fixed.
- adodb_time bug fixed with dates after 2038 fixed by Jason Pell. http://phplens.com/lens/lensforum/msgs.php?id=6980
## 3.71 - 4 Aug 2003
- The oci8 driver, MetaPrimaryKeys() did not check the owner correctly when $owner == false.
- Russian language file contributed by "Cyrill Malevanov" cyrill#malevanov.spb.ru.
- Spanish language file contributed by "Horacio Degiorgi" horaciod#codigophp.com.
- 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.
- 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().
## 3.70 - 29 July 2003
- Added new SQLite driver. Tested on PHP 4.3 and PHP 5.
- Added limited "sapdb" driver support - mainly date support.
- The oci8 driver did not identify NUMBER with no defined precision correctly.
- Added ADODB_FORCE_NULLS, if set, then PHP nulls are converted to SQL nulls in GetInsertSQL/GetUpdateSQL.
- DBDate() and DBTimeStamp() format for postgresql had problems. Fixed.
- Added tableoptions to ChangeTableSQL(). Thx to Mike Benoit.
- Added charset support to postgresql. Thx to Julian Tarkhanov.
- Changed OS check for MS-Windows to prevent confusion with darWIN (MacOS)
- Timestamp format for db2 was wrong. Changed to yyyy-mm-dd-hh.mm.ss.nnnnnn.
- adodb-cryptsession.php includes wrong. Fixed.
- Added MetaForeignKeys(). Supported by mssql, odbc_mssql and oci8.
- Fixed some oci8 MetaColumns/MetaPrimaryKeys bugs. Thx to Walt Boring.
- adodb_getcount() did not init qryRecs to 0\. Missing "WHERE" clause checking in GetUpdateSQL fixed. Thx to Sebastiaan van Stijn.
- Added support for only 'VIEWS' and "TABLES" in MetaTables. From Walt Boring.
- Upgraded to adodb-xmlschema.inc.php 0.0.2.
- NConnect for mysql now returns value. Thx to Dennis Verspuij.
- ADODB_FETCH_BOTH support added to interbase/firebird.
- Czech language file contributed by Kamil Jakubovic jake#host.sk.
- PostgreSQL BlobDecode did not use _connectionID properly. Thx to Juraj Chlebec.
- Added some new initialization stuff for Informix. Thx to "Andrea Pinnisi" pinnisi#sysnet.it
- ADODB_ASSOC_CASE constant wrong in sybase _fetch(). Fixed.
## 3.60 - 16 June 2003
- We now SET CONCAT_NULL_YIELDS_NULL OFF for odbc_mssql driver to be compat with mssql driver.
- The property $emptyDate missing from connection class. Also changed 1903 to constant (TIMESTAMP_FIRST_YEAR=100). Thx to Sebastiaan van Stijn.
- ADOdb speedup optimization - we now return all arrays by reference.
- Now DBDate() and DBTimeStamp() now accepts the string 'null' as a parameter. Suggested by vincent.
- Added GetArray() to connection class.
- Added not_null check in informix metacolumns().
- Connection parameters for postgresql did not work correctly when port was defined.
- 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.
- The odbc driver's FetchField() field names did not obey ADODB_ASSOC_CASE. Fixed.
- Some bugs in adodb_backtrace() fixed.
- Added "INT IDENTITY" type to adorecordset::MetaType() to support odbc_mssql properly.
- MetaColumns() for oci8, mssql, odbc revised to support scale. Also minor revisions to odbc MetaColumns() for vfp and db2 compat.
- Added unsigned support to mysql datadict class. Thx to iamsure.
- Infinite loop in mssql MoveNext() fixed when ADODB_FETCH_ASSOC used. Thx to Josh R, Night_Wulfe#hotmail.com.
- ChangeTableSQL contributed by Florian Buzin.
- The odbc_mssql driver now sets CONCAT_NULL_YIELDS_NULL OFF for compat with mssql driver.
## 3.50 - 19 May 2003
- Fixed mssql compat with FreeTDS. FreeTDS does not implement mssql_fetch_assoc().
- Merged back connection and recordset code into adodb.inc.php.
- ADOdb sessions using oracle clobs contributed by achim.gosse#ddd.de. See adodb-session-clob.php.
- Added /s modifier to preg_match everywhere, which ensures that regex does not stop at /n. Thx Pao-Hsi Huang.
- Fixed error in metacolumns() for mssql.
- Added time format support for SQLDate.
- Image => B added to metatype.
- MetaType now checks empty($this->blobSize) instead of empty($this).
- Datadict has beta support for informix, sybase (mapped to mssql), db2 and generic (which is a fudge).
- BlobEncode for postgresql uses pg_escape_bytea, if available. Needed for compat with 7.3.
- Added $ADODB_LANG, to support multiple languages in MetaErrorMsg().
- Datadict can now parse table definition as declarative text.
- For DataDict, oci8 autoincrement trigger missing semi-colon. Fixed.
- For DataDict, when REPLACE flag enabled, drop sequence in datadict for autoincrement field in postgres and oci8.s
- Postgresql defaults to template1 database if no database defined in connect/pconnect.
- We now clear _resultid in postgresql if query fails.
## 3.40 - 19 May 2003
- Added insert_id for odbc_mssql.
- Modified postgresql UpdateBlobFile() because it did not work in safe mode.
- Now connection object is passed to raiseErrorFn as last parameter. Needed by StartTrans().
- Added StartTrans() and CompleteTrans(). It is recommended that you do not modify transOff, but use the above functions.
- oci8po now obeys ADODB_ASSOC_CASE settings.
- Added virtualized error codes, using PEAR DB equivalents. Requires you to manually include adodb-error.inc.php yourself, with MetaError() and MetaErrorMsg($errno).
- GetRowAssoc for mysql and pgsql were flawed. Fix by Ross Smith.
- Added to datadict types I1, I2, I4 and I8\. Changed datadict type 'T' to map to timestamp instead of datetime for postgresql.
- Error handling in ExecuteSQLArray(), adodb-datadict.inc.php did not work.
- We now auto-quote postgresql connection parameters when building connection string.
- Added session expiry notification.
- We now test with odbc mysql - made some changes to odbc recordset constructor.
- MetaColumns now special cases access and other databases for odbc.
## 3.31 - 17 March 2003
- Added row checking for _fetch in postgres.
- Added Interval type to MetaType for postgres.
- Remapped postgres driver to call postgres7 driver internally.
- Adorecordset_array::getarray() did not return array when nRows >= 0.
- Postgresql: at times, no error message returned by pg_result_error() but error message returned in pg_last_error(). Recoded again.
- Interbase blob's now use chunking for updateblob.
- Move() did not set EOF correctly. Reported by Jorma T.
- We properly support mysql timestamp fields when we are creating mysql tables using the data-dict interface.
- Table regex includes backticks character now.
## 3.30 - 3 March 2003
- Added $ADODB_EXTENSION and $ADODB_COMPAT_FETCH constant.
- Made blank1stItem configurable using syntax "value:text" in GetMenu/GetMenu2. Thx to Gabriel Birke.
- Previously ADOdb differed from the Microsoft standard because it did not define what to set $this->fields when EOF was reached. Now at EOF, ADOdb sets $this->fields to false for all databases, which is consist with Microsoft's implementation. Postgresql and mysql have always worked this way (in 3.11 and earlier). If you are experiencing compatibility problems (and you are not using postgresql nor mysql) on upgrading to 3.30, try setting the global variables $ADODB_COUNTRECS = true (which is the default) and $ADODB_FETCH_COMPAT = true (this is a new global variable).
- We now check both pg_result_error and pg_last_error as sometimes pg_result_error does not display anything. Iman Mayes
- We no longer check for magic quotes gpc in Quote().
- Misc fixes for table creation in adodb-datadict.inc.php. Thx to iamsure.
- Time calculations use adodb_time library for all negative timestamps due to problems in Red Hat 7.3 or later. Formerly, only did this for Windows.
- In mssqlpo, we now check if $sql in _query is a string before we change || to +. This is to support prepared stmts.
- Move() and MoveLast() internals changed to support to support EOF and $this->fields change.
- Added ADODB_FETCH_BOTH support to mssql. Thx to Angel Fradejas afradejas#mediafusion.es
- We now check if link resource exists before we run mysql_escape_string in qstr().
- Before we flock in csv code, we check that it is not a http url.
## 3.20 - 17 Feb 2003
- Added new Data Dictionary classes for creating tables and indexes. Warning - this is very much alpha quality code. The API can still change. See adodb/tests/test-datadict.php for more info.
- We now ignore $ADODB_COUNTRECS for mysql, because PHP truncates incomplete recordsets when mysql_unbuffered_query() is called a second time.
- Now postgresql works correctly when $ADODB_COUNTRECS = false.
- Changed _adodb_getcount to properly support SELECT DISTINCT.
- Discovered that $ADODB_COUNTRECS=true has some problems with prepared queries - suspect PHP bug.
- Now GetOne and GetRow run in $ADODB_COUNTRECS=false mode for better performance.
- Added support for mysql_real_escape_string() and pg_escape_string() in qstr().
- Added an intermediate variable for mysql _fetch() and MoveNext() to store fields, to prevent overwriting field array with boolean when mysql_fetch_array() returns false.
- Made arrays for getinsertsql and getupdatesql case-insensitive. Suggested by Tim Uckun" tim#diligence.com
## 3.11 - 11 Feb 2003
- Added check for ADODB_NEVER_PERSIST constant in PConnect(). If defined, then PConnect() will actually call non-persistent Connect().
- Modified interbase to properly work with Prepare().
- Added $this->ibase_timefmt to allow you to change the date and time format.
- Added support for $input_array parameter in CacheFlush().
- Added experimental support for dbx, which was then removed when i found that it was slower than using native calls.
- Added MetaPrimaryKeys for mssql and ibase/firebird.
- Added new $trim parameter to GetCol and CacheGetCol
- Uses updated adodb-time.inc.php 0.06.
## 3.10 - 27 Jan 2003
- Added adodb_date(), adodb_getdate(), adodb_mktime() and adodb-time.inc.php.
- For interbase, added code to handle unlimited number of bind parameters. From Daniel Hasan daniel#hasan.cl.
- Added BlobDecode and UpdateBlob for informix. Thx to Fernando Ortiz.
- Added constant ADODB_WINDOWS. If defined, means that running on Windows.
- Added constant ADODB_PHPVER which stores php version as a hex num. Removed $ADODB_PHPVER variable.
- Felho Bacsi reported a minor white-space regular expression problem in GetInsertSQL.
- Modified ADO to use variant to store _affectedRows
- Changed ibase to use base class Replace(). Modified base class Replace() to support ibase.
- Changed odbc to auto-detect when 0 records returned is wrong due to bad odbc drivers.
- Changed mssql to use datetimeconvert ini setting only when 4.30 or later (does not work in 4.23).
- ExecuteCursor($stmt, $cursorname, $params) now accepts a new $params array of additional bind parameters -- William Lovaton walovaton#yahoo.com.mx.
- Added support for sybase_unbuffered_query if ADODB_COUNTRECS == false. Thx to chuck may.
- Fixed FetchNextObj() bug. Thx to Jorma Tuomainen.
- We now use SCOPE_IDENTITY() instead of @@IDENTITY for mssql - thx to marchesini#eside.it
- Changed postgresql movenext logic to prevent illegal row number from being passed to pg_fetch_array().
- Postgresql initrs bug found by "Bogdan RIPA" bripa#interakt.ro $f1 accidentally named $f
## 3.00 - 6 Jan 2003
- Fixed adodb-pear.inc.php syntax error.
- Improved _adodb_getcount() to use SELECT COUNT(*) FROM ($sql) for languages that accept it.
- Fixed _adodb_getcount() caching error.
- Added sql to retrive table and column info for odbc_mssql.
+109
View File
@@ -0,0 +1,109 @@
## 4.990/5.05 - 11 Jul 2008
- Added support for multiple recordsets in mysqli Geisel Sierote <geisel#4up.com.br>. See http://phplens.com/lens/lensforum/msgs.php?id=15917
- Malcolm Cook added new Reload() function to Active Record. See http://phplens.com/lens/lensforum/msgs.php?id=17474
- Thanks Zoltan Monori [monzol#fotoprizma.hu] for bug fixes in iterator, SelectLimit, GetRandRow, etc.
- Under heavy loads, the performance monitor for oci8 disables Ixora views.
- Fixed sybase driver SQLDate to use str_replace(). Also for adodb5, changed sybase driver UnixDate and UnixTimeStamp calls to static.
- Changed oci8 lob handler to use &amp; reference $this-&gt;_refLOBs[$numlob]['VAR'] = &amp;$var.
- We now strtolower the get_class() function in PEAR::isError() for php5 compat.
- CacheExecute did not retrieve cache recordsets properly for 5.04 (worked in 4.98). Fixed.
- New ADODB_Cache_File class for file caching defined in adodb.inc.php.
- Farsi language file contribution by Peyman Hooshmandi Raad (phooshmand#gmail.com)
- New API for creating your custom caching class which is stored in $ADODB_CACHE:
```
include "/path/to/adodb.inc.php";
$ADODB_CACHE_CLASS = 'MyCacheClass';
class MyCacheClass extends ADODB_Cache_File
{
function writecache($filename, $contents,$debug=false){...}
function &readcache($filename, &$err, $secs2cache, $rsClass){ ...}
:
}
$DB = NewADOConnection($driver);
$DB->Connect(...); ## MyCacheClass created here and stored in $ADODB_CACHE global variable.
$data = $rs->CacheGetOne($sql); ## MyCacheClass is used here for caching...
```
- Memcache supports multiple pooled hosts now. Only if none of the pooled servers can be contacted will a connect error be generated. Usage example below:
```
$db = NewADOConnection($driver);
$db->memCache = true; /// should we use memCache instead of caching in files
$db->memCacheHost = array($ip1, $ip2, $ip3); /// $db->memCacheHost = $ip1; still works
$db->memCachePort = 11211; /// this is default memCache port
$db->memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
$db->Connect(...);
$db->CacheExecute($sql);
```
## 4.98/5.04 - 13 Feb 2008
- Fixed adodb_mktime problem which causes a performance bottleneck in $hrs.
- Added mysqli support to adodb_getcount().
- Removed MYSQLI_TYPE_CHAR from MetaType().
## 4.97/5.03 - 22 Jan 2008
- Active Record: $ADODB_ASSOC_CASE=1 did not work properly. Fixed.
- Modified Fields() in recordset class to support display null fields in FetchNextObject().
- In ADOdb5, active record implementation, we now support column names with spaces in them - we autoconvert the spaces to _ using __set(). Thx Daniel Cook. http://phplens.com/lens/lensforum/msgs.php?id=17200
- Removed $arg3 from mysqli SelectLimit. See http://phplens.com/lens/lensforum/msgs.php?id=16243. Thx Zsolt Szeberenyi.
- Changed oci8 FetchField, which returns the max_length of BLOB/CLOB/NCLOB as 4000 (incorrectly) to -1.
- CacheExecute would sometimes return an error on Windows if it was unable to lock the cache file. This is harmless and has been changed to a warning that can be ignored. Also adodb_write_file() code revised.
- ADOdb perf code changed to only log sql if execution time &gt;= 0.05 seconds. New $ADODB_PERF_MIN variable holds min sql timing. Any SQL with timing value below this and is not causing an error is not logged.
- Also adodb_backtrace() now traces 1 level deeper as sometimes actual culprit function is not displayed.
- Fixed a group by problem with adodb_getcount() for db's which are not postgres/oci8 based.
- Changed mssql driver Parameter() from SQLCHAR to SQLVARCHAR: case 'string': $type = SQLVARCHAR; break.
- Problem with mssql driver in php5 (for adodb 5.03) because some functions are not static. Fixed.
## 4.96/5.02 - 24 Sept 2007
ADOdb perf for oci8 now has non-table-locking code when clearing the sql. Slower but better transparency. Added in 4.96a and 5.02a.
Fix adodb count optimisation. Preg_match did not work properly. Also rewrote the ORDER BY stripping code in _adodb_getcount(), adodb-lib.inc.php.
SelectLimit for oci8 not optimal for large recordsets when offset=0. Changed $nrows check.
Active record optimizations. Added support for assoc arrays in Set().
Now GetOne returns null if EOF (no records found), and false if error occurs. Use ErrorMsg()/ErrorNo() to get the error.
Also CacheGetRow and CacheGetCol will return false if error occurs, or empty array() if EOF, just like GetRow and GetCol.
Datadict now allows changing of types which are not resizable, eg. VARCHAR to TEXT in ChangeTableSQL. -- Mateo Tibaquirá
Added BIT data type support to adodb-ado.inc.php and adodb-ado5.inc.php.
Ldap driver did not return actual ldap error messages. Fixed.
Implemented GetRandRow($sql, $inputarr). Optimized for Oci8.
Changed adodb5 active record to use static SetDatabaseAdapter() and removed php4 constructor. Bas van Beek bas.vanbeek#gmail.com.
Also in adodb5, changed adodb-session2 to use static function declarations in class. Thx Daniel Berlin.
Added "Clear SQL Log" to bottom of Performance screen.
Sessions2 code echo'ed directly to the screen in debug mode. Now uses ADOConnection::outp().
In mysql/mysqli, qstr(null) will return the string "null" instead of empty quoted string "''".
postgresql optimizeTable in perf-postgres.inc.php added by Daniel Berlin (mail#daniel-berlin.de)
Added 5.2.1 compat code for oci8.
Changed @@identity to SCOPE_IDENTITY() for multiple mssql drivers. Thx Stefano Nari.
Code sanitization introduced in 4.95 caused problems in European locales (as float 3.2 was typecast to 3,2). Now we only sanitize if is_numeric fails.
Added support for customizing ADORecordset_empty using $this-&gt;rsPrefix.'empty'. By Josh Truwin.
Added proper support for ALterColumnSQL for Postgresql in datadict code. Thx. Josh Truwin.
Added better support for MetaType() in mysqli when using an array recordset.
Changed parser for pgsql error messages in adodb-error.inc.php to case-insensitive regex.
## 4.95/5.01 - 17 May 2007
CacheFlush debug outp() passed in invalid parameters. Fixed.
Added Thai language file for adodb. Thx Trirat Petchsingh rosskouk#gmail.com
and Marcos Pont
Added zerofill checking support to MetaColumns for mysql and mysqli.
CacheFlush no longer deletes all files/directories. Only *.cache files
deleted.
DB2 timestamp format changed to var $fmtTimeStamp =
&quot;'Y-m-d-H:i:s'&quot;;
Added some code sanitization to AutoExecute in adodb-lib.inc.php.
Due to typo, all connections in adodb-oracle.inc.php would become
persistent, even non-persistent ones. Fixed.
Oci8 DBTimeStamp uses 24 hour time for input now, so you can perform string
comparisons between 2 DBTimeStamp values.
Some PHP4.4 compat issues fixed in adodb-session2.inc.php
For ADOdb 5.01, fixed some adodb-datadict.inc.php MetaType compat issues
with PHP5.
The $argHostname was wiped out in adodb-ado5.inc.php. Fixed.
Adodb5 version, added iterator support for adodb_recordset_empty.
Adodb5 version,more error checking code now will use exceptions if
available.
+722
View File
@@ -0,0 +1,722 @@
# ADOdb old Changelog - v4.x
See the [Current Changelog](changelog.md).
Older changelogs:
[v3.x](changelog_v3.x.md),
[v2.x](changelog_v2.x.md).
## 4.990 - 11 Jul 2008
- Added support for multiple recordsets in mysqli Geisel Sierote <geisel#4up.com.br>. See http://phplens.com/lens/lensforum/msgs.php?id=15917
- Malcolm Cook added new Reload() function to Active Record. See http://phplens.com/lens/lensforum/msgs.php?id=17474
- Thanks Zoltan Monori [monzol#fotoprizma.hu] for bug fixes in iterator, SelectLimit, GetRandRow, etc.
- Under heavy loads, the performance monitor for oci8 disables Ixora views.
- Fixed sybase driver SQLDate to use str_replace(). Also for adodb5, changed sybase driver UnixDate and UnixTimeStamp calls to static.
- Changed oci8 lob handler to use &amp; reference $this-&gt;_refLOBs[$numlob]['VAR'] = &amp;$var.
- We now strtolower the get_class() function in PEAR::isError() for php5 compat.
- CacheExecute did not retrieve cache recordsets properly for 5.04 (worked in 4.98). Fixed.
- New ADODB_Cache_File class for file caching defined in adodb.inc.php.
- Farsi language file contribution by Peyman Hooshmandi Raad (phooshmand#gmail.com)
- New API for creating your custom caching class which is stored in $ADODB_CACHE:
```
include "/path/to/adodb.inc.php";
$ADODB_CACHE_CLASS = 'MyCacheClass';
class MyCacheClass extends ADODB_Cache_File
{
function writecache($filename, $contents,$debug=false){...}
function &readcache($filename, &$err, $secs2cache, $rsClass){ ...}
:
}
$DB = NewADOConnection($driver);
$DB->Connect(...); ## MyCacheClass created here and stored in $ADODB_CACHE global variable.
$data = $rs->CacheGetOne($sql); ## MyCacheClass is used here for caching...
```
- Memcache supports multiple pooled hosts now. Only if none of the pooled servers can be contacted will a connect error be generated. Usage example below:
```
$db = NewADOConnection($driver);
$db->memCache = true; /// should we use memCache instead of caching in files
$db->memCacheHost = array($ip1, $ip2, $ip3); /// $db->memCacheHost = $ip1; still works
$db->memCachePort = 11211; /// this is default memCache port
$db->memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
$db->Connect(...);
$db->CacheExecute($sql);
```
## 4.98 - 13 Feb 2008
- Fixed adodb_mktime problem which causes a performance bottleneck in $hrs.
- Added mysqli support to adodb_getcount().
- Removed MYSQLI_TYPE_CHAR from MetaType().
## 4.97 - 22 Jan 2008
- Active Record: $ADODB_ASSOC_CASE=1 did not work properly. Fixed.
- Modified Fields() in recordset class to support display null fields in FetchNextObject().
- In ADOdb5, active record implementation, we now support column names with spaces in them - we autoconvert the spaces to `_` using `__set()`. Thx Daniel Cook. http://phplens.com/lens/lensforum/msgs.php?id=17200
- Removed $arg3 from mysqli SelectLimit. See http://phplens.com/lens/lensforum/msgs.php?id=16243. Thx Zsolt Szeberenyi.
- Changed oci8 FetchField, which returns the max_length of BLOB/CLOB/NCLOB as 4000 (incorrectly) to -1.
- CacheExecute would sometimes return an error on Windows if it was unable to lock the cache file. This is harmless and has been changed to a warning that can be ignored. Also adodb_write_file() code revised.
- ADOdb perf code changed to only log sql if execution time &gt;= 0.05 seconds. New $ADODB_PERF_MIN variable holds min sql timing. Any SQL with timing value below this and is not causing an error is not logged.
- Also adodb_backtrace() now traces 1 level deeper as sometimes actual culprit function is not displayed.
- Fixed a group by problem with adodb_getcount() for db's which are not postgres/oci8 based.
- Changed mssql driver Parameter() from SQLCHAR to SQLVARCHAR: case 'string': $type = SQLVARCHAR; break.
- Problem with mssql driver in php5 (for adodb 5.03) because some functions are not static. Fixed.
## 4.96 - 24 Sept 2007
- ADOdb perf for oci8 now has non-table-locking code when clearing the sql. Slower but better transparency. Added in 4.96a and 5.02a.
- Fix adodb count optimisation. Preg_match did not work properly. Also rewrote the ORDER BY stripping code in _adodb_getcount(), adodb-lib.inc.php.
- SelectLimit for oci8 not optimal for large recordsets when offset=0. Changed $nrows check.
- Active record optimizations. Added support for assoc arrays in Set().
- Now GetOne returns null if EOF (no records found), and false if error occurs. Use ErrorMsg()/ErrorNo() to get the error.
- Also CacheGetRow and CacheGetCol will return false if error occurs, or empty array() if EOF, just like GetRow and GetCol.
- Datadict now allows changing of types which are not resizable, eg. VARCHAR to TEXT in ChangeTableSQL. -- Mateo Tibaquirá
- Added BIT data type support to adodb-ado.inc.php and adodb-ado5.inc.php.
- Ldap driver did not return actual ldap error messages. Fixed.
- Implemented GetRandRow($sql, $inputarr). Optimized for Oci8.
- Changed adodb5 active record to use static SetDatabaseAdapter() and removed php4 constructor. Bas van Beek bas.vanbeek#gmail.com.
- Also in adodb5, changed adodb-session2 to use static function declarations in class. Thx Daniel Berlin.
- Added "Clear SQL Log" to bottom of Performance screen.
- Sessions2 code echo'ed directly to the screen in debug mode. Now uses ADOConnection::outp().
- In mysql/mysqli, qstr(null) will return the string "null" instead of empty quoted string "''".
- postgresql optimizeTable in perf-postgres.inc.php added by Daniel Berlin (mail#daniel-berlin.de)
- Added 5.2.1 compat code for oci8.
- Changed @@identity to SCOPE_IDENTITY() for multiple mssql drivers. Thx Stefano Nari.
- Code sanitization introduced in 4.95 caused problems in European locales (as float 3.2 was typecast to 3,2). Now we only sanitize if is_numeric fails.
- Added support for customizing ADORecordset_empty using $this-&gt;rsPrefix.'empty'. By Josh Truwin.
- Added proper support for ALterColumnSQL for Postgresql in datadict code. Thx. Josh Truwin.
- Added better support for MetaType() in mysqli when using an array recordset.
- Changed parser for pgsql error messages in adodb-error.inc.php to case-insensitive regex.
## 4.95 - 17 May 2007
- CacheFlush debug outp() passed in invalid parameters. Fixed.
- Added Thai language file for adodb. Thx Trirat Petchsingh rosskouk#gmail.com and Marcos Pont
- Added zerofill checking support to MetaColumns for mysql and mysqli.
- CacheFlush no longer deletes all files directories. Only `*.cache` files deleted.
- DB2 timestamp format changed to var $fmtTimeStamp = 'Y-m-d-H:i:s';
- Added some code sanitization to AutoExecute in adodb-lib.inc.php.
- Due to typo, all connections in adodb-oracle.inc.php would become persistent, even non-persistent ones. Fixed.
- Oci8 DBTimeStamp uses 24 hour time for input now, so you can perform string comparisons between 2 DBTimeStamp values.
- Some PHP4.4 compat issues fixed in adodb-session2.inc.php
- For ADOdb 5.01, fixed some adodb-datadict.inc.php MetaType compat issues with PHP5.
- The $argHostname was wiped out in adodb-ado5.inc.php. Fixed.
- Adodb5 version, added iterator support for adodb_recordset_empty.
- Adodb5 version,more error checking code now will use exceptions if available.
## 4.94 - 23 Jan 2007
- Active Record: $ADODB_ASSOC_CASE=2 did not work properly. Fixed. Thx gmane#auxbuss.com.
- mysqli had bugs in BeginTrans() and EndTrans(). Fixed.
- Improved error handling when no database is connected for oci8. Thx Andy Hassall.
- Names longer than 30 chars in oci8 datadict will be changed to random name. Thx Eugenio. http://phplens.com/lens/lensforum/msgs.php?id=16182
- Added var $upperCase = 'ucase' to access and ado_access drivers. Thx Renato De Giovanni renato#cria.org.br
- Postgres64 driver, if preparing plan failed in _query, did not handle error properly. Fixed. See http://phplens.com/lens/lensforum/msgs.php?id=16131.
- Fixed GetActiveRecordsClass() reference bug. See http://phplens.com/lens/lensforum/msgs.php?id=16120
- Added handling of nulls in adodb-ado_mssql.inc.php for qstr(). Thx to Felix Rabinovich.
- Adodb-dict contributions by Gaetano
- Support for INDEX in data-dict. Example: idx_ev1. The ability to define indexes using the INDEX keyword was added in ADOdb 4.94. The following example features mutiple indexes, including a compound index idx_ev1.
```
event_id I(11) NOTNULL AUTOINCREMENT PRIMARY,
event_type I(4) NOTNULL
event_start_date T DEFAULT NULL **INDEX id_esd**,
event_end_date T DEFAULT '0000-00-00 00:00:00' **INDEX id_eted**,
event_parent I(11) UNSIGNED NOTNULL DEFAULT 0 **INDEX id_evp**,
event_owner I(11) DEFAULT 0 **INDEX idx_ev1**,
event_project I(11) DEFAULT 0 **INDEX idx_ev1**,
event_times_recuring I(11) UNSIGNED NOTNULL DEFAULT 0,
event_icon C(20) DEFAULT 'obj/event',
event_description X
```
- Prevents the generated SQL from including double drop-sequence statements for REPLACE case of tables with autoincrement columns (on those dbs that emulate it via sequences)
- makes any date defined as DEFAULT value for D and T columns work cross-database, not just the "sysdate" value (as long as it is specified using adodb standard format). See above example.
- Fixed pdo's GetInsertID() support. Thx Ricky Su.
- oci8 Prepare() now sets error messages if an error occurs.
- Added 'PT_BR' to SetDateLocale() -- brazilian portugese.
- charset in oci8 was not set correctly on `*Connect()`
- ADOConnection::Transpose() now appends as first column the field names.
- Added $ADODB_QUOTE_FIELDNAMES. If set to true, will autoquote field names in AutoExecute(),GetInsertSQL(), GetUpdateSQL().
- Transpose now adds the field names as the first column after transposition.
- Added === check in ADODB_SetDatabaseAdapter for $db, adodb-active-record.inc.php. Thx Christian Affolter.
- Added ErrorNo() to adodb-active-record.inc.php. Thx ante#novisplet.com.
## 4.93 - 10 Oct 2006
- Added support for multiple database connections in performance monitoring code (adodb-perf.inc.php). Now all sql in multiple database connections can be saved into one database ($ADODB_LOG_CONN).
- Added MetaIndexes() to odbc_mssql.
- Added connection property $db->null2null = 'null'. In autoexecute/getinsertsql/getupdatesql, this value will be converted to a null. Set this to a funny invalid value if you do not want null conversion. See http://phplens.com/lens/lensforum/msgs.php?id=15902.
- Path disclosure problem in mysqli fixed. Thx Andy.
- Fixed typo in session_schema2.xml.
- Changed INT in oci8 to return correct precision in $fld->max_length, MetaColumns(). Thx Eloy Lafuente Plaza.
- Patched postgres64 _connect to handle serverinfo(). see http://phplens.com/lens/lensforum/msgs.php?id=15887.
- Added pdo fix for null columns. See http://phplens.com/lens/lensforum/msgs.php?id=15889
- For stored procedures, missing connection id now passed into mssql_query(). Thx Ecsy (ecsy#freemail.hu).
## 4.92a - 30 Aug 2006
- Syntax error in postgres7 driver. Thx Eloy Lafuente Plaza.
- Minor bug fixes - adodb informix 10 types added to adodb.inc.php. Thx Fernando Ortiz.
## 4.92 - 29 Aug 2006
- Better odbtp date support.
- Added IgnoreErrors() to bypass default error handling.
- The _adodb_getcount() function in adodb-lib.inc.php, some ORDER BY bug fixes.
- For ibase and firebird, set $sysTimeStamp = "CURRENT_TIMESTAMP".
- Fixed postgres connection bug: http://phplens.com/lens/lensforum/msgs.php?id=11057.
- Changed CacheSelectLimit() to flush cache when $secs2cache==-1 due to complaints from other users.
- Added support for using memcached with CacheExecute/CacheSelectLimit. Requires memcache module PECL extension. Usage:
```
$db = NewADOConnection($driver);
$db->memCache = true; /// should we use memCache instead of caching in files
$db->memCacheHost = "126.0.1.1"; /// memCache host
$db->memCachePort = 11211; /// this is default memCache port
$db->memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
$db->Connect(...);
$db->CacheExecute($sql);
```
- Implemented Transpose() for recordsets. Recordset must be retrieved using ADODB_FETCH_NUM. First column becomes the column name.
```
$db = NewADOConnection('mysql');
$db->Connect(...);
$db->SetFetchMode(ADODB_FETCH_NUM);
$rs = $db->Execute('select productname,productid,unitprice from products limit 10');
$rs2 = $db->Transpose($rs);
rs2html($rs2);
```
## 4.91 - 2 Aug 2006
- Major session code rewrite... See session docs.
- PDO bindinputarray() was not set properly for MySQL (changed from true to false).
- Changed CacheSelectLimit() to re-cache when $secs2cache==0. This is one way to flush the cache when SelectLimit is called.
- Added to quotes to mysql and mysqli: "SHOW COLUMNS FROM \`%s\`";
- Removed accidental optgroup handling in GetMenu(). Fixed ibase _BlobDecode for php5 compat, and also mem alloc issues for small blobs, thx salvatori#interia.pl
- Mysql driver OffsetDate() speedup, useful for adodb-sessions.
- Fix for GetAssoc() PHP5 compat. See http://phplens.com/lens/lensforum/msgs.php?id=15425
- Active Record - If inserting a record and the value of a primary key field is null, then we do not insert that field in as we assume it is an auto-increment field. Needed by mssql.
- Changed postgres7 MetaForeignKeys() see http://phplens.com/lens/lensforum/msgs.php?id=15531
- DB2 will now return db2_conn_errormsg() when it is a connection error.
## 4.90 - 8 June 2006
- Changed adodb_countrec() in adodb-lib.inc.php to allow LIMIT to be used as a speedup to reduce no of records counted.
- Added support for transaction modes for postgres and oci8 with SetTransactionMode(). These transaction modes affect all subsequent transactions of that connection.
- Thanks to Halmai Csongor for suggestion.
- Removed `$off = $fieldOffset - 1` line in db2 driver, FetchField(). Tx Larry Menard.
- Added support for PHP5 objects as Execute() bind parameters using `__toString` (eg. Simple-XML). Thx Carl-Christian Salvesen.
- Rounding in tohtml.inc.php did not work properly. Fixed.
- MetaIndexes in postgres fails when fields are deleted then added in again because the attnum has gaps in it. See http://sourceforge.net/tracker/index.php?func=detail&aid=1451245&group_id=42718&atid=433976. Fixed.
- MetaForeignkeys in mysql and mysqli did not work when fetchMode==ADODB_FETCH_ASSOC used. Fixed.
- Reference error in AutoExecute() fixed.
- Added macaddr postgres type to MetaType. Maps to 'C'.
- Added to `_connect()` in adodb-ado5.inc.php support for $database and $dataProvider parameters. Thx Larry Menard.
- Added support for sequences in adodb-ado_mssql.inc.php. Thx Larry Menard.
- Added ADODB_SESSION_READONLY.
- Added session expiryref support to crc32 mode, and in LOB code.
- Clear `_errorMsg` in postgres7 driver, so that ErrorMsg() displays properly when no error occurs.
- Added BindDate and BindTimeStamp
## 4.81 - 3 May 2006
- Fixed variable ref errors in adodb-ado5.inc.php in _query().
- Mysqli setcharset fix using method_exists().
- The adodb-perf.inc.php CreateLogTable() code now works for user-defined table names.
- Error in ibase_blob_open() fixed. See http://phplens.com/lens/lensforum/msgs.php?id=14997
## 4.80 - 8 Mar 2006
- Added activerecord support.
- Added mysql `$conn->compat323 = true` if you want MySQL 3.23 compat enabled. Fixes GetOne() Select-Limit problems.
- Added adodb-xmlschema03.inc.php to support XML Schema version 3 and updated adodb-datadict.htm docs.
- Better memory management in Execute. Thx Mike Fedyk.
## 4.72 - 21 Feb 2006
- Added 'new' DSN parameter for NConnect().
- Pager now sanitizes $PHP_SELF to protect against XSS. Thx to James Bercegay and others.
- ADOConnection::MetaType changed to setup $rs->connection correctly.
- New native DB2 driver contributed by Larry Menard, Dan Scott, Andy Staudacher, Bharat Mediratta.
- The mssql CreateSequence() did not BEGIN TRANSACTION correctly. Fixed. Thx Sean Lee.
- The _adodb_countrecs() function in adodb-lib.inc.php has been revised to handle more ORDER BY variations.
## 4.71 - 24 Jan 2006
- Fixes postgresql security issue related to binary strings. Thx to Andy Staudacher.
- Several DSN bugs found:
1. Fix bugs in DSN connections introduced in 4.70 when underscores are found in the DSN.
2. DSN with _ did not work properly in PHP5 (fine in PHP4). Fixed.
3. Added support for PDO DSN connections in NewADOConnection(), and database parameter in PDO::Connect().
- The oci8 datetime flag not correctly implemented in ADORecordSet_array. Fixed.
- Added BlobDelete() to postgres, as a counterpoint to UpdateBlobFile().
- Fixed GetInsertSQL() to support oci8po.
- Fixed qstr() issue with postgresql with \0 in strings.
- Fixed some datadict driver loading issues in _adodb_getdriver().
- Added register shutdown function session_write_close in adodb-session.inc.php for PHP 5 compat. See http://phplens.com/lens/lensforum/msgs.php?id=14200.
## 4.70 - 6 Jan 2006
- Many fixes from Danila Ulyanov to ibase, oci8, postgres, mssql, odbc_oracle, odbtp, etc drivers.
- Changed usage of binary hint in adodb-session.inc.php for mysql. See http://phplens.com/lens/lensforum/msgs.php?id=14160
- Fixed invalid variable reference problem in undomq(), adodb-perf.inc.php.
- Fixed http://phplens.com/lens/lensforum/msgs.php?id=14254 in adodb-perf.inc.php, `_DBParameter()` settings of fetchmode was wrong.
- Fixed security issues in server.php and tmssql.php discussed by Andreas Sandblad in a Secunia security advisory. Added `$ACCEPTIP = 127.0.0.1` and changed suggested root password to something more secure.
- Changed pager to close recordset after RenderLayout().
## 4.68 - 25 Nov 2005
- PHP 5 compat for mysqli. MetaForeignKeys repeated twice and MYSQLI_BINARY_FLAG missing.
- PHP 5.1 support for postgresql bind parameters using ? did not work if >= 10 parameters. Fixed. Thx to Stanislav Shramko.
- Lots of PDO improvements.
- Spelling error fixed in mysql MetaForeignKeys, $associative parameter.
## 4.67 - 16 Nov 2005
- Postgresql not_null flag not set to false correctly. Thx Cristian MARIN.
- We now check in Replace() if key is in fieldArray. Thx Sébastien Vanvelthem.
- `_file_get_contents()` function was missing in xmlschema. fixed.
- Added week in year support to SQLDate(), using 'W' flag. Thx Spider.
- In sqlite metacolumns was repeated twice, causing PHP 5 problems. Fixed.
- Made debug output XHTML compliant.
## 4.66 - 28 Sept 2005
- ExecuteCursor() in oci8 did not clean up properly on failure. Fixed.
- Updated xmlschema.dtd, by "Alec Smecher" asmecher#smecher.bc.ca
- Hardened SelectLimit, typecasting nrows and offset to integer.
- Fixed misc bugs in AutoExecute() and GetInsertSQL().
- Added $conn->database as the property holding the database name. The older $conn->databaseName is retained for backward compat.
- Changed _adodb_backtrace() compat check to use function_exists().
- Bug in postgresql MetaIndexes fixed. Thx Kevin Jamieson.
- Improved OffsetDate for MySQL, reducing rounding error.
- Metacolumns added to sqlite. Thx Mark Newnham.
- PHP 4.4 compat fixes for GetAssoc().
- Added postgresql bind support for php 5.1. Thx Cristiano da Cunha Duarte
- OffsetDate() fixes for postgresql, typecasting strings to date or timestamp.
- DBTimeStamp formats for mssql, odbc_mssql and postgresql made to conform with other db's.
- Changed PDO constants from PDO_ to PDO:: to support latest spec.
## 4.65 - 22 July 2005
- Reverted 'X' in mssql datadict to 'TEXT' to be compat with mssql driver. However now you can set $datadict->typeX = 'varchar(4000)' or 'TEXT' or 'CLOB' for mssql and oci8 drivers.
- Added charset support when using DSN for Oracle.
- _adodb_getmenu did not use fieldcount() to get number of fields. Fixed.
- MetaForeignKeys() for mysql/mysqli contributed by Juan Carlos Gonzalez.
- MetaDatabases() now correctly returns an array for mysqli driver. Thx Cristian MARIN.
- CompleteTrans(false) did not return false. Fixed. Thx to JMF.
- AutoExecute() did not work with Oracle. Fixed. Thx José Moreira.
- MetaType() added to connection object.
- More PHP 4.4 reference return fixes. Thx Ryan C Bonham and others.
## 4.64 - 20 June 2005
- In datadict, if the default field value is set to '', then it is not applied when the field is created. Fixed by Eugenio.
- MetaPrimaryKeys for postgres did not work because of true/false change in 4.63. Fixed.
- Tested ocifetchstatement in oci8. Rejected at the end.
- Added port to dsn handling. Supported in postgres, mysql, mysqli,ldap.
- Added 'w' and 'l' to mysqli SQLDate().
- Fixed error handling in ldap _connect() to be more consistent. Also added ErrorMsg() handling to ldap.
- Added support for union in _adodb_getcount, adodb-lib.inc.php for postgres and oci8.
- rs2html() did not work with null dates properly.
- PHP 4.4 reference return fixes.
## 4.63 - 18 May 2005
- Added $nrows<0 check to mysqli's SelectLimit().
- Added OptimizeTable() and OptimizeTables() in adodb-perf.inc.php. By Markus Staab.
- PostgreSQL inconsistencies fixed. true and false set to TRUE and FALSE, and boolean type in datadict-postgres.inc.php set to 'L' => 'BOOLEAN'. Thx Kevin Jamieson.
- New adodb_session_create_table() function in adodb-session.inc.php. By Markus Staab.
- Added null check to UserTimeStamp().
- Fixed typo in mysqlt driver in adorecordset. Thx to Andy Staudacher.
- GenID() had a bug in the raiseErrorFn handling. Fixed. Thx Marcos Pont.
- Datadict name quoting now handles ( ) in index fields correctly - they aren't part of the index field.
- Performance monitoring:
1. oci8 Ixora checks moved down;
2. expensive sql changed so that only those sql with count(*)>1 are shown;
3. changed sql1 field to a length+crc32 checksum - this breaks backward compat.
- We remap firebird15 to firebird in data dictionary.
## 4.62 - 2 Apr 2005
- Added 'w' (dow as 0-6 or 1-7) and 'l' (dow as string) for SQLDate for oci8, postgres and mysql.
- Rolled back MetaType() changes for mysqli done in prev version.
- Datadict change by chris, cblin#tennaxia.com data mappings from:
```
oci8: X->varchar(4000) XL->CLOB
mssql: X->XL->TEXT
mysql: X->XL->LONGTEXT
fbird: X->XL->varchar(4000)
```
to:
```
oci8: X->varchar(4000) XL->CLOB
mssql: X->VARCHAR(4000) XL->TEXT
mysql: X->TEXT XL->LONGTEXT
fbird: X->VARCHAR(4000) XL->VARCHAR(32000)
```
- Added $connection->disableBlobs to postgresql to improve performance when no bytea is used (2-5% improvement).
- Removed all HTTP_* vars.
- Added $rs->tableName to be set before calling AutoExecute().
- Alex Rootoff rootoff#pisem.net contributed ukrainian language file.
- Added new mysql_option() support using $conn->optionFlags array.
- Added support for ldap_set_option() using the $LDAP_CONNECT_OPTIONS global variable. Contributed by Josh Eldridge.
- Added LDAP_* constant definitions to ldap.
- Added support for boolean bind variables. We use $conn->false and $conn->true to hold values to set false/true to.
- We now do not close the session connection in adodb-session.inc.php as other objects could be using this connection.
- We now strip off `\0` at end of Ixora SQL strings in $perf->tohtml() for oci8.
## 4.61 - 23 Feb 2005
- MySQLi added support for mysqli_connect_errno() and mysqli_connect_error().
- Massive improvements to alpha PDO driver.
- Quote string bind parameters logged by performance monitor for easy type checking. Thx Jason Judge.
- Added support for $role when connecting with Interbase/firebird.
- Added support for enum recognition in MetaColumns() mysql and mysqli. Thx Amedeo Petrella.
- The sybase_ase driver contributed by Interakt Online. Thx Cristian Marin cristic#interaktonline.com.
- Removed not_null, has_default, and default_value from ADOFieldObject.
- Sessions code, fixed quoting of keys when handling LOBs in session write() function.
- Sessions code, added adodb_session_regenerate_id(), to reduce risk of session hijacking by changing session cookie dynamically. Thx Joe Li.
- Perf monitor, polling for CPU did not work for PHP 4.3.10 and 5.0.0-5.0.3 due to PHP bugs, so we special case these versions.
- Postgresql, UpdateBlob() added code to handle type==CLOB.
## 4.60 - 24 Jan 2005
- Implemented PEAR DB's autoExecute(). Simplified design because I don't like using constants when strings work fine.
- _rs2serialize will now update $rs->sql and $rs->oldProvider.
- Added autoExecute().
- Added support for postgres8 driver. Currently just remapped to postgres7 driver.
- Changed oci8 _query(), so that OCIBindByName() sets the length to -1 if element size is > 4000. This provides better support for LONGs.
- Added SetDateLocale() support for netherlands (Nl).
- Spelling error in pivot code ($iff should be $iif).
- mysql insert_id() did not work with mysql 3.x. Fixed.
- `\r\n` not converted to spaces correctly in exporting data. Fixed.
- _nconnect() in mysqli did not return value correctly. Fixed.
- Arne Eckmann contributed danish language file.
- Added clone() support to FetchObject() for PHP5.
- Removed SQL_CUR_USE_ODBC from odbc_mssql.
## 4.55 - 5 Jan 2005
- Found bug in Execute() with bind params for db's that do not support binding natively.
- DropSequence() now correctly uses default parameter.
- Now Execute() ignores locale for floats, so 1.23 is NEVER converted to 1,23.
- SetFetchMode() not properly saved in adodb-perf, suspicious sql and expensive sql. Fixed.
- Added INET to postgresql metatypes. Thx motzel.
- Allow oracle hints to work when counting with _adodb_getcount in adodb-lib.inc.php. Thx Chris Wrye.
- Changed mysql insert_id() to use SELECT LAST_INSERT_ID().
- If alter col in datadict does not modify col type/size of actual col, then it is removed from alter col code. By Mark Newham. Not perfect as MetaType() !== ActualType().
- Added handling of view fields in metacolumns() for postgresql. Thx Renato De Giovanni.
- Added to informix MetaPrimaryKeys and MetaColumns fixes for null bit. Thx to Cecilio Albero.
- Removed obsolete connection_timeout() from perf code.
- Added support for arrayClass in adodb-csv.inc.php.
- RSFilter now accepts methods of the form $array($obj, 'methodname'). Thx to blake#near-time.com.
- Changed CacheFlush to `$cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/';`
- For better cursor concurrency, added code to free ref cursors in oci8 when $rs->Close() is called. Note that CLose() is called internally by the Get* functions too.
- Added IIF support for access when pivoting. Thx Volodia Krupach.
- Added mssql datadict support for timestamp. Thx Alexios.
- Informix pager fix. By Mario Ramirez.
- ADODB_TABLE_REGEX now includes ':'. By Mario Ramirez.
- Mark Newnham contributed MetaIndexes for oci8 and db2.
## 4.54 - 5 Nov 2004
- Now you can set $db->charSet = ?? before doing a Connect() in oci8.
- Added adodbFetchMode to sqlite.
- Perf code, added a string typecast to substr in adodb_log_sql().
- Postgres: Changed BlobDecode() to use po_loread, added new $maxblobsize parameter, and now it returns the blob instead of sending it to stdout - make sure to mention that as a compat warning. Also added $db->IsOID($oid) function; uses a heuristic, not guaranteed to work 100%.
- Contributed arabic language file by "El-Shamaa, Khaled" k.el-shamaa#cgiar.org
- PHP5 exceptions did not handle @ protocol properly. Fixed.
- Added ifnull handling for postgresql (using coalesce).
- Added metatables() support for Postgresql 8.0 (no longer uses pg_% dictionary tables).
- Improved Sybase ErrorMsg() function. By Gaetano Giunta.
- Improved oci8 SelectLimit() to use Prepare(). By Cristiano Duarte.
- Type-cast $row parameter in ifx_fetch_row() to int. Thx stefan bodgan.
- Ralf becker contributed improvements in postgresql, sapdb, mysql data dictionary handling:
- MySql and Postgres MetaType was reporting every int column which was part of a primary key and unique as serial
- Postgres was not reporting the scale of decimal types
- MaxDB was padding the defaults of none-string types with spaces
- MySql now correctly converts enum columns to varchar
- Ralf also changed Postgresql datadict:
- you cant add NOT NULL columns in postgres in one go, they need to be added as NULL and then altered to NOT NULL
- AlterColumnSQL could not change a varchar column with numbers into an integer column, postgres need an explicit conversation
- a re-created sequence was not set to the correct value, if the name was the old name (no implicit sequence), now always the new name of the implicit sequence is used
- Sergio Strampelli added extra $intoken check to Lens_ParseArgs() in datadict code.
## 4.53 - 28 Sept 2004
- FetchMode cached in recordset is sometimes mapped to native db fetchMode. Normally this does not matter, but when using cached recordsets, we need to switch back to using adodb fetchmode. So we cache this in $rs->adodbFetchMode if it differs from the db's fetchMode.
- For informix we now set canSeek = false driver because stefan bodgan tells me that seeking doesn't work.
- SetDateLocale() never worked till now ;-) Thx david#tomato.it
- Set $_bindInputArray = true in sapdb driver. Required for clob support.
- Fixed some PEAR::DB emulation issues with isError() and isWarning. Thx to Gert-Rainer Bitterlich.
- Empty() used in getupdatesql without strlen() check. Fixed.
- Added unsigned detection to mysql and mysqli drivers. Thx to dan cech.
- Added hungarian language file. Thx to Halászvári Gábor.
- Improved fieldname-type formatting of datadict SQL generated (adding $widespacing parameter to _GenField).
- Datadict oci8 DROP CONSTRAINTS misspelt. Fixed. Thx Mark Newnham.
- Changed odbtp to dynamically change databaseType based on connection, eg. from 'odbtp' to 'odbtp_mssql' when connecting to mssql database.
- In datadict, MySQL I4 was wrongly mapped to MEDIUMINT, which is actually I3. Fixed.
- Fixed mysqli MetaType() recognition. Mysqli returns numeric types unlike mysql extension. Thx Francesco Riosa.
- VFP odbc driver curmode set wrongly, causing problems with memo fields. Fixed.
- Odbc driver did not recognize odbc version 2 driver date types properly. Fixed. Thx Bostjan.
- ChangeTableSQL() fixes to datadict-db2.inc.php by Mark Newnham.
- Perf monitoring with odbc improved. Now we try in perf code to manually set the sysTimeStamp using date() if sysTimeStamp is empty.
- All ADO errors are thrown as exceptions in PHP5. So we added exception handling to ado in PHP5 by creating new adodb-ado5.inc.php driver.
- Added IsConnected(). Returns true if connection object connected. By Luca.Gioppo.
- "Ralf Becker" RalfBecker#digitalROCK.de contributed new sapdb data-dictionary driver and a large patch that implements field and table renaming for oracle, mssql, postgresql, mysql and sapdb. See the new RenameTableSQL() and RenameColumnSQL() functions.
- We now check ExecuteCursor to see if PrepareSP was initially called.
- Changed oci8 datadict to use MODIFY for $dd->alterCol. Thx Mark Newnham.
## 4.52 - 10 Aug 2004
- Bug found in Replace() when performance logging enabled, introduced in ADOdb 4.50. Fixed.
- Replace() checks update stmt. If update stmt fails, we now return immediately. Thx to alex.
- Added support for $ADODB_FORCE_TYPE in GetUpdateSQL/GetInsertSQL. Thx to niko.
- Added ADODB_ASSOC_CASE support to postgres/postgres7 driver.
- Support for DECLARE stmt in oci8. Thx Lochbrunner.
## 4.51 - 29 July 2004
- Added adodb-xmlschema 1.0.2. Thx dan and richard.
- Added new adorecordset_ext_* classes. If ADOdb extension installed for mysql, mysqlt and oci8 (but not oci8po), we use the superfast ADOdb extension code for movenext.
- Added schema support to mssql and odbc_mssql MetaPrimaryKeys().
- Patched MSSQL driver to support PHP NULL and Boolean values while binding the input array parameters in the _query() function. By Stephen Farmer.
- Added support for clob's for mssql, UpdateBlob(). Thx to gfran#directa.com.br
- Added normalize support for postgresql (true=lowercase table name, or false=case-sensitive table names) to MetaColumns($table, $normalize=true).
- PHP5 variant dates in ADO not working. Fixed in adodb-ado.inc.php.
- Constant ADODB_FORCE_NULLS was not working properly for many releases (for GetUpdateSQL). Fixed. Also GetUpdateSQL strips off ORDER BY now - thx Elieser Leão.
- Perf Monitor for oci8 now dynamically highlights optimizer_* params if too high/low.
- Added dsn support to NewADOConnection/ADONewConnection.
- Fixed out of page bounds bug in _adodb_pageexecute_all_rows() Thx to "Sergio Strampelli" sergio#rir.it
- Speedup of movenext for mysql and oci8 drivers.
- Moved debugging code _adodb_debug_execute() to adodb-lib.inc.php.
- Fixed postgresql bytea detection bug. See http://phplens.com/lens/lensforum/msgs.php?id=9849.
- Fixed ibase datetimestamp typo in PHP5. Thx stefan.
- Removed whitespace at end of odbtp drivers.
- Added db2 metaprimarykeys fix.
- Optimizations to MoveNext() for mysql and oci8. Misc speedups to Get* functions.
## 4.50 - 6 July 2004
- Bumped it to 4.50 to avoid confusion with PHP 4.3.x series.
- Added db2 metatables and metacolumns extensions.
- Added alpha PDO driver. Very buggy, only works with odbc.
- Tested mysqli. Set poorAffectedRows = true. Cleaned up movenext() and _fetch().
- PageExecute does not work properly with php5 (return val not a variable). Reported Dmytro Sychevsky sych#php.com.ua. Fixed.
- MetaTables() for mysql, $showschema parameter was not backward compatible with older versions of adodb. Fixed.
- Changed mysql GetOne() to work with mysql 3.23 when using with non-select stmts (e.g. SHOW TABLES).
- Changed TRIG_ prefix to a variable in datadict-oci8.inc.php. Thx to Luca.Gioppo#csi.it.
- New to adodb-time code. We allow you to define your own daylights savings function, adodb_daylight_sv for pre-1970 dates. If the function is defined (somewhere in an include), then you can correct for daylights savings. See http://phplens.com/phpeverywhere/node/view/16#daylightsavings for more info.
- New sqlitepo driver. This is because assoc mode does not work like other drivers in sqlite. Namely, when selecting (joining) multiple tables, in assoc mode the table names are included in the assoc keys in the "sqlite" driver. In "sqlitepo" driver, the table names are stripped from the returned column names. When this results in a conflict, the first field get preference. Contributed by Herman Kuiper herman#ozuzo.net
- Added $forcenull parameter to GetInsertSQL/GetUpdateSQL. Idea by Marco Aurelio Silva.
- More XHTML changes for GetMenu. By Jeremy Evans.
- Fixes some ibase date issues. Thx to stefan bogdan.
- Improvements to mysqli driver to support $ADODB_COUNTRECS.
- Fixed adodb-csvlib.inc.php problem when reading stream from socket. We need to poll stream continiously.
## 4.23 - 16 June 2004
- New interbase/firebird fixes thx to Lester Caine. Driver fixes a problem with getting field names in the result array, and corrects a couple of data conversions. Also we default to dialect3 for firebird. Also ibase sysDate property was wrong. Changed to cast as timestamp.
- The datadict driver is set up to give quoted tables and fields as this was the only way round reserved words being used as field names in TikiWiki. TikiPro is tidying that up, and I hope to be able to produce a build of THAT which uses what I consider proper UPPERCASE field and table names. The conversion of TikiWiki to ADOdb helped in that, but until the database is completely tidied up in TikiPro ...
- Modified _gencachename() to include fetchmode in name hash. This means you should clear your cache directory after installing this release as the cache name algorithm has changed.
- Now Cache* functions work in safe mode, because we do not create sub-directories in the $ADODB_CACHE_DIR in safe mode. In non-safe mode we still create sub-directories. Done by modifying _gencachename().
- Added $gmt parameter (true/false) to UserDate and UserTimeStamp in connection class, to force conversion of input (in local time) to be converted to UTC/GMT.
- Mssql datadict did not support INT types properly (no size param allowed). Added _GetSize() to datadict-mssql.inc.php.
- For borland_ibase, BeginTrans(), changed:
```
$this->_transactionID = $this->_connectionID;
```
to
```
$this->_transactionID = ibase_trans($this->ibasetrans, $this->_connectionID);
```
- Fixed typo in mysqi_field_seek(). Thx to Sh4dow (sh4dow#php.pl).
- LogSQL did not work with Firebird/Interbase. Fixed.
- Postgres: made errorno() handling more consistent. Thx to Michael Jahn, Michael.Jahn#mailbox.tu-dresden.de.
- Added informix patch to better support metatables, metacolumns by "Cecilio Albero" c-albero#eos-i.com
- Cyril Malevanov contributed patch to oci8 to support passing of LOB parameters:
```
$text = 'test test test';
$sql = "declare rs clob; begin :rs := lobinout(:sa0); end;";
$stmt = $conn -> PrepareSP($sql);
$conn -> InParameter($stmt,$text,'sa0', -1, OCI_B_CLOB);
$rs = '';
$conn -> OutParameter($stmt,$rs,'rs', -1, OCI_B_CLOB);
$conn -> Execute($stmt);
echo "return = ".$rs."<br>";</pre>
```
As he says, the LOBs limitations are:
- use OCINewDescriptor before binding
- if Param is IN, uses save() before each execute. This is done automatically for you.
- if Param is OUT, uses load() after each execute. This is done automatically for you.
- when we bind $var as LOB, we create new descriptor and return it as a Bind Result, so if we want to use OUT parameters, we have to store somewhere &$var to load() data from LOB to it.
- IN OUT params are not working now (should not be a big problem to fix it)
- now mass binding not working too (I've wrote about it before)</pre>
- Simplified Connect() and PConnect() error handling.
- When extension not loaded, Connect() and PConnect() will return null. On connect error, the fns will return false.
- CacheGetArray() added to code.
- Added Init() to adorecordset_empty().
- Changed postgres64 driver, MetaColumns() to not strip off quotes in default value if :: detected (type-casting of default).
- Added test: if (!defined('ADODB_DIR')) die(). Useful to prevent hackers from detecting file paths.
- Changed metaTablesSQL to ignore Postgres 7.4 information schemas (sql_*).
- New polish language file by Grzegorz Pacan
- Added support for UNION in _adodb_getcount().
- Added security check for ADODB_DIR to limit path disclosure issues. Requested by postnuke team.
- Added better error message support to oracle driver. Thx to Gaetano Giunta.
- Added showSchema support to mysql.
- Bind in oci8 did not handle $name=false properly. Fixed.
- If extension not loaded, Connect(), PConnect(), NConnect() will return null.
## 4.22 - 15 Apr 2004
- Moved docs to own adodb/docs folder.
- Fixed session bug when quoting compressed/encrypted data in Replace().
- Netezza Driver and LDAP drivers contributed by Josh Eldridge.
- GetMenu now uses rtrim() on values instead of trim().
- Changed MetaColumnNames to return an associative array, keys being the field names in uppercase.
- Suggested fix to adodb-ado.inc.php affected_rows to support PHP5 variants. Thx to Alexios Fakos.
- Contributed bulgarian language file by Valentin Sheiretsky valio#valio.eu.org.
- Contributed romanian language file by stefan bogdan.
- GetInsertSQL now checks for table name (string) in $rs, and will create a recordset for that table automatically. Contributed by Walt Boring. Also added OCI_B_BLOB in bind on Walt's request - hope it doesn't break anything :-)
- Some minor postgres speedups in `_initrs()`.
- ChangeTableSQL checks now if MetaColumns returns empty. Thx Jason Judge.
- Added ADOConnection::Time(), returns current database time in unix timestamp format, or false.
## 4.21 - 20 Mar 2004
- We no longer in SelectLimit for VFP driver add SELECT TOP X unless an ORDER BY exists.
- Pim Koeman contributed dutch language file adodb-nl.inc.php.
- Rick Hickerson added CLOB support to db2 datadict.
- Added odbtp driver. Thx to "stefan bogdan" sbogdan#rsb.ro.
- Changed PrepareSP() 2nd parameter, $cursor, to default to true (formerly false). Fixes oci8 backward compat problems with OUT params.
- Fixed month calculation error in adodb-time.inc.php. 2102-June-01 appeared as 2102-May-32.
- Updated PHP5 RC1 iterator support. API changed, hasMore() renamed to valid().
- Changed internal format of serialized cache recordsets. As we store a version number, this should be backward compatible.
- Error handling when driver file not found was flawed in ADOLoadCode(). Fixed.
## 4.20 - 27 Feb 2004
- Updated to AXMLS 1.01.
- MetaForeignKeys for postgres7 modified by Edward Jaramilla, works on pg 7.4.
- Now numbers accepts function calls or sequences for GetInsertSQL/GetUpdateSQL numeric fields.
- Changed quotes of 'delete from $perf_table' to "". Thx Kehui (webmaster#kehui.net)
- Added ServerInfo() for ifx, and putenv trim fix. Thx Fernando Ortiz.
- Added addq(), which is analogous to addslashes().
- Tested with php5b4. Fix some php5 compat problems with exceptions and sybase.
- Carl-Christian Salvesen added patch to mssql _query to support binds greater than 4000 chars.
- Mike suggested patch to PHP5 exception handler. $errno must be numeric.
- Added double quotes (") to ADODB_TABLE_REGEX.
- 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.
- Now dateHasTime property in connection object renamed to datetime for consistency. This could break bc.
- Csongor Halmai reports that db2 SelectLimit with input array is not working. Fixed..
## 4.11 - 27 Jan 2004
- Csongor Halmai reports db2 binding not working. Reverted back to emulated binding.
- Dan Cech modifies datadict code. Adds support for DropIndex. Minor cleanups.
- Table misspelt in perf-oci8.inc.php. Changed v$conn_cache_advice to v$db_cache_advice. Reported by Steve W.
- UserTimeStamp and DBTimeStamp did not handle YYYYMMDDHHMMSS format properly. Reported by Mike Muir. Fixed.
- 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.
- Added InParameter() and OutParameter(). Wrapper functions to Parameter(), but nicer because they are self-documenting.
- Added 'R' handling in ActualType() to datadict-mysql.inc.php
- Added ADOConnection::SerializableRS($rs). Returns a recordset that can be serialized in a session.
- Added "Run SQL" to performance UI().
- Misc spelling corrections in adodb-mysqli.inc.php, adodb-oci8.inc.php and datadict-oci8.inc.php, from Heinz Hombergs.
- MetaIndexes() for ibase contributed by Heinz Hombergs.
## 4.10 - 12 Jan 2004
- Dan Cech contributed extensive changes to data dictionary to support name quoting (with `\``), and drop table/index.
- Informix added cursorType property. Default remains IFX_SCROLL, but you can change to 0 (non-scrollable cursor) for performance.
- Added ADODB_View_PrimaryKeys() for returning view primary keys to MetaPrimaryKeys().
- Simplified chinese file, adodb-cn.inc.php from cysoft.
- Added check for ctype_alnum in adodb-datadict.inc.php. Thx to Jason Judge.
- Added connection parameter to ibase Prepare(). Fix by Daniel Hassan.
- 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.
- BOOL type not recognised correctly as L. Fixed.
- Fixed paths in ADODB_DIR for session files, and back-ported it to 4.05 (15 Dec 2003)
- Added Schema to postgresql MetaTables. Thx to col#gear.hu
- Empty postgresql recordsets that had blob fields did not set EOF properly. Fixed.
- CacheSelectLimit internal parameters to SelectLimit were wrong. Thx to Nio.
- Modified adodb_pr() and adodb_backtrace() to support command-line usage (eg. no html).
- Fixed some fr and it lang errors. Thx to Gaetano G.
- Added contrib directory, with adodb rs to xmlrpc convertor by Gaetano G.
- Fixed array recordset bugs when `_skiprow1` is true. Thx to Gaetano G.
- Fixed pivot table code when count is false.
## 4.05 - 13 Dec 2003
- Added MetaIndexes to data-dict code - thx to Dan Cech.
- Rewritten session code by Ross Smith. Moved code to adodb/session directory.
- Added function exists check on connecting to most drivers, so we don't crash with the unknown function error.
- Smart Transactions failed with GenID() when it no seq table has been created because the sql statement fails. Fix by Mark Newnham.
- Added $db->length, which holds name of function that returns strlen.
- Fixed error handling for bad driver in ADONewConnection - passed too few params to error-handler.
- Datadict did not handle types like 16.0 properly in _GetSize. Fixed.
- Oci8 driver SelectLimit() bug &= instead of =& used. Thx to Swen Thümmler.
- Jesse Mullan suggested not flushing outp when output buffering enabled. Due to Apache 2.0 bug. Added.
- MetaTables/MetaColumns return ref bug with PHP5 fixed in adodb-datadict.inc.php.
- 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.
- $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.
- Mysql driver's GenID() function did not work when when sql logging is on. Fixed.
- $ADODB_SESSION_TBL not declared as global var. Not available if adodb-session.inc.php included in function. Fixed.
- The input array not passed to Execute() in _adodb_getcount(). Fixed.
## 4.04 - 13 Nov 2003
- Switched back to foreach - faster than list-each.
- Fixed bug in ado driver - wiping out $this->fields with date fields.
- Performance Monitor, View SQL, Explain Plan did not work if strlen($SQL)>max($_GET length). Fixed.
- Performance monitor, oci8 driver added memory sort ratio.
- Added random property, returns SQL to generate a floating point number between 0 and 1;
## 4.03 - 6 Nov 2003
- The path to adodb-php4.inc.php and adodb-iterators.inc.php was not setup properly.
- Patched SQLDate in interbase to support hours/mins/secs. Thx to ari kuorikoski.
- 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
## 4.02 - 5 Nov 2003
- Some errors in adodb_error_pg() fixed. Thx to Styve.
- Spurious Insert_ID() error was generated by LogSQL(). Fixed.
- Insert_ID was interfering with Affected_Rows() and Replace() when LogSQL() enabled. Fixed.
- More foreach loops optimized with list/each.
- Null dates not handled properly in ADO driver (it becomes 31 Dec 1969!).
- Heinz Hombergs contributed patches for mysql MetaColumns - adding scale, made interbase MetaColumns work with firebird/interbase, and added lang/adodb-de.inc.php.
- Added INFORMIXSERVER environment variable.
- Added $ADODB_ANSI_PADDING_OFF for interbase/firebird.
- PHP 5 beta 2 compat check. Foreach (Iterator) support. Exceptions support.
## 4.01 - 23 Oct 2003
- Fixed bug in rs2html(), tohtml.inc.php, that generated blank table cells.
- Fixed insert_id() incorrectly generated when logsql() enabled.
- Modified PostgreSQL _fixblobs to use list/each instead of foreach.
- Informix ErrorNo() implemented correctly.
- Modified several places to use list/each, including GetRowAssoc().
- Added UserTimeStamp() to connection class.
- Added $ADODB_ANSI_PADDING_OFF for oci8po.
## 4.00 - 20 Oct 2003
- Upgraded adodb-xmlschema to 1 Oct 2003 snapshot.
- Fix to rs2html warning message. Thx to Filo.
- Fix for odbc_mssql/mssql SQLDate(), hours was wrong.
- Added MetaColumns and MetaPrimaryKeys for sybase. Thx to Chris Phillipson.
- Added autoquoting to datadict for MySQL and PostgreSQL. Suggestion by Karsten Dambekalns
-1079
View File
@@ -1,1079 +0,0 @@
<html>
<style>
pre {
background-color: #eee;
padding: 0.75em 1.5em;
font-size: 12px;
border: 1px solid #ddd;
}
li,p {
font-family: Arial, Helvetica, sans-serif ;
}
</style>
<title>ADOdb Active Record</title>
<body>
<h1>ADOdb Active Record</h1>
<p> (c) 2000-2009 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><hr>
<ol>
<h3><li>Introduction</h3>
<p>
ADOdb_Active_Record is an Object Relation Mapping (ORM) implementation using PHP. In an ORM system, the tables and rows of the database are abstracted into native PHP objects. This allows the programmer to focus more on manipulating the data and less on writing SQL queries.
<p>
This implementation differs from Zend Framework's implementation in the following ways:
<ul>
<li>Works with PHP4 and PHP5 and provides equivalent functionality in both versions of PHP.<p>
<li>ADOdb_Active_Record works when you are connected to multiple databases. Zend's only works when connected to a default database.<p>
<li>Support for $ADODB_ASSOC_CASE. The field names are upper-cased, lower-cased or left in natural case depending on this setting.<p>
<li>No field name conversion to camel-caps style, unlike Zend's implementation which will convert field names such as 'first_name' to 'firstName'.<p>
<li>NewADOConnection::GetActiveRecords() and ADOConnection::GetActiveRecordsClass() functions in adodb.inc.php.<p>
<li>Caching of table metadata so it is only queried once per table, no matter how many Active Records are created.<p>
<li>PHP5 version of ADOdb_Active_Record now supports <a href=#onetomany>one-to-many</a> relationships.<p>
<li>New adodb-active-recordx.inc.php, which is an <a href=#recordx>Active Record eXtended</a> implementation that support JOINs for higher performance when loading children, and other nice features.<p>
<li>Lots of <a href=#additional>additional functionality</a>.<p>
</ul>
<P>
ADOdb_Active_Record is designed upon the principles of the "ActiveRecord" design pattern, which was first described by Martin Fowler. The ActiveRecord pattern has been implemented in many forms across the spectrum of programming languages. ADOdb_Active_Record attempts to represent the database as closely to native PHP objects as possible.
<p>
ADOdb_Active_Record maps a database table to a PHP class, and each instance of that class represents a table row. Relations between tables can also be defined, allowing the ADOdb_Active_Record objects to be nested.
<p>
<h3><li>Setting the Database Connection</h3>
<p>
The first step to using ADOdb_Active_Record is to set the default connection that an ADOdb_Active_Record objects will use to connect to a database.
<pre>
require_once('adodb/adodb-active-record.inc.php');
$db = NewADOConnection('mysql://root:pwd@localhost/dbname');
ADOdb_Active_Record::SetDatabaseAdapter($db);
</pre>
<h3><li>Table Rows as Objects</h3>
<p>
First, let's create a temporary table in our MySQL database that we can use for demonstrative purposes throughout the rest of this tutorial. We can do this by sending a CREATE query:
<pre>
$db->Execute("CREATE TEMPORARY TABLE `persons` (
`id` int(10) unsigned NOT NULL auto_increment,
`name_first` varchar(100) NOT NULL default '',
`name_last` varchar(100) NOT NULL default '',
`favorite_color` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
");
</pre>
<p>
ADOdb_Active_Records are object representations of table rows. Each table in the database is represented by a class in PHP. To begin working with a table as a ADOdb_Active_Record, a class that extends ADOdb_Active_Record needs to be created for it.
<pre>
class person extends ADOdb_Active_Record{}
$person = new person();
</pre>
<p>
In the above example, a new ADOdb_Active_Record object $person was created to access the "persons" table. Zend_Db_DataObject takes the name of the class, pluralizes it (according to American English rules), and assumes that this is the name of the table in the database. Also note that with MySQL, table names are case-sensitive, so your class name must match the table name's case. With other databases with case-insensitive tables, your class can be capitalized differently.
<p>
This kind of behavior is typical of ADOdb_Active_Record. It will assume as much as possible by convention rather than explicit configuration. In situations where it isn't possible to use the conventions that ADOdb_Active_Record expects, options can be overridden as we'll see later.
<h3><li>Table Columns as Object Properties</h3>
<p>
When the $person object was instantiated, ADOdb_Active_Record read the table metadata from the database itself, and then exposed the table's columns (fields) as object properties.
<p>
Our "persons" table has three fields: "name_first", "name_last", and "favorite_color". Each of these fields is now a property of the $person object. To see all these properties, use the ADOdb_Active_Record::getAttributeNames() method:
<pre>
var_dump($person->getAttributeNames());
/**
* Outputs the following:
* array(4) {
* [0]=>
* string(2) "id"
* [1]=>
* string(9) "name_first"
* [2]=>
* string(8) "name_last"
* [3]=>
* string(13) "favorite_color"
* }
*/
</pre>
<p>
One big difference between ADOdb and Zend's implementation is we do not automatically convert to camelCaps style.
<p>
<h3><li>Inserting and Updating a Record</h3><p>
An ADOdb_Active_Record object is a representation of a single table row. However, when our $person object is instantiated, it does not reference any particular row. It is a blank record that does not yet exist in the database. An ADOdb_Active_Record object is considered blank when its primary key is NULL. The primary key in our persons table is "id".
<p>
To insert a new record into the database, change the object's properties and then call the ADOdb_Active_Record::save() method:
<pre>
$person = new person();
$person->name_first = 'Andi';
$person->name_last = 'Gutmans';
$person->save();
</pre>
<p>
Oh, no! The above code snippet does not insert a new record into the database. Instead, outputs an error:
<pre>
1048: Column 'favorite_color' cannot be null
</pre>
<p>
This error occurred because MySQL rejected the INSERT query that was generated by ADOdb_Active_Record. If exceptions are enabled in ADOdb and you are using PHP5, an error will be thrown. In the definition of our table, we specified all of the fields as NOT NULL; i.e., they must contain a value.
<p>
ADOdb_Active_Records are bound by the same contraints as the database tables they represent. If the field in the database cannot be NULL, the corresponding property in the ADOdb_Active_Record also cannot be NULL. In the example above, we failed to set the property $person->favoriteColor, which caused the INSERT to be rejected by MySQL.
<p>
To insert a new ADOdb_Active_Record in the database, populate all of ADOdb_Active_Record's properties so that they satisfy the constraints of the database table, and then call the save() method:
<pre>
/**
* Calling the save() method will successfully INSERT
* this $person into the database table.
*/
$person = new person();
$person->name_first = 'Andi';
$person->name_last = 'Gutmans';
$person->favorite_color = 'blue';
$person->save();
</pre>
<p>
Once this $person has been INSERTed into the database by calling save(), the primary key can now be read as a property. Since this is the first row inserted into our temporary table, its "id" will be 1:
<pre>
var_dump($person->id);
/**
* Outputs the following:
* string(1)
*/
</pre>
<p>
From this point on, updating it is simply a matter of changing the object's properties and calling the save() method again:
<pre>
$person->favorite_color = 'red';
$person->save();
</pre>
<p>
The code snippet above will change the favorite color to red, and then UPDATE the record in the database.
<a name=additional>
<h2>ADOdb Specific Functionality</h2>
<h3><li>Setting the Table Name</h3>
<p>The default behaviour on creating an ADOdb_Active_Record is to "pluralize" the class name and
use that as the table name. Often, this is not the case. For example, the person class could be reading
from the "People" table.
<p>We provide two ways to define your own table:
<p>1. Use a constructor parameter to override the default table naming behaviour.
<pre>
class person extends ADOdb_Active_Record{}
$person = new person('People');
</pre>
<p>2. Define it in a class declaration:
<pre>
class person extends ADOdb_Active_Record
{
var $_table = 'People';
}
$person = new person();
</pre>
<h3><li>$ADODB_ASSOC_CASE</h3>
<p>This allows you to control the case of field names and properties. For example, all field names in Oracle are upper-case by default. So you
can force field names to be lowercase using $ADODB_ASSOC_CASE. Legal values are as follows:
<pre>
0: lower-case
1: upper-case
2: native-case
</pre>
<p>So to force all Oracle field names to lower-case, use
<pre>
$ADODB_ASSOC_CASE = 0;
$person = new person('People');
$person->name = 'Lily';
$ADODB_ASSOC_CASE = 2;
$person2 = new person('People');
$person2->NAME = 'Lily';
</pre>
<p>Also see <a href=http://phplens.com/adodb/reference.constants.adodb_assoc_case.html>$ADODB_ASSOC_CASE</a>.
<h3><li>ADOdb_Active_Record::Save()</h3>
<p>
Saves a record by executing an INSERT or UPDATE SQL statement as appropriate.
<p>Returns false on unsuccessful INSERT, true if successsful INSERT.
<p>Returns 0 on failed UPDATE, and 1 on UPDATE if data has changed, and -1 if no data was changed, so no UPDATE statement was executed.
<h3><li>ADOdb_Active_Record::Replace()</h3>
<p>
ADOdb supports replace functionality, whereby the record is inserted if it does not exists, or updated otherwise.
<pre>
$rec = new ADOdb_Active_Record("product");
$rec->name = 'John';
$rec->tel_no = '34111145';
$ok = $rec->replace(); // 0=failure, 1=update, 2=insert
</pre>
<h3><li>ADOdb_Active_Record::Load($where)</h3>
<p>Sometimes, we want to load a single record into an Active Record. We can do so using:
<pre>
$person->load("id=3");
// or using bind parameters
$person->load("id=?", array(3));
</pre>
<p>Returns false if an error occurs.
<h3><li>ADOdb_Active_Record::Find($whereOrderBy, $bindarr=false, $pkeyArr=false)</h3>
<p>We want to retrieve an array of active records based on some search criteria. For example:
<pre>
class person extends ADOdb_Active_Record {
var $_table = 'people';
}
$person = new person();
$peopleArray = $person->Find("name like ? order by age", array('Sm%'));
</pre>
<h3><li>Quoting Identifiers</h3>
<p>You can force column names to be quoted in INSERT and UPDATE statements, typically because you are using reserved words as column names by setting
<pre>
ADODB_Active_Record::$_quoteNames = true;
</pre>
<p>Default is false.
<h3><li>Error Handling and Debugging</h3>
<p>
In PHP5, if adodb-exceptions.inc.php is included, then errors are thrown. Otherwise errors are handled by returning a value. False by default means an error has occurred. You can get the last error message using the ErrorMsg() function.
<p>
To check for errors in ADOdb_Active_Record, do not poll ErrorMsg() as the last error message will always be returned, even if it occurred several operations ago. Do this instead:
<pre>
# right!
$ok = $rec->Save();
if (!$ok) $err = $rec->ErrorMsg();
# wrong :(
$rec->Save();
if ($rec->ErrorMsg()) echo "Wrong way to detect error";
</pre>
<p>The ADOConnection::Debug property is obeyed. So
if $db->debug is enabled, then ADOdb_Active_Record errors are also outputted to standard output and written to the browser.
<h3><li>ADOdb_Active_Record::Set()</h3>
<p>You can convert an array to an ADOdb_Active_Record using Set(). The array must be numerically indexed, and have all fields of the table defined in the array. The elements of the array must be in the table's natural order too.
<pre>
$row = $db->GetRow("select * from tablex where id=$id");
# PHP4 or PHP5 without enabling exceptions
$obj = new ADOdb_Active_Record('Products');
if ($obj->ErrorMsg()){
echo $obj->ErrorMsg();
} else {
$obj->Set($row);
}
# in PHP5, with exceptions enabled:
include('adodb-exceptions.inc.php');
try {
$obj = new ADOdb_Active_Record('Products');
$obj->Set($row);
} catch(exceptions $e) {
echo $e->getMessage();
}
</pre>
<p>
<h3><li>Primary Keys</h3>
<p>
ADOdb_Active_Record does not require the table to have a primary key. You can insert records for such a table, but you will not be able to update nor delete.
<p>Sometimes you are retrieving data from a view or table that has no primary key, but has a unique index. You can dynamically set the primary key of a table through the constructor, or using ADOdb_Active_Record::SetPrimaryKeys():
<pre>
$pkeys = array('category','prodcode');
// set primary key using constructor
$rec = new ADOdb_Active_Record('Products', $pkeys);
// or use method
$rec->SetPrimaryKeys($pkeys);
</pre>
<h3><li>Retrieval of Auto-incrementing ID</h3>
When creating a new record, the retrieval of the last auto-incrementing ID is not reliable for databases that do not support the Insert_ID() function call (check $connection->hasInsertID). In this case we perform a <b>SELECT MAX($primarykey) FROM $table</b>, which will not work reliably in a multi-user environment. You can override the ADOdb_Active_Record::LastInsertID() function in this case.
<h3><li>Dealing with Multiple Databases</h3>
<p>
Sometimes we want to load data from one database and insert it into another using ActiveRecords. This can be done using the optional parameter of the ADOdb_Active_Record constructor. In the following example, we read data from db.table1 and store it in db2.table2:
<pre>
$db = NewADOConnection(...);
$db2 = NewADOConnection(...);
ADOdb_Active_Record::SetDatabaseAdapter($db2);
$activeRecs = $db->GetActiveRecords('table1');
foreach($activeRecs as $rec) {
$rec2 = new ADOdb_Active_Record('table2',$db2);
$rec2->id = $rec->id;
$rec2->name = $rec->name;
$rec2->Save();
}
</pre>
<p>
If you have to pass in a primary key called "id" and the 2nd db connection in the constructor, you can do so too:
<pre>
$rec = new ADOdb_Active_Record("table1",array("id"),$db2);
</pre>
<p>You can now give a named label in SetDatabaseAdapter, allowing to determine in your class definition which database to load, using var $_dbat.
<pre>
$db1 = NewADOConnection(...); // some ADOdb DB
ADOdb_Active_Record::SetDatabaseAdapter($db1, 'mysql');
$db2 = NewADOConnection(...); // some ADOdb DB
ADOdb_Active_Record::SetDatabaseAdapter($db2, 'oracle');
class FooRecord extends ADOdb_Active_Record
{
<b>var $_dbat = 'mysql';</b> // uses 'mysql' connection
...
}
</pre>
<h3><li>$ADODB_ACTIVE_CACHESECS</h3>
<p>You can cache the table metadata (field names, types, and other info such primary keys) in $ADODB_CACHE_DIR (which defaults to /tmp) by setting
the global variable $ADODB_ACTIVE_CACHESECS to a value greater than 0. This will be the number of seconds to cache.
You should set this to a value of 30 seconds or greater for optimal performance.
<h3><li>Active Record Considered Bad?</h3>
<p>Although the Active Record concept is useful, you have to be aware of some pitfalls when using Active Record. The level of granularity of Active Record is individual records. It encourages code like the following, used to increase the price of all furniture products by 10%:
<pre>
$recs = $db->GetActiveRecords("Products","category='Furniture'");
foreach($recs as $rec) {
$rec->price *= 1.1; // increase price by 10% for all Furniture products
$rec->save();
}
</pre>
Of course an UPDATE statement is superior because it's simpler and much more efficient (probably by a factor of x10 or more):
<pre>
$db->Execute("update Products set price = price * 1.1 where category='Furniture'");
</pre>
<p>For performance sensitive code, using direct SQL will always be faster than using Active Records due to overhead and the fact that all fields in a row are retrieved (rather than only the subset you need) whenever an Active Record is loaded.
<h3><li>Transactions</h3>
<p>
The default transaction mode in ADOdb is autocommit. So that is the default with active record too.
The general rules for managing transactions still apply. Active Record to the database is a set of insert/update/delete statements, and the db has no knowledge of active records.
<p>
Smart transactions, that does an auto-rollback if an error occurs, is still the best method to multiple activities (inserts/updates/deletes) that need to be treated as a single transaction:
<pre>
$conn->StartTrans();
$parent->save();
$child->save();
$conn->CompleteTrans();
</pre>
<a name=onetomany>
<h2>One to Many Relations</h3>
<p>Since ADOdb 5.06, we support parent child relationships. This is done using the ClassBelongsTo() and ClassHasMany() functions.
<a name=tablehasmany>
<h3><li>ClassHasMany</h3>
<p>To globally define a one-to-many relationship we use the static function ADODB_Active_Record::ClassHasMany($class, $relation, $foreignKey = '', $foreignClass = 'ADODB_Active_Record'). For example, we have 2 tables, <strong>persons</strong> (parent table) and <strong>children</strong> (child table)
linked by <strong>persons.id = children.person_id</strong>. The variable $person->children is an array that holds the children. To define this relationship:
<pre>
class person extends ADOdb_Active_Record{}
ADODB_Active_Record::ClassHasMany('person', 'children','person_id');
$person = new person();
$person->Load("id=1");
foreach($person->children as $c) {
echo " $c->name_first ";
$c->name_first .= ' K.';
$c->Save(); ## each child record must be saved individually
}
</pre>
<p>If no data is loaded, then children is set to an empty array:
<pre>
$person2 = new person();
$p = $person2->children; ## $p is an empty array()
</pre>
<P>By default, data returned by HasMany() is unsorted. To define an order by clause (or define a SELECT LIMIT window), see <a href=#loadrelations>LoadRelations()</a> below. Another point is that all children are loaded only when the child member is accessed (in __get), and not when the Load() function of the parent object is called. This helps to conserve memory.
<p>To create and save new parent and child records:
<pre>
class person extends ADOdb_Active_Record{}
class children extends ADOdb_Active_Record{}
ADODB_Active_Record::ClassHasMany('person', 'children','person_id');
$person = new person();
for ($i=0; $i<10; $i++)
$person->children[0] = new children('children');
// modify fields of $person, then...
$person->save();
foreach($person->children as $c) {
// modify fields of $c then...
$c->save();
}
</pre>
<p>You can have multiple relationships (warning: relations are case-sensitive, 'Children' !== 'children'):
<pre>
ADODB_Active_Record::ClassHasMany('person', 'children','person_id');
ADODB_Active_Record::ClassHasMany('person', 'siblings','person_id');
$person = new person();
$person->Load('id=1');
var_dump($person->children);
var_dump($person->siblings);
</pre>
<p>By default, the child class is ADOdb_Active_Record. Sometimes you might want the child class to be based on your own class which has additional functions. You can do so using the last parameter:
<pre>
class person extends ADOdb_Active_Record{}
class child extends ADOdb_Active_Record { .... some modifications here ... }
ADODB_Active_Record::ClassHasMany('person', 'children','person_id', 'child');
</pre>
<p>Lastly some troubleshooting issues. We use the __get() method to set
$p->children below. So once $p->children is defined by accessing it, we don't change the child reference, as shown below:
<pre>
ADODB_Active_Record::ClassHasMany('person', 'children','person_id');
$p = new person();
$p->Load('id=1');
# $p->children points to person_id = 1
var_dump($p->children);
$p->Load('id=2');
# $p->children still points to person_id = 1
var_dump($p->children);
</pre>
<p>The solution to the above is to unset($p->children) before $p->Load('id=2').
<h3><li>TableHasMany</h3>
For some classes, the mapping between class name and table name (which is the pluralised version) might not match. For example,
the class name might be <b>person</b>, but the table name might be <b>people</b>. So we have 2 tables, <strong>people</strong> (parent table) and <strong>children</strong> (child table)
linked by <strong>people.id = children.person_id</strong>.
<p>Then you use the following static function
ADODB_Active_Record::TableHasMany($table, $relation, $foreignKey = '', $foreignClass = 'ADODB_Active_Record') like this:
<pre>
ADODB_Active_Record::TableHasMany('people', 'children', 'person_id')
</pre>
<h3><li>TableKeyHasMany</h3>
For some classes, the mapping between class name and table name (which is the pluralised version) might not match or the primary key is not the default <b>id</b>. For example,
the class name might be <b>person</b>, but the table name might be <b>people</b>. So we have 2 tables, <strong>people</strong> (parent table) and <strong>children</strong> (child table)
linked by <strong>people.pid = children.person_id</strong>.
<p>Then you use the following static function
ADODB_Active_Record::TableKeyHasMany($table, $tablePKey, $relation, $foreignKey = '', $foreignClass = 'ADODB_Active_Record') like this:
<pre>
ADODB_Active_Record::TableKeyHasMany('people', 'pid', 'children', 'person_id')
</pre>
<h3><li>A Complete ClassHasMany example</h3>
<p>Here is sample usage using mysql:
<pre>
include_once('../adodb.inc.php');
include_once('../adodb-active-record.inc.php');
$db = NewADOConnection('mysql://root@localhost/northwind');
ADOdb_Active_Record::SetDatabaseAdapter($db);
$db->Execute("CREATE TEMPORARY TABLE `persons` (
`id` int(10) unsigned NOT NULL auto_increment,
`name_first` varchar(100) NOT NULL default '',
`name_last` varchar(100) NOT NULL default '',
`favorite_color` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
");
$db->Execute("CREATE TEMPORARY TABLE `children` (
`id` int(10) unsigned NOT NULL auto_increment,
`person_id` int(10) unsigned NOT NULL,
`gender` varchar(10) default 'F',
`name_first` varchar(100) NOT NULL default '',
`name_last` varchar(100) NOT NULL default '',
`favorite_pet` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
");
$db->Execute("insert into children (person_id,name_first,name_last) values (1,'Jill','Lim')");
$db->Execute("insert into children (person_id,name_first,name_last) values (1,'Joan','Lim')");
$db->Execute("insert into children (person_id,name_first,name_last) values (1,'JAMIE','Lim')");
class person extends ADOdb_Active_Record{}
ADODB_Active_Record::ClassHasMany('person', 'children','person_id');
$person = new person();
$person->name_first = 'John';
$person->name_last = 'Lim';
$person->favorite_color = 'lavender';
$person->save(); // this save will perform an INSERT successfully
$person2 = new person(); # no need to define HasMany() again, adodb remembers definition
$person2->Load('id=1');
$c = $person2->children;
if (is_array($c) && sizeof($c) == 3 && $c[0]->name_first=='Jill' && $c[1]->name_first=='Joan'
&& $c[2]->name_first == 'JAMIE') echo "OK Loaded HasMany&lt;br>";
else {
echo "Error loading hasMany should have 3 array elements Jill Joan Jamie&lt;br>";
}
</pre>
<h3><li>HasMany</h3>
<p>This older method is deprecated and ClassHasMany/TableHasMany/TableKeyHasMany should be used.
<p>The older way to define a one-to-many relationship is to use $parentobj->HasMany($relation, $foreignKey = ''). For example, we have 2 tables, <strong>persons</strong> (parent table) and <strong>children</strong> (child table)
linked by <strong>persons.id = children.person_id</strong>. The variable $person->children is an array that holds the children. To define this relationship:
<pre>
class person extends ADOdb_Active_Record{}
$person = new person();
$person->HasMany('children','person_id');
$person->Load("id=1");
foreach($person->children as $c) {
echo " $c->name_first ";
$c->name_first .= ' K.';
$c->Save(); ## each child record must be saved individually
}
</pre>
<p>This HasMany() definition is global for the current script. This means that you only need to define it once. In the following example, $person2 knows about <em>children</em>.
<pre>
$person = new person();
$person->HasMany('children','person_id');
$person2 = new person();
$person->Load("id=1");
$p = $person2->children;
</pre>
<h3><li>ClassBelongsTo</h3>
<p>You can define the parent of the current object using ADODB_Active_Record::ClassBelongsTo($class, $relationName, $foreignKey, $parentPrimaryKey = 'id', $parentClass = 'ADODB_Active_Record'). In the example below,
we have a child table <strong>kids</strong>, and a parent table <strong>person</strong>. We have a link <strong>kids.person_id = persons.id</strong>. We create a child first, then link it to the parent:
<pre>
class kid extends ADOdb_Active_Record{};
ADODB_Active_Record::ClassBelongsTo('kid','person','person_id','id');
$ch = new kid(); // default tablename will be 'kids', with primary key 'id'
$ch->Load('id=1');
$p = $ch->person;
if (!$p || $p->name_first != 'John') echo "Error loading belongsTo&lt;br>";
else echo "OK loading BelongTo&lt;br>";
</pre>
<p>
<p>Note that relationships are case-sensitive, so ClassBelongsTo('kid','PARENT', 'parent_id') and ClassBelongsTo('kid', 'parent', 'parent_id') are not the same.
<p>Also if no data is loaded into the child instance, then $p will return null;
<pre>
ADODB_Active_Record::ClassBelongsTo('kid','person','person_id','id');
$ch = new kid();
$p = $ch->person; # $p is null
</pre>
<p>Another way to define the class of the parent (which otherwise defaults to ADODB_Active_Record) as follows:
<pre>
class kid extends ADOdb_Active_Record{};
class person extends ADOdb_Active_Record{... your modifications ... };
ADODB_Active_Record::ClassBelongsTo('kid','person','person_id','id', 'person');
</pre>
<h3><li>TableBelongsTo</h3>
<p>If the child table differs from the convention that the child table name is the plural of the child class name, use this function:
ADODB_Active_Record::TableBelongsTo($childTable, $relationName, $foreignKey, $parentPrimaryKey = 'id', $parentClass = 'ADODB_Active_Record').
<p>E.g. the class is <b>child</b>, but the table name is <b>children</b>, and the link between the two tables is children.person_id = person.id:
<pre>
ADODB_Active_Record::TableBelongsTo('children','person','person_id','id');
</pre>
<h3><li>TableKeyBelongsTo</h3>
<p>If the child table differs from the convention that the child table name is the plural of the child class name or the primary key is not 'id', use this function:
ADODB_Active_Record::TableKeyBelongsTo($childTable, $childKey, $relationName, $foreignKey, $parentPrimaryKey = 'id', $parentClass = 'ADODB_Active_Record').
<p>E.g. the class is <b>child</b>, but the table name is <b>children</b> and primary key is <b>ch_id</b>, and the link between the two tables is children.person_id = person.id:
<pre>
ADODB_Active_Record::TableKeyBelongsTo('children','ch_id', 'person','person_id','id');
</pre>
<h3><li>BelongsTo</h3>
<p>The following is deprecated. Use ClassBelongsTo/TableBelongsTo/TableKeyBelongsTo instead.
<p>The older way to define the parent of the current object is using BelongsTo($relationName, $foreignKey, $parentPrimaryKey = 'id'). In the example below,
we have a child table <strong>children</strong>, and a parent table <strong>person</strong>. We have a link <strong>children.person_id = persons.id</strong>. We create a child first, then link it to the parent:
<pre>
class Child extends ADOdb_Active_Record{};
$ch = new Child('children',array('id'));
$ch->BelongsTo('person','person_id','id'); ## this can be simplified to $ch->BelongsTo('person')
## as foreign key defaults to $table.'_id' and
## parent pkey defaults to 'id'
$ch->Load('id=1');
$p = $ch->person;
if (!$p || $p->name_first != 'John') echo "Error loading belongsTo&lt;br>";
else echo "OK loading BelongTo&lt;br>";
</pre>
<p>You only need to define BelongsTo() once in a script as it is global for all instances.
<a name=loadrelations>
<h3><li>LoadRelations</h3>
<p>Sometimes you want to load only a subset of data in a relationship. For example, you could load all female children sorted by children.name
using LoadRelations($relation, $whereOrderBy = '', $offset = -1, $limit = -1):
<pre>
# assume this has been called:
# ADODB_Active_Record::ClassHasMany('person', 'children','person_id');
$person = new person();
$person->Load('id=23');
# Load doesn't load children until $person->children is accessed or LoadRelations is called:
$person->LoadRelations('children',"gender='F' order by name");
</pre>
<p>Lastly, if you have lots of child data, you can define a window of data of records to load. In the following
example, we load a window of 100 records at a time:
<pre>
# assume this has been called:
# ADODB_Active_Record::ClassHasMany('Account', 'transactions','account_id');
$acc = new Account();
$acc->Load('id=23');
while(true) {
$start = 0;
$acc->LoadRelations('transactions',"tx_done=0 order by trxdate", $start, $start+100);
if (!$acc->transactions) break;
foreach ($acc->transactions as $k => $trx) {
## process
$trx->tx_done = 1;
$trx->save();
}
$start += 100;
}
</pre>
<p>The $offset is 0-based, and $limit is the number of records to retrieve. The default is to ignore $offset (-1) and $limit (-1).
<h3><li>Acknowledgements</h3>
<p>Thanks to Chris Ravenscroft for original one-to-many code (chris#voilaweb.com).
<h2>ADOConnection Supplement</h2>
<h3><li>ADOConnection::GetActiveRecords()</h3>
<p>
This allows you to retrieve an array of ADOdb_Active_Records. Returns false if an error occurs.
<pre>
$table = 'products';
$whereOrderBy = "name LIKE 'A%' ORDER BY Name";
$activeRecArr = $db->GetActiveRecords($table, $whereOrderBy);
foreach($activeRecArr as $rec) {
$rec->id = rand();
$rec->save();
}
</pre>
<p>
And to retrieve all records ordered by specific fields:
<pre>
$whereOrderBy = "1=1 ORDER BY Name";
$activeRecArr = $db->GetActiveRecords($table);
</pre>
<p>
To use bind variables (assuming ? is the place-holder for your database):
<pre>
$activeRecArr = $db->GetActiveRecords($tableName, 'name LIKE ?',
array('A%'));
</pre>
<p>You can also define the primary keys of the table by passing an array of field names:
<pre>
$activeRecArr = $db->GetActiveRecords($tableName, 'name LIKE ?',
array('A%'), array('id'));
</pre>
<h3><li>ADOConnection::GetActiveRecordsClass()</h3>
<p>
This allows you to retrieve an array of objects derived from ADOdb_Active_Records. Returns false if an error occurs.
<pre>
class Product extends ADOdb_Active_Record{};
$table = 'products';
$whereOrderBy = "name LIKE 'A%' ORDER BY Name";
$activeRecArr = $db->GetActiveRecordsClass('Product',$table, $whereOrderBy);
# the objects in $activeRecArr are of class 'Product'
foreach($activeRecArr as $rec) {
$rec->id = rand();
$rec->save();
}
</pre>
<p>
To use bind variables (assuming ? is the place-holder for your database):
<pre>
$activeRecArr = $db->GetActiveRecordsClass($className,$tableName, 'name LIKE ?',
array('A%'));
</pre>
<p>You can also define the primary keys of the table by passing an array of field names:
<pre>
$activeRecArr = $db->GetActiveRecordsClass($className,$tableName, 'name LIKE ?',
array('A%'), array('id'));
</pre>
</ol>
<h3><li>ADOConnection::ErrorMsg()</h3>
<p>Returns last error message.
<h3><li>ADOConnection::ErrorNo()</h3>
<p>Returns last error number.
<h2>ActiveRecord Code Sample</h2>
<p>The following works with PHP4 and PHP5
<pre>
include('../adodb.inc.php');
include('../adodb-active-record.inc.php');
// uncomment the following if you want to test exceptions
#if (PHP_VERSION >= 5) include('../adodb-exceptions.inc.php');
$db = NewADOConnection('mysql://root@localhost/northwind');
$db->debug=1;
ADOdb_Active_Record::SetDatabaseAdapter($db);
$db->Execute("CREATE TEMPORARY TABLE `persons` (
`id` int(10) unsigned NOT NULL auto_increment,
`name_first` varchar(100) NOT NULL default '',
`name_last` varchar(100) NOT NULL default '',
`favorite_color` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
");
class person extends ADOdb_Active_Record{}
$person = new person();
echo "&lt;p>Output of getAttributeNames: ";
var_dump($person->getAttributeNames());
/**
* Outputs the following:
* array(4) {
* [0]=>
* string(2) "id"
* [1]=>
* string(9) "name_first"
* [2]=>
* string(8) "name_last"
* [3]=>
* string(13) "favorite_color"
* }
*/
$person = new person();
$person->name_first = 'Andi';
$person->name_last = 'Gutmans';
$person->save(); // this save() will fail on INSERT as favorite_color is a must fill...
$person = new person();
$person->name_first = 'Andi';
$person->name_last = 'Gutmans';
$person->favorite_color = 'blue';
$person->save(); // this save will perform an INSERT successfully
echo "&lt;p>The Insert ID generated:"; print_r($person->id);
$person->favorite_color = 'red';
$person->save(); // this save() will perform an UPDATE
$person = new person();
$person->name_first = 'John';
$person->name_last = 'Lim';
$person->favorite_color = 'lavender';
$person->save(); // this save will perform an INSERT successfully
// load record where id=2 into a new ADOdb_Active_Record
$person2 = new person();
$person2->Load('id=2');
var_dump($person2);
// retrieve an array of records
$activeArr = $db->GetActiveRecordsClass($class = "person",$table = "persons","id=".$db->Param(0),array(2));
$person2 = $activeArr[0];
echo "&lt;p>Name first (should be John): ",$person->name_first, "&lt;br>Class = ",get_class($person2);
</pre>
<a name=recordx>
<h2>Active Record eXtended</h2>
<p>This is the original one-to-many Active Record implementation submitted by
Chris Ravenscroft (chris#voilaweb.com). The reason why we are offering both versions is that the Extended version
is more powerful but more complex. My personal preference is to keep it simpler, but your view may vary.
<p>To use, just include adodb-active-recordx.inc.php instead of adodb-active-record.inc.php.
<p>It provides a new function called Find() that is quite intuitive to use as shown in the example below. It also supports loading all relationships using a single query (using joins).
<pre>
&lt;?php
function ar_assert($obj, $cond)
{
global $err_count;
$res = var_export($obj, true);
return (strpos($res, $cond));
}
include_once('../adodb.inc.php');
include_once('../adodb-active-recordx.inc.php');
$db = NewADOConnection('mysql://root@localhost/northwind');
$db->debug=0;
ADOdb_Active_Record::SetDatabaseAdapter($db);
echo "&lt;pre>\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "Preparing database using SQL queries (creating 'people', 'children')\n";
$db->Execute("DROP TABLE `people`");
$db->Execute("DROP TABLE `children`");
$db->Execute("CREATE TABLE `people` (
`id` int(10) unsigned NOT NULL auto_increment,
`name_first` varchar(100) NOT NULL default '',
`name_last` varchar(100) NOT NULL default '',
`favorite_color` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
");
$db->Execute("CREATE TABLE `children` (
`id` int(10) unsigned NOT NULL auto_increment,
`person_id` int(10) unsigned NOT NULL,
`name_first` varchar(100) NOT NULL default '',
`name_last` varchar(100) NOT NULL default '',
`favorite_pet` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
");
$db->Execute("insert into children (person_id,name_first,name_last,favorite_pet) values (1,'Jill','Lim','tortoise')");
$db->Execute("insert into children (person_id,name_first,name_last) values (1,'Joan','Lim')");
$db->Execute("insert into children (person_id,name_first,name_last) values (1,'JAMIE','Lim')");
// This class _implicitely_ relies on the 'people' table (pluralized form of 'person')
class Person extends ADOdb_Active_Record
{
function __construct()
{
parent::__construct();
$this->hasMany('children');
}
}
// This class _implicitely_ relies on the 'children' table
class Child extends ADOdb_Active_Record
{
function __construct()
{
parent::__construct();
$this->belongsTo('person');
}
}
// This class _explicitely_ relies on the 'children' table and shares its metadata with Child
class Kid extends ADOdb_Active_Record
{
function __construct()
{
parent::__construct('children');
$this->belongsTo('person');
}
}
// This class _explicitely_ relies on the 'children' table but does not share its metadata
class Rugrat extends ADOdb_Active_Record
{
function __construct()
{
parent::__construct('children', false, false, array('new' => true));
}
}
echo "Inserting person in 'people' table ('John Lim, he likes lavender')\n";
echo "---------------------------------------------------------------------------\n";
$person = new Person();
$person->name_first = 'John';
$person->name_last = 'Lim';
$person->favorite_color = 'lavender';
$person->save(); // this save will perform an INSERT successfully
$err_count = 0;
echo "\n\n---------------------------------------------------------------------------\n";
echo "person->Find('id=1') [Lazy Method]\n";
echo "person is loaded but its children will be loaded on-demand later on\n";
echo "---------------------------------------------------------------------------\n";
$person5 = new Person();
$people5 = $person5->Find('id=1');
echo (ar_assert($people5, "'name_first' => 'John'")) ? "[OK] Found John\n" : "[!!] Find failed\n";
echo (ar_assert($people5, "'favorite_pet' => 'tortoise'")) ? "[!!] Found relation when I shouldn't\n" : "[OK] No relation yet\n";
foreach($people5 as $person)
{
foreach($person->children as $child)
{
if($child->name_first);
}
}
echo (ar_assert($people5, "'favorite_pet' => 'tortoise'")) ? "[OK] Found relation: child\n" : "[!!] Missing relation: child\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "person->Find('id=1' ... ADODB_WORK_AR) [Worker Method]\n";
echo "person is loaded, and so are its children\n";
echo "---------------------------------------------------------------------------\n";
$person6 = new Person();
$people6 = $person6->Find('id=1', false, false, array('loading' => ADODB_WORK_AR));
echo (ar_assert($people6, "'name_first' => 'John'")) ? "[OK] Found John\n" : "[!!] Find failed\n";
echo (ar_assert($people6, "'favorite_pet' => 'tortoise'")) ? "[OK] Found relation: child\n" : "[!!] Missing relation: child\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "person->Find('id=1' ... ADODB_JOIN_AR) [Join Method]\n";
echo "person and its children are loaded using a single query\n";
echo "---------------------------------------------------------------------------\n";
$person7 = new Person();
// When I specifically ask for a join, I have to specify which table id I am looking up
// otherwise the SQL parser will wonder which table's id that would be.
$people7 = $person7->Find('people.id=1', false, false, array('loading' => ADODB_JOIN_AR));
echo (ar_assert($people7, "'name_first' => 'John'")) ? "[OK] Found John\n" : "[!!] Find failed\n";
echo (ar_assert($people7, "'favorite_pet' => 'tortoise'")) ? "[OK] Found relation: child\n" : "[!!] Missing relation: child\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "person->Load('people.id=1') [Join Method]\n";
echo "Load() always uses the join method since it returns only one row\n";
echo "---------------------------------------------------------------------------\n";
$person2 = new Person();
// Under the hood, Load(), since it returns only one row, always perform a join
// Therefore we need to clarify which id we are talking about.
$person2->Load('people.id=1');
echo (ar_assert($person2, "'name_first' => 'John'")) ? "[OK] Found John\n" : "[!!] Find failed\n";
echo (ar_assert($person2, "'favorite_pet' => 'tortoise'")) ? "[OK] Found relation: child\n" : "[!!] Missing relation: child\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "child->Load('children.id=1') [Join Method]\n";
echo "We are now loading from the 'children' table, not from 'people'\n";
echo "---------------------------------------------------------------------------\n";
$ch = new Child();
$ch->Load('children.id=1');
echo (ar_assert($ch, "'name_first' => 'Jill'")) ? "[OK] Found Jill\n" : "[!!] Find failed\n";
echo (ar_assert($ch, "'favorite_color' => 'lavender'")) ? "[OK] Found relation: person\n" : "[!!] Missing relation: person\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "child->Find('children.id=1' ... ADODB_WORK_AR) [Worker Method]\n";
echo "---------------------------------------------------------------------------\n";
$ch2 = new Child();
$ach2 = $ch2->Find('id=1', false, false, array('loading' => ADODB_WORK_AR));
echo (ar_assert($ach2, "'name_first' => 'Jill'")) ? "[OK] Found Jill\n" : "[!!] Find failed\n";
echo (ar_assert($ach2, "'favorite_color' => 'lavender'")) ? "[OK] Found relation: person\n" : "[!!] Missing relation: person\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "kid->Find('children.id=1' ... ADODB_WORK_AR) [Worker Method]\n";
echo "Where we see that kid shares relationships with child because they are stored\n";
echo "in the common table's metadata structure.\n";
echo "---------------------------------------------------------------------------\n";
$ch3 = new Kid('children');
$ach3 = $ch3->Find('children.id=1', false, false, array('loading' => ADODB_WORK_AR));
echo (ar_assert($ach3, "'name_first' => 'Jill'")) ? "[OK] Found Jill\n" : "[!!] Find failed\n";
echo (ar_assert($ach3, "'favorite_color' => 'lavender'")) ? "[OK] Found relation: person\n" : "[!!] Missing relation: person\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "kid->Find('children.id=1' ... ADODB_LAZY_AR) [Lazy Method]\n";
echo "Of course, lazy loading also retrieve medata information...\n";
echo "---------------------------------------------------------------------------\n";
$ch32 = new Kid('children');
$ach32 = $ch32->Find('children.id=1', false, false, array('loading' => ADODB_LAZY_AR));
echo (ar_assert($ach32, "'name_first' => 'Jill'")) ? "[OK] Found Jill\n" : "[!!] Find failed\n";
echo (ar_assert($ach32, "'favorite_color' => 'lavender'")) ? "[!!] Found relation when I shouldn't\n" : "[OK] No relation yet\n";
foreach($ach32 as $akid)
{
if($akid->person);
}
echo (ar_assert($ach32, "'favorite_color' => 'lavender'")) ? "[OK] Found relation: person\n" : "[!!] Missing relation: person\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "rugrat->Find('children.id=1' ... ADODB_WORK_AR) [Worker Method]\n";
echo "In rugrat's constructor it is specified that\nit must forget any existing relation\n";
echo "---------------------------------------------------------------------------\n";
$ch4 = new Rugrat('children');
$ach4 = $ch4->Find('children.id=1', false, false, array('loading' => ADODB_WORK_AR));
echo (ar_assert($ach4, "'name_first' => 'Jill'")) ? "[OK] Found Jill\n" : "[!!] Find failed\n";
echo (ar_assert($ach4, "'favorite_color' => 'lavender'")) ? "[!!] Found relation when I shouldn't\n" : "[OK] No relation found\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "kid->Find('children.id=1' ... ADODB_WORK_AR) [Worker Method]\n";
echo "Note how only rugrat forgot its relations - kid is fine.\n";
echo "---------------------------------------------------------------------------\n";
$ch5 = new Kid('children');
$ach5 = $ch5->Find('children.id=1', false, false, array('loading' => ADODB_WORK_AR));
echo (ar_assert($ach5, "'name_first' => 'Jill'")) ? "[OK] Found Jill\n" : "[!!] Find failed\n";
echo (ar_assert($ach5, "'favorite_color' => 'lavender'")) ? "[OK] I did not forget relation: person\n" : "[!!] I should not have forgotten relation: person\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "rugrat->Find('children.id=1' ... ADODB_WORK_AR) [Worker Method]\n";
echo "---------------------------------------------------------------------------\n";
$ch6 = new Rugrat('children');
$ch6s = $ch6->Find('children.id=1', false, false, array('loading' => ADODB_WORK_AR));
$ach6 = $ch6s[0];
echo (ar_assert($ach6, "'name_first' => 'Jill'")) ? "[OK] Found Jill\n" : "[!!] Find failed\n";
echo (ar_assert($ach6, "'favorite_color' => 'lavender'")) ? "[!!] Found relation when I shouldn't\n" : "[OK] No relation yet\n";
echo "\nLoading relations:\n";
$ach6->belongsTo('person');
$ach6->LoadRelations('person', 'order by id', 0, 2);
echo (ar_assert($ach6, "'favorite_color' => 'lavender'")) ? "[OK] Found relation: person\n" : "[!!] Missing relation: person\n";
echo "\n\n---------------------------------------------------------------------------\n";
echo "Test suite complete.\n";
echo "---------------------------------------------------------------------------\n";
?>
</pre>
<h3>Todo (Code Contributions welcome)</h3>
<p>Check _original and current field values before update, only update changes. Also if the primary key value is changed, then on update, we should save and use the original primary key values in the WHERE clause!
<p>PHP5 specific: Make GetActiveRecords*() return an Iterator.
<p>PHP5 specific: Change PHP5 implementation of Active Record to use __get() and __set() for better performance.
<h3> Change Log</h3>
<p>0.93
<p>You can force column names to be quoted in INSERT and UPDATE statements, typically because you are using reserved words as column names by setting
ADODB_Active_Record::$_quoteNames = true;
<p>0.92
<p>Fixed some issues with incompatible fetch modes (ADODB_FETCH_ASSOC) causing problems in UpdateActiveTable.
<p>Added support for functions that support predefining one-to-many relationships:<br>
&nbsp; <i>ClassHasMany ClassBelongsTo TableHasMany TableBelongsTo TableKeyHasMany TableKeyBelongsTo</i>. <br>
<p>You can also define your child/parent class in these functions, instead of the default ADODB_Active_Record.
<P>0.91
<p>HasMany hardcoded primary key field name to "id". Fixed.
<p>0.90
<p>Support for belongsTo and hasMany. Thanks to Chris Ravenscroft (chris#voilaweb.com).
<p>Added LoadRelations().
<p>0.08
Added support for assoc arrays in Set().
<p>0.07
<p>$ADODB_ASSOC_CASE=2 did not work properly. Fixed.
<p>Added === check in ADODB_SetDatabaseAdapter for $db, adodb-active-record.inc.php. Thx Christian Affolter.
<p>0.06
<p>Added ErrorNo().
<p>Fixed php 5.2.0 compat issues.
<p>0.05
<p>If inserting a record and the value of a primary key field is null, then we do not insert that field in as
we assume it is an auto-increment field. Needed by mssql.
<p>0.04 5 June 2006 <br>
<p>Added support for declaring table name in $_table in class declaration. Thx Bill Dueber for idea.
<p>Added find($where,$bindarr=false) method to retrieve an array of active record objects.
<p>0.03 <br>
- Now we only update fields that have changed, using $this->_original.<br>
- We do not include auto_increment fields in replace(). Thx Travis Cline<br>
- Added ADODB_ACTIVE_CACHESECS.<br>
<p>0.02 <br>
- Much better error handling. ErrorMsg() implemented. Throw implemented if adodb-exceptions.inc.php detected.<br>
- You can now define the primary keys of the view or table you are accessing manually.<br>
- The Active Record allows you to create an object which does not have a primary key. You can INSERT but not UPDATE in this case.
- Set() documented.<br>
- Fixed _pluralize bug with y suffix.
<p>
0.01 6 Mar 2006<br>
- Fixed handling of nulls when saving (it didn't save nulls, saved them as '').<br>
- Better error handling messages.<br>
- Factored out a new method GetPrimaryKeys().<br>
<p>
0.00 5 Mar 2006<br>
1st release
</body>
</html>
File diff suppressed because it is too large Load Diff
-330
View File
@@ -1,330 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<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;
background-color: #EEEEEE; padding: .5em; margin: 0px;
}
.toplink {
font-size: 8pt;
}
</style>
</head>
<body style="background-color: rgb(255, 255, 255);">
<h2>ADOdb Data Dictionary Library for PHP</h2>
<p>V5.06 16 Oct 2008 (c) 2000-2009 John Lim (<a
href="mailto:jlim#natsoft.com">jlim#natsoft.com</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://adodb.sourceforge.net/#download">Download</a>
&nbsp; <a href="http://adodb.sourceforge.net/#docs">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. You can contact them at
dcech#phpwerx.net and richtl#arscognita.com.</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');<br> <font color="#006600"># First create a normal connection</font><br> $db = NewADOConnection('mysql');<br> $db-&gt;Connect(...);<br><br> <font
color="#006600"># Then create a data dictionary object, using this connection</font><br> $dict = <strong>NewDataDictionary</strong>($db);<br><br> <font
color="#006600"># We have a portable declarative data dictionary format in ADOdb, similar to SQL.<br> # Field types use 1 character codes, and fields are separated by commas.<br> # The following example creates three fields: "col1", "col2" and "col3":</font><br> $flds = " <br> <font
color="#663300"><strong> col1 C(32) NOTNULL DEFAULT 'abc',<br> col2 I DEFAULT 0,<br> col3 N(12.2)</strong></font><br> ";<br><br> <font
color="#006600"># We demonstrate creating tables and indexes</font><br> $sqlarray = $dict-&gt;<strong>CreateTableSQL</strong>($tabname, $flds, $taboptarray);<br> $dict-&gt;<strong>ExecuteSQLArray</strong>($sqlarray);<br><br> $idxflds = 'co11, col2';<br> $sqlarray = $dict-&gt;<strong>CreateIndexSQL</strong>($idxname, $tabname, $idxflds);<br> $dict-&gt;<strong>ExecuteSQLArray</strong>($sqlarray);<br></pre>
<h3>More Complex Table Sample</h3>
<p>
The following string will create a table with a primary key event_id and multiple indexes, including one compound index idx_ev1. The ability to define indexes using the INDEX keyword was added in ADOdb 4.94 by Gaetano Giunta.
<pre>
$flds = "
event_id I(11) NOTNULL AUTOINCREMENT PRIMARY,
event_type I(4) NOTNULL <b>INDEX idx_evt</b>,
event_start_date T DEFAULT NULL <b>INDEX id_esd</b>,
event_end_date T DEFAULT '0000-00-00 00:00:00' <b>INDEX id_eted</b>,
event_parent I(11) UNSIGNED NOTNULL DEFAULT 0 <b>INDEX id_evp</b>,
event_owner I(11) DEFAULT 0 <b>INDEX idx_ev1</b>,
event_project I(11) DEFAULT 0 <b>INDEX idx_ev1</b>,
event_times_recuring I(11) UNSIGNED NOTNULL DEFAULT 0,
event_icon C(20) DEFAULT 'obj/event',
event_description X
";
$sqlarray = $db-><b>CreateTableSQL</b>($tablename, $flds);
$dict-><b>ExecuteSQLArray</b>($sqlarray);
</pre>
<h3>Class Factory</h3>
<h4>NewDataDictionary($connection, $drivername=false)</h4>
<p>Creates a new data dictionary object. You pass a database connection object in $connection. The $connection does not have to be actually connected to the database. Some database connection objects are generic (eg. odbtp and odbc). Since 4.53, you can tell ADOdb the actual database with $drivername. E.g.</p>
<pre>
$db = NewADOConnection('odbtp');
$datadict = NewDataDictionary($db, 'mssql'); # force mssql
</pre>
<h3>Class 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<br> $tabname: name of table<br> $fldarray: string (or array) containing field info<br> $taboptarray: array containing table options<br></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, capped to 255 characters.<br> X: Larger varchar, capped to 4000 characters (to be compatible with Oracle). <br> XL: For Oracle, returns CLOB, otherwise the largest varchar size.<br><br> C2: Multibyte varchar<br> X2: Multibyte varchar (largest size)<br><br> B: BLOB (binary large object)<br><br> D: Date (some databases do not support this, and we return a datetime type)<br> T: Datetime or Timestamp accurate to the second.<br> TS: Datetime or Timestamp supporting Sub-second accuracy.<br> Supported by Oracle, PostgreSQL and SQL Server currently. <br> Otherwise equivalent to T.<br>
L: Integer field suitable for storing booleans (0 or 1)<br> I: Integer (mapped to I4)<br> I1: 1-byte integer<br> I2: 2-byte integer<br> I4: 4-byte integer<br> I8: 8-byte integer<br> F: Floating point number<br> N: Numeric or decimal number<br></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.<br> Sets NOTNULL also.<br> AUTOINCREMENT Same as auto.<br> KEY Primary key field. Sets NOTNULL also. Compound keys are supported.<br> PRIMARY Same as KEY.<br> DEF Synonym for DEFAULT for lazy typists.<br> DEFAULT The default value. Character strings are auto-quoted unless<br> the string begins and ends with spaces, eg ' SYSDATE '.<br> NOTNULL If field is not null.<br> DEFDATE Set default value to call function to get today's date.<br> DEFTIMESTAMP Set default to call function to get today's datetime.<br> NOQUOTE Prevents autoquoting of default string values.<br> CONSTRAINTS Additional constraints defined at the end of the field<br> definition.<br></pre>
<p>The Data Dictonary accepts two formats, the older array
specification:</p>
<pre> $flds = array(<br> array('COLNAME', 'DECIMAL', '8.4', 'DEFAULT' =gt; 0, 'NOTNULL'),<br> array('id', 'I' , 'AUTO'),<br> array('`MY DATE`', 'D' , 'DEFDATE'),<br> array('NAME', 'C' , '32', 'CONSTRAINTS' =gt; 'FOREIGN KEY REFERENCES reftable')<br> );<br></pre>
<p>Or the simpler declarative format:</p>
<pre> $flds = "<font color="#660000"><strong><br> COLNAME DECIMAL(8.4) DEFAULT 0 NOTNULL,<br> id I AUTO,<br> `MY DATE` D DEFDATE,<br> NAME C(32) CONSTRAINTS 'FOREIGN KEY REFERENCES reftable'</strong></font><br> ";<br></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 will treat the names as case-sensitive (eg. Oracle) , and
others won'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 <a href="#foreignkey">example</a> 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 "users"
tablespace if using Oracle</em>. And because we specified REPLACE, drop
the table first.</p>
<pre> $taboptarray = array('mysql' =gt; 'TYPE=ISAM', 'oci8' =gt; 'tablespace users', 'REPLACE');</pre>
<p><a name=foreignkey></a>You can also define foreign key constraints. The following is syntax
for postgresql:
</p>
<pre> $taboptarray = array('constraints' =gt; ', 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, $tableOptions=false, $dropOldFlds=false)</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>
<p>Old fields not defined in $flds are not dropped by default. To drop old fields, set $dropOldFlds to true.
<h4>function RenameTableSQL($tabname,$newname)</h4>
<p>Rename a table. Returns the an array of strings, which is the SQL required to rename a table. Since ADOdb 4.53. Contributed by Ralf Becker.</p>
<h4> function RenameColumnSQL($tabname,$oldcolumn,$newcolumn,$flds='')</h4>
<p>Rename a table field. Returns the an array of strings, which is the SQL required to rename a column. The optional $flds is a complete column-defintion-string like for AddColumnSQL, only used by mysql at the moment. Since ADOdb 4.53. Contributed by Ralf Becker.</p>
<h4>function CreateIndexSQL($idxname, $tabname, $flds,
$idxoptarray=false)</h4>
<pre> RETURNS: an array of strings, the sql to be executed, or false<br> $idxname: name of index<br> $tabname: name of table<br> $flds: list of fields as a comma delimited string or an array of strings<br> $idxoptarray: array of index creation options<br></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)<br> BITMAP Create bitmap index (only oci8)<br> UNIQUE Make unique index<br> FULLTEXT Make fulltext index (only mysql)<br> HASH Create hash index (only postgres)<br> DROP Drop legacy index<br></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 MetaTables()</h4>
<h4>function MetaColumns($tab, $upper=true, $schema=false)</h4>
<h4>function MetaPrimaryKeys($tab,$owner=false,$intkey=false)</h4>
<h4>function 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<br> $sqlarray: an array of strings with sql code (no semicolon at the end of string)<br> $contOnError: if true, then continue executing even if error occurs<br></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>Adodb-xmlschema, or AXMLS, is a set of classes that allow the user
to quickly and easily build or upgrade a database on almost any RDBMS
using the excellent ADOdb database library and a simple XML formatted
schema file. Our goal is to give developers a tool that's simple to
use, but that will allow them to create a single file that can build,
upgrade, and manipulate databases on most RDBMS platforms.</p>
<span style="font-weight: bold;"> Installing axmls</span>
<p>The easiest way to install AXMLS to download and install any recent
version of the ADOdb database abstraction library. To install AXMLS
manually, simply copy the adodb-xmlschema.inc.php file and the xsl
directory into your adodb directory.</p>
<span style="font-weight: bold;"> Using AXMLS in Your Application</span>
<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="1.0"?&gt;<br>&lt;schema version="0.2"&gt;<br><br> &lt;table name="users"&gt;<br> &lt;desc&gt;A typical users table for our application.&lt;/desc&gt;<br> &lt;field name="userId" type="I"&gt;<br> &lt;descr&gt;A unique ID assigned to each user.&lt;/descr&gt;<br><br> &lt;KEY/&gt;<br> &lt;AUTOINCREMENT/&gt;<br> &lt;/field&gt;<br> <br> &lt;field name="userName" type="C" size="16"&gt;&lt;NOTNULL/&gt;&lt;/field&gt;<br><br> <br> &lt;index name="userName"&gt;<br> &lt;descr&gt;Put a unique index on the user name&lt;/descr&gt;<br> &lt;col&gt;userName&lt;/col&gt;<br> &lt;UNIQUE/&gt;<br><br> &lt;/index&gt;<br> &lt;/table&gt;<br> <br> &lt;sql&gt;<br> &lt;descr&gt;Insert some data into the users table.&lt;/descr&gt;<br> &lt;query&gt;insert into users (userName) values ( 'admin' )&lt;/query&gt;<br><br> &lt;query&gt;insert into users (userName) values ( 'Joe' )&lt;/query&gt;<br> &lt;/sql&gt;<br>&lt;/schema&gt; <br></pre></pre>
<p>Let's take a detailed look at this schema.</p>
<p>The opening &lt;?xml version="1.0"?&gt; tag is required by XML. The
&lt;schema&gt; tag tells the parser that the enclosed markup defines an
XML schema. The version="0.2" attribute sets <em>the version of the
AXMLS DTD used by the XML schema.</em> </p>
<p>All versions of AXMLS prior to version 1.0 have a schema version of
"0.1". The current schema version is "0.2".</p>
<pre class="listing"><pre>&lt;?xml version="1.0"?&gt;<br>&lt;schema version="0.2"&gt;<br> ...<br>&lt;/schema&gt;<br></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="" attribute
specifies the name of the table that will be created in the database.</p>
<pre class="listing"><pre>&lt;table name="users"&gt;<br><br> &lt;desc&gt;A typical users table for our application.&lt;/desc&gt;<br> &lt;field name="userId" type="I"&gt;<br><br> &lt;descr&gt;A unique ID assigned to each user.&lt;/descr&gt;<br> &lt;KEY/&gt;<br> &lt;AUTOINCREMENT/&gt;<br> &lt;/field&gt;<br> <br> &lt;field name="userName" type="C" size="16"&gt;&lt;NOTNULL/&gt;&lt;/field&gt;<br><br> <br>&lt;/table&gt;<br></pre></pre>
<p>This table is called "users" 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 "userId" of
type "I", 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 "userName" of
type "C", 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="users"&gt;<br> ...<br> <br> &lt;index name="userName"&gt;<br> &lt;descr&gt;Put a unique index on the user name&lt;/descr&gt;<br> &lt;col&gt;userName&lt;/col&gt;<br><br> &lt;UNIQUE/&gt;<br> &lt;/index&gt;<br> <br>&lt;/table&gt;<br></pre></pre>
<p>The &lt;index&gt; tag specifies that an index should be created on
the enclosing table. The name="" 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;<br> &lt;descr&gt;Insert some data into the users table.&lt;/descr&gt;<br> &lt;query&gt;insert into users (userName) values ( 'admin' )&lt;/query&gt;<br><br> &lt;query&gt;insert into users (userName) values ( 'Joe' )&lt;/query&gt;<br>&lt;/sql&gt;<br></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>
<pre class="listing"><pre>&lt;?PHP<br>/* You must tell the script where to find the ADOdb and<br> * the AXMLS libraries.<br> */
require( "path_to_adodb/adodb.inc.php");
require( "path_to_adodb/adodb-xmlschema.inc.php" ); # or adodb-xmlschema03.inc.php
/* Configuration information. Define the schema filename,<br> * RDBMS platform (see the ADODB documentation for valid<br> * platform names), and database connection information here.<br> */<br>$schemaFile = 'example.xml';<br>$platform = 'mysql';<br>$dbHost = 'localhost';<br>$dbName = 'database';<br>$dbUser = 'username';<br>$dbPassword = 'password';<br><br>/* Start by creating a normal ADODB connection.<br> */<br>$db = ADONewConnection( $platform );<br>$db-&gt;Connect( $dbHost, $dbUser, $dbPassword, $dbName );<br><br>/* Use the database connection to create a new adoSchema object.<br> */<br>$schema = new adoSchema( $db );<br><br>/* Call ParseSchema() to build SQL from the XML schema file.<br> * Then call ExecuteSchema() to apply the resulting SQL to <br> * the database.<br> */<br>$sql = $schema-&gt;ParseSchema( $schemaFile );<br>$result = $schema-&gt;ExecuteSchema();<br>?&gt;<br></pre></pre>
<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' );<br>$db-&gt;Connect( 'host', 'user', 'password', 'database' );<br></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">$schema = new adoSchema( $db );<br></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">$schema-&gt;ParseSchema( $schemaFile ); <br>$schema-&gt;ExecuteSchema();</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 Version 3</h3>
<p>In March 2006, we added adodb-xmlschema03.inc.php to the release, which supports version 3 of XML Schema.
The adodb-xmlschema.inc.php remains the same as previous releases, and supports version 2 of XML Schema.
Version 3 provides some enhancements:
<ul>
<li> Support for updating table data during an upgrade.
<li> Support for platform-specific table options and platform negation.
<li> Support for unsigned fields.
<li> Fixed opt and constraint support
<li> Many other fixes such as OPT tag, which allows you to set optional platform settings:
</ul>
<p>Example usage:
<pre>&lt;?xml version="1.0"?>
<b>&lt;schema version="0.3"></b>
&lt;table name="ats_kb">
&lt;descr>ATS KnowledgeBase&lt;/descr>
&lt;opt platform="mysql">TYPE=INNODB&lt;/opt>
&lt;field name="recid" type="I"/>
&lt;field name="organization_code" type="I4"/>
&lt;field name="sub_code" type="C" size="20"/>
etc...
</pre>
<p>To use it, change your code to include adodb-xmlschema03.inc.php.
<h3>Upgrading</h3>
<p>
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>
-542
View File
@@ -1,542 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<style>
pre {
background-color: #eee;
padding: 0.75em 1.5em;
font-size: 12px;
border: 1px solid #ddd;
}
.greybg {
background-color: #eee;
padding: 0.75em 1.5em;
font-size: 12px;
border: 1px solid #ddd;
}
.style1 {color: #660000}
</style>
<title>ADOdb with PHP and Oracle</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</style>
</head>
<body>
<table width=100%><tr><td>
<h2>Using ADOdb with PHP and Oracle: an advanced tutorial</h2>
</td><td><div align="right"><img src=cute_icons_for_site/adodb.gif width="88" height="31"></div></tr></table>
<p><font size="1">(c)2004-2005 John Lim. All rights reserved.</font></p>
<h3>1. Introduction</h3>
<p>Oracle is the most popular commercial database used with PHP. There are many ways of accessing Oracle databases in PHP. These include:</p>
<ul>
<li>The oracle extension</li>
<li>The oci8 extension</li>
<li>PEAR DB library</li>
<li>ADOdb library</li>
</ul>
<p>The wide range of choices is confusing to someone just starting with Oracle and PHP. I will briefly summarize the differences, and show you the advantages of using <a href="http://adodb.sourceforge.net/">ADOdb</a>. </p>
<p>First we have the C extensions which provide low-level access to Oracle functionality. These C extensions are precompiled into PHP, or linked in dynamically when the web server starts up. Just in case you need it, here's a <a href=http://www.oracle.com/technology/tech/opensource/php/apache/inst_php_apache_linux.html>guide to installing Oracle and PHP on Linux</a>.</p>
<table width="75%" border="1" align="center">
<tr valign="top">
<td nowrap><b>Oracle extension</b></td>
<td>Designed for Oracle 7 or earlier. This is obsolete.</td>
</tr>
<tr valign="top">
<td nowrap><b>Oci8 extension</b></td>
<td> Despite it's name, which implies it is only for Oracle 8i, this is the standard method for accessing databases running Oracle 8i, 9i or 10g (and later).</td>
</tr>
</table>
<p>Here is an example of using the oci8 extension to query the <i>emp</i> table of the <i>scott</i> schema with bind parameters:
<pre>
$conn = OCILogon("scott","tiger", $tnsName);
$stmt = OCIParse($conn,"select * from emp where empno > :emp order by empno");
$emp = 7900;
OCIBindByName($stmt, ':emp', $emp);
$ok = OCIExecute($stmt);
while (OCIFetchInto($stmt,$arr)) {
print_r($arr);
echo "&lt;hr>";
}
</pre>
<p>This generates the following output:
<div class=greybg>
Array ( [0] => 7902 [1] => FORD [2] => ANALYST [3] => 7566 [4] => 03/DEC/81 [5] => 3000 [7] => 20 )
<hr />
Array ( [0] => 7934 [1] => MILLER [2] => CLERK [3] => 7782 [4] => 23/JAN/82 [5] => 1300 [7] => 10 )
</div>
<p>We also have many higher level PHP libraries that allow you to simplify the above code. The most popular are <a href="http://pear.php.net/">PEAR DB</a> and <a href="http://adodb.sourceforge.net/">ADOdb</a>. Here are some of the differences between these libraries:</p>
<table width="75%" border="1" align="center">
<tr>
<td><b>Feature</b></td>
<td><b>PEAR DB 1.6</b></td>
<td><b>ADOdb 4.52</b></td>
</tr>
<tr valign="top">
<td>General Style</td>
<td>Simple, easy to use. Lacks Oracle specific functionality.</td>
<td>Has multi-tier design. Simple high-level design for beginners, and also lower-level advanced Oracle functionality.</td>
</tr>
<tr valign="top">
<td>Support for Prepare</td>
<td>Yes, but only on one statement, as the last prepare overwrites previous prepares.</td>
<td>Yes (multiple simultaneous prepare's allowed)</td>
</tr>
<tr valign="top">
<td>Support for LOBs</td>
<td>No</td>
<td>Yes, using update semantics</td>
</tr>
<tr valign="top">
<td>Support for REF Cursors</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr valign="top">
<td>Support for IN Parameters</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr valign="top">
<td>Support for OUT Parameters</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr valign="top">
<td>Schema creation using XML</td>
<td>No</td>
<td>Yes, including ability to define tablespaces and constraints</td>
</tr>
<tr valign="top">
<td>Provides database portability features</td>
<td>No</td>
<td>Yes, has some ability to abstract features that differ between databases such as dates, bind parameters, and data types.</td>
</tr>
<tr valign="top">
<td>Performance monitoring and tracing</td>
<td>No</td>
<td>Yes. SQL can be traced and linked to web page it was executed on. Explain plan support included.</td>
</tr>
<tr valign="top">
<td>Recordset caching for frequently used queries</td>
<td>No</td>
<td>Yes. Provides great speedups for SQL involving complex <i>where, group-by </i>and <i>order-by</i> clauses.</td>
</tr>
<tr valign="top">
<td>Popularity</td>
<td>Yes, part of PEAR release</td>
<td>Yes, many open source projects are using this software, including PostNuke, Xaraya, Mambo, Tiki Wiki.</td>
</tr>
<tr valign="top">
<td>Speed</td>
<td>Medium speed.</td>
<td>Very high speed. Fastest database abstraction library available for PHP. <a href="http://phplens.com/lens/adodb/">Benchmarks are available</a>.</td>
</tr>
<tr valign="top">
<td>High Speed Extension available</td>
<td>No</td>
<td>Yes. You can install the optional ADOdb extension, which reimplements the most frequently used parts of ADOdb as fast C code. Note that the source code version of ADOdb runs just fine without this extension, and only makes use of the extension if detected.</td>
</tr>
</table>
<p> PEAR DB is good enough for simple web apps. But if you need more power, you can see ADOdb offers more sophisticated functionality. The rest of this article will concentrate on using ADOdb with Oracle. You can find out more about <a href="#connecting">connecting to Oracle</a> later in this guide.</p>
<h4>ADOdb Example</h4>
<p>In ADOdb, the above oci8 example querying the <i>emp</i> table could be written as:</p>
<pre>
include "/path/to/adodb.inc.php";
$db = NewADOConnection("oci8");
$db->Connect($tnsName, "scott", "tiger");
$rs = $db->Execute("select * from emp where empno>:emp order by empno",
array('emp' => 7900));
while ($arr = $rs->FetchRow()) {
print_r($arr);
echo "&lt;hr>";
}
</pre>
<p>The Execute( ) function returns a recordset object, and you can retrieve the rows returned using $recordset-&gt;FetchRow( ). </p>
<p>If we ignore the initial connection preamble, we can see the ADOdb version is much easier and simpler:</p>
<table width="100%" border="1">
<tr valign="top" bgcolor="#FFFFFF">
<td width="50%" bgcolor="#e0e0e0"><b>Oci8</b></td>
<td bgcolor="#e0e0e0"><b>ADOdb</b></td>
</tr>
<tr valign="top" bgcolor="#CCCCCC">
<td><pre><font size="1">$stmt = <b>OCIParse</b>($conn,
"select * from emp where empno > :emp");
$emp = 7900;
<b>OCIBindByName</b>($stmt, ':emp', $emp);
$ok = <b>OCIExecute</b>($stmt);
while (<b>OCIFetchInto</b>($stmt,$arr)) {
print_r($arr);
echo "&lt;hr>";
} </font></pre></td>
<td><pre><font size="1">$recordset = $db-><b>Execute</b>("select * from emp where empno>:emp",
array('emp' => 7900));
while ($arr = $recordset-><b>FetchRow</b>()) {
print_r($arr);
echo "&lt;hr>";
}</font></pre></td>
</tr>
</table>
<p>&nbsp;</p>
<h3>2. ADOdb Query Semantics</h3>
<p>You can also query the database using the standard Microsoft ADO MoveNext( ) metaphor. The data array for the current row is stored in the <i>fields</i> property of the recordset object, $rs.
MoveNext( ) offers the highest performance among all the techniques for iterating through a recordset:
<pre>
$rs = $db->Execute("select * from emp where empno>:emp", array('emp' => 7900));
while (!$rs->EOF) {
print_r($rs->fields);
$rs->MoveNext();
}
</pre>
<p>And if you are interested in having the data returned in a 2-dimensional array, you can use:
<pre>
$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));
</pre>
<p>Now to obtain only the first row as an array:
<pre>
$arr = $db->GetRow("select * from emp where empno=:emp", array('emp' => 7900));
</pre>
<p>Or to retrieve only the first field of the first row:
<pre>
$arr = $db->GetOne("select ename from emp where empno=:emp", array('emp' => 7900));
</pre>
<p>For easy pagination support, we provide the SelectLimit function. The following will perform a select query, limiting it to 100 rows, starting from row 201 (row 1 being the 1st row):
<pre>
$offset = 200; $limitrows = 100;
$rs = $db->SelectLimit('select * from table', $limitrows, $offset);
</pre>
<p>The $offset parameter is optional.
<h4>Array Fetch Mode</h4>
<p>When data is being returned in an array, you can choose the type of array the data is returned in.
<ol>
<li> Numeric indexes - use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_NUM).</font></li>
<li>Associative indexes - the keys of the array are the names of the fields (in upper-case). Use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_ASSOC)</font><font face="Courier New, Courier, mono">.</font></li>
<li>Both numeric and associative indexes - use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_BOTH).</font></li>
</ol>
<p>The default is ADODB_FETCH_BOTH for Oracle.</p>
<h4><b>Caching</b></h4>
<p>You can define a database cache directory using $ADODB_CACHE_DIR, and cache the results of frequently used queries that rarely change. This is particularly useful for SQL with complex where clauses and group-by's and order-by's. It is also good for relieving heavily-loaded database servers.</p>
<p>This example will cache the following select statement for 3600 seconds (1 hour):</p>
<pre>
$ADODB_CACHE_DIR = '/var/adodb/tmp';
$rs = $db->CacheExecute(3600, "select names from allcountries order by 1");
</pre>
There are analogous CacheGetArray(
), CacheGetRow( ), CacheGetOne( ) and CacheSelectLimit( ) functions. The first parameter is the number of seconds to cache. You can also pass a bind array as a 3rd parameter (not shown above).
<p>There is an alternative syntax for the caching functions. The first parameter is omitted, and you set the cacheSecs
property of the connection object:
<pre>
$ADODB_CACHE_DIR = '/var/adodb/tmp';
$connection->cacheSecs = 3600;
$rs = $connection->CacheExecute($sql, array('id' => 1));
</pre>
<h3>&nbsp;</h3>
<h3>3. Using Prepare( ) For Frequently Used Statements</h3>
<p>Prepare( ) is for compiling frequently used SQL statement for reuse. For example, suppose we have a large array which needs to be inserted into an Oracle database. The following will result in a massive speedup in query execution (at least 20-40%), as the SQL statement only needs to be compiled once:</p>
<pre>
$stmt = $db->Prepare('insert into table (field1, field2) values (:f1, :f2)');
foreach ($arrayToInsert as $key => $value) {
$db->Execute($stmt, array('f1' => $key, 'f2' => $val);
}
</pre>
<p>&nbsp;</p>
<h3>4. Working With LOBs</h3>
<p>Oracle treats data which is more than 4000 bytes in length specially. These are called Large Objects, or LOBs for short. Binary LOBs are BLOBs, and character LOBs are CLOBs. In most Oracle libraries, you need to do a lot of work to process LOBs, probably because Oracle designed it to work in systems with little memory. ADOdb tries to make things easy by assuming the LOB can fit into main memory. </p>
<p>ADOdb will transparently handle LOBs in <i>select</i> statements. The LOBs are automatically converted to PHP variables without any special coding.</p>
<p>For updating records with LOBs, the functions UpdateBlob( ) and UpdateClob( ) are provided. Here's a BLOB example. The parameters should be self-explanatory:
<pre>
$ok = $db->Execute("insert into aTable (id, name, ablob)
values (aSequence.nextVal, 'Name', null)");
if (!$ok) return LogError($db-&gt;ErrorMsg());
<font color="#006600"># params: $tableName, $blobFieldName, $blobValue, $whereClause</font>
$db->UpdateBlob('aTable', 'ablob', $blobValue, 'id=aSequence.currVal');
</pre>
<p>and the analogous CLOB example:
<pre>
$ok = $db->Execute("insert into aTable (id, name, aclob)
values (aSequence.nextVal, 'Name', null)");
if (!$ok) return LogError($db-&gt;ErrorMsg());
$db->UpdateClob('aTable', 'aclob', $clobValue, 'id=aSequence.currVal');
</pre>
<p>Note that LogError( ) is a user-defined function, and not part of ADOdb.
<p>Inserting LOBs is more complicated. Since ADOdb 4.55, we allow you to do this
(assuming that the <em>photo</em> field is a BLOB, and we want to store $blob_data into
this field, and the primary key is the <em>id</em> field):
<pre>
$sql = <span class="style1">"INSERT INTO photos ( ID, photo) ".
"VALUES ( :id, empty_blob() )".
" RETURNING photo INTO :xx"</span>;
$stmt = $db->PrepareSP($sql);
$db->InParameter($stmt, $<strong>id</strong>, <span class="style1">'id'</span>);
$blob = $db->InParameter($stmt, $<strong>blob_data</strong>, <span class="style1">'xx'</span>,-1, OCI_B_BLOB);
$db->StartTrans();
$ok = $db->Execute($stmt);
$db->CompleteTrans();
</pre>
<p>
<h3>5. REF CURSORs</h3>
<p>Oracle recordsets can be passed around as variables called REF Cursors. For example, in PL/SQL, we could define a function <i>open_tab</i> that returns a REF CURSOR in the first parameter:</p>
<pre>
TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;
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;
</pre>
<p>In ADOdb, we could access this REF Cursor using the ExecuteCursor() function. The following will find
all table names that begin with 'A' in the current schema:
<pre>
$rs = $db->ExecuteCursor("BEGIN open_tab(:refc,'A%'); END;",'refc');
while ($arr = $rs->FetchRow()) print_r($arr);
</pre>
<p>The first parameter is the PL/SQL statement, and the second parameter is the name of the REF Cursor.
</p>
<p>&nbsp;</p>
<h3>6. In and Out Parameters</h3>
<p>The following PL/SQL
stored procedure requires an input variable, and returns a result into an output variable:
<pre>
PROCEDURE data_out(input IN VARCHAR, output OUT VARCHAR) IS
BEGIN
output := 'I love '||input;
END;
</pre>
<p>The following ADOdb code allows you to call the stored procedure:</p>
<pre>
$stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");
$input = 'Sophia Loren';
$db->InParameter($stmt,$input,'a1');
$db->OutParameter($stmt,$output,'a2');
$ok = $db->Execute($stmt);
if ($ok) echo ($output == 'I love Sophia Loren') ? 'OK' : 'Failed';
</pre>
<p>PrepareSP( ) is a special function that knows about bind parameters.
The main limitation currently is that IN OUT parameters do not work.
<h4>Bind Parameters and REF CURSORs</h4>
<p>We could also rewrite the REF CURSOR example to use InParameter (requires ADOdb 4.53 or later):
<pre>
$stmt = $db->PrepareSP("BEGIN adodb.open_tab(:refc,:tabname); END;");
$input = 'A%';
$db->InParameter($stmt,$input,'tabname');
$rs = $db->ExecuteCursor($stmt,'refc');
while ($arr = $rs->FetchRow()) print_r($arr);
</pre>
<h4>Bind Parameters and LOBs</h4>
<p>You can also operate on LOBs. In this example, we have IN and OUT parameters using CLOBs.
<pre>
$text = 'test test test';
$sql = "declare rs clob; begin :rs := lobinout(:sa0); end;";
$stmt = $conn -> PrepareSP($sql);
$conn -> InParameter($stmt,$text,'sa0', -1, OCI_B_CLOB); # -1 means variable length
$rs = '';
$conn -> OutParameter($stmt,$rs,'rs', -1, OCI_B_CLOB);
$conn -> Execute($stmt);
echo "return = ".$rs."&lt;br>";
</pre>
<p>Similarly, you can use the constant OCI_B_BLOB to indicate that you are using BLOBs.
<h4>Reusing Bind Parameters with CURSOR_SHARING=FORCE</h4>
<p>Many web programmers do not care to use bind parameters, and prefer to enter the SQL directly. So instead of:</p>
<pre>
$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));
</pre>
<p>They prefer entering the values inside the SQL:
<pre>
$arr = $db->GetArray("select * from emp where empno>7900");
</pre>
<p>This reduces Oracle performance because Oracle will reuse compiled SQL which is identical to previously compiled SQL. The above example with the values inside the SQL
is unlikely to be reused. As an optimization, from Oracle 8.1 onwards, you can set the following session parameter after you login:
<pre>
ALTER SESSION SET CURSOR_SHARING=FORCE
</pre>
<p>This will force Oracle to convert all such variables (eg. the 7900 value) into constant bind parameters, improving SQL reuse.</p>
<p>More <a href="http://phplens.com/adodb/code.initialization.html#speed">speedup tips</a>.</p>
<p>&nbsp;</p>
<h3>7. Dates and Datetime in ADOdb</h3>
<p>There are two things you need to know about dates in ADOdb. </p>
<p>First, to ensure cross-database compability, ADOdb assumes that dates are returned in ISO format (YYYY-MM-DD H24:MI:SS).</p>
<p>Secondly, since Oracle treats dates and datetime as the same data type, we decided not to display the time in the default date format. So on login, ADOdb will set the NLS_DATE_FORMAT to 'YYYY-MM-DD'. If you prefer to show the date and time by default, do this:</p>
<pre>
$db = NewADOConnection('oci8');
$db->NLS_DATE_FORMAT = 'RRRR-MM-DD HH24:MI:SS';
$db->Connect($tns, $user, $pwd);
</pre>
<p>Or execute:</p>
<pre>$sql = quot;ALTER SESSION SET NLS_DATE_FORMAT = 'RRRR-MM-DD HH24:MI:SS'&quot;;
$db-&gt;Execute($sql);
</pre>
<p>If you are not concerned about date portability and do not use ADOdb's portability layer, you can use your preferred date format instead.
<p>
<h3>8. Database Portability Layer</h3>
<p>ADOdb provides the following functions for portably generating SQL functions
as strings to be merged into your SQL statements:</p>
<table width="75%" border="1" align=center>
<tr>
<td width=30%><b>Function</b></td>
<td><b>Description</b></td>
</tr>
<tr>
<td>DBDate($date)</td>
<td>Pass in a UNIX timestamp or ISO date and it will convert it to a date
string formatted for INSERT/UPDATE</td>
</tr>
<tr>
<td>DBTimeStamp($date)</td>
<td>Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp
string formatted for INSERT/UPDATE</td>
</tr>
<tr>
<td>SQLDate($date, $fmt)</td>
<td>Portably generate a date formatted using $fmt mask, for use in SELECT
statements.</td>
</tr>
<tr>
<td>OffsetDate($date, $ndays)</td>
<td>Portably generate a $date offset by $ndays.</td>
</tr>
<tr>
<td>Concat($s1, $s2, ...)</td>
<td>Portably concatenate strings. Alternatively, for mssql use mssqlpo driver,
which allows || operator.</td>
</tr>
<tr>
<td>IfNull($fld, $replaceNull)</td>
<td>Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL.</td>
</tr>
<tr>
<td>Param($name)</td>
<td>Generates bind placeholders, using ? or named conventions as appropriate.</td>
</tr>
<tr><td>$db->sysDate</td><td>Property that holds the SQL function that returns today's date</td>
</tr>
<tr><td>$db->sysTimeStamp</td><td>Property that holds the SQL function that returns the current
timestamp (date+time).
</td>
</tr>
<tr>
<td>$db->concat_operator</td><td>Property that holds the concatenation operator
</td>
</tr>
<tr><td>$db->length</td><td>Property that holds the name of the SQL strlen function.
</td></tr>
<tr><td>$db->upperCase</td><td>Property that holds the name of the SQL strtoupper function.
</td></tr>
<tr><td>$db->random</td><td>Property that holds the SQL to generate a random number between 0.00 and 1.00.
</td>
</tr>
<tr><td>$db->substr</td><td>Property that holds the name of the SQL substring function.
</td></tr>
</table>
<p>ADOdb also provides multiple oracle oci8 drivers for different scenarios:</p>
<table width="75%" border="1" align="center">
<tr>
<td nowrap><b>Driver Name</b></td>
<td><b>Description</b></td>
</tr>
<tr>
<td>oci805 </td>
<td>Specifically for Oracle 8.0.5. This driver has a slower SelectLimit( ).</td>
</tr>
<tr>
<td>oci8</td>
<td>The default high performance driver. The keys of associative arrays returned in a recordset are upper-case.</td>
</tr>
<tr>
<td>oci8po</td>
<td> The portable Oracle driver. Slightly slower than oci8. This driver uses ? instead of :<i>bindvar</i> for binding variables, which is the standard for other databases. Also the keys of associative arrays are in lower-case like other databases.</td>
</tr>
</table>
<p>Here's an example of calling the <i>oci8po</i> driver. Note that the bind variables use question-mark:</p>
<pre>$db = NewADOConnection('oci8po');
$db-&gt;Connect($tns, $user, $pwd);
$db-&gt;Execute(&quot;insert into atable (f1, f2) values (?,?)&quot;, array(12, 'abc'));</pre>
<p>&nbsp;<a name=connecting></a>
<h3>9. Connecting to Oracle</h3>
<p>Before you can use ADOdb, you need to have the Oracle client installed and setup the oci8 extension. This extension comes pre-compiled for Windows (but you still need to enable it in the php.ini file). For information on compiling the oci8 extension for PHP and Apache on Unix, there is an excellent guide at <a href="http://www.oracle.com/technology/tech/opensource/php/apache/inst_php_apache_linux.html">oracle.com</a>. </p>
<h4>Should You Use Persistent Connections</h4>
<p>One question that is frequently asked is should you use persistent connections to Oracle. Persistent connections allow PHP to recycle existing connections, reusing them after the previous web pages have completed. Non-persistent connections close automatically after the web page has completed. Persistent connections are faster because the cost of reconnecting is expensive, but there is additional resource overhead. As an alternative, Oracle allows you to pool and reuse server processes; this is called <a href="http://www.cise.ufl.edu/help/database/oracle-docs/server.920/a96521/manproc.htm#13132">Shared Server</a> (also known as MTS).</p>
<p>The author's benchmarks suggest that using non-persistent connections and the Shared Server configuration offer the best performance. If Shared Server is not an option, only then consider using persistent connections.</p>
<h4>Connection Examples</h4>
<p>Just in case you are having problems connecting to Oracle, here are some examples:</p>
<p>a. PHP and Oracle reside on the same machine, use default SID, with non-persistent connections:</p>
<pre> $conn = NewADOConnection('oci8');
$conn-&gt;Connect(false, 'scott', 'tiger');</pre>
<p>b. TNS Name defined in tnsnames.ora (or ONAMES or HOSTNAMES), eg. 'myTNS', using persistent connections:</p>
<pre> $conn = NewADOConnection('oci8');
$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->connectSID = true;
$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>
<p>e. Oracle connection string:
<pre> $cstr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$host)(PORT=$port))
(CONNECT_DATA=(SID=$sid)))";
$conn-&gt;Connect($cstr, 'scott', 'tiger');
</pre>
<p>f. ADOdb data source names (dsn):
<pre>
$dsn = 'oci8://user:pwd@tnsname/?persist'; # persist is optional
$conn = ADONewConnection($dsn); # no need for Connect/PConnect
$dsn = 'oci8://user:pwd@host/sid';
$conn = ADONewConnection($dsn);
$dsn = 'oci8://user:pwd@/'; # oracle on local machine
$conn = ADONewConnection($dsn);</pre>
<p>With ADOdb data source names,
you don't have to call Connect( ) or PConnect( ).
</p>
<p>&nbsp;</p>
<h3>10. Error Checking</h3>
<p>The examples in this article are easy to read but a bit simplistic because we ignore error-handling. Execute( ) and Connect( ) will return false on error. So a more realistic way to call Connect( ) and Execute( ) is:
<pre>function InvokeErrorHandler()
{<br>global $db; ## assume global
MyLogFunction($db-&gt;ErrorNo(), $db-&gt;ErrorMsg());
}
if (!$db-&gt;Connect($tns, $usr, $pwd)) InvokeErrorHandler();
$rs = $db->Execute("select * from emp where empno>:emp order by empno",
array('emp' => 7900));
if (!$rs) return InvokeErrorHandler();
while ($arr = $rs->FetchRow()) {
print_r($arr);
echo "&lt;hr>";
}
</pre>
<p>You can retrieve the error message and error number of the last SQL statement executed from ErrorMsg( ) and ErrorNo( ). You can also <a href=http://phplens.com/adodb/using.custom.error.handlers.and.pear_error.html>define a custom error handler function</a>.
ADOdb also supports throwing exceptions in PHP5.
<p>&nbsp;</p>
<h3>Handling Large Recordsets (added 27 May 2005)</h3>
The oci8 driver does not support counting the number of records returned in a SELECT statement, so the function RecordCount()
is emulated when the global variable $ADODB_COUNTRECS is set to true, which is the default.
We emulate this by buffering all the records. This can take up large amounts of memory for big recordsets.
Set $ADODB_COUNTRECS to false for the best performance.
<p>
This variable is checked every time a query is executed, so you can selectively choose which recordsets to count.
<p>&nbsp;</p>
<h3>11. Other ADOdb Features</h3>
<p><a href="http://phplens.com/lens/adodb/docs-datadict.htm">Schema generation</a>. This allows you to define a schema using XML and import it into different RDBMS systems portably.</p>
<p><a href="http://phplens.com/lens/adodb/docs-perf.htm">Performance monitoring and tracing</a>. Highlights of performance monitoring include identification of poor and suspicious SQL, with explain plan support, and identifying which web pages the SQL ran on.</p>
<p>&nbsp;</p>
<h3>12. Download</h3>
<p>You can <a href="http://adodb.sourceforge.net/#download">download ADOdb from sourceforge</a>. ADOdb uses a BSD style license. That means that it is free for commercial use, and redistribution without source code is allowed.</p>
<p>&nbsp;</p>
<h3>13. Resources</h3>
<ul>
<li>Oracle's <a href="http://www.oracle.com/technology/pub/articles/php_experts/index.html">Hitchhiker Guide to PHP</a></li>
<li>OTN article on <a href=http://www.oracle.com/technology/pub/articles/deployphp/lim_deployphp.html>Optimizing PHP and Oracle</a> by this author.
<li>Oracle has an excellent <a href="http://www.oracle.com/technology/tech/opensource/php/php_troubleshooting_faq.html">FAQ on PHP</a></li>
<li>PHP <a href="http://php.net/oci8">oci8</a> manual pages</li>
<li><a href=http://phplens.com/lens/lensforum/topics.php?id=4>ADOdb forums</a>.
</ul>
</body>
</html>
-965
View File
@@ -1,965 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ADOdb Performance Monitoring Library</title>
<style type="text/css">
body, td {
/*font-family: Arial, Helvetica, sans-serif;*/
font-size: 11pt;
}
pre {
font-size: 9pt;
background-color: #EEEEEE; padding: .5em; margin: 0px;
}
.toplink {
font-size: 8pt;
}
</style>
</head>
<body>
<h3>The ADOdb Performance Monitoring Library</h3>
<p>V5.06 16 Oct 2008 (c) 2000-2009 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://adodb.sourceforge.net/#download">Download</a>
&nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
</p>
<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: </p>
<ul>
<li>A quick health check of your database server using <code>$perf-&gt;HealthCheck()</code>
or <code>$perf-&gt;HealthCheckCLI()</code>. </li>
<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>
<li>Gives you an API to build database monitoring tools for a server
farm, for example calling <code>$perf-&gt;DBParameter('data cache hit
ratio')</code> returns this very important statistic in a database
independant manner. </li>
</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:
</p>
<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<br>include_once('adodb.inc.php');<br>session_start(); <font
color="#006600"># session variables required for monitoring</font><br>$conn = ADONewConnection($driver);<br>$conn-&gt;Connect($server,$user,$pwd,$db);<br>$perf =&amp; NewPerfMonitor($conn);<br>$perf-&gt;UI($pollsecs=5);<br>?&gt;<br></pre>
<p>It is also possible to retrieve a single database parameter:</p>
<pre>$size = $perf-&gt;DBParameter('data cache size');<br></pre>
<p>
Thx to Fernando Ortiz for the informix module. </p>
<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>
<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-&gt;UI(). </p>
<p> </p>
<pre>define('ADODB_PERF_NO_RUN_SQL',1);</pre>
<p>Sample output follows below:</p>
<table bgcolor="lightyellow" border="1" width="100%">
<tbody>
<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></td>
</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></td>
</tr>
</tbody>
</table>
<table bgcolor="white" border="1">
<tbody>
<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>
</tbody>
</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 -- <br> MyISAM cache hit ratio =gt; 56.5635738832 <br> InnoDB cache hit ratio =gt; 0 <br> sql cache hit ratio =gt; 0 <br> -- IO -- <br> data reads =gt; 2622 <br> data writes =gt; 2415.5 <br> -- Data Cache -- <br> MyISAM data cache size =gt; 512K <br> BDB data cache size =gt; 8388600<br> InnoDB data cache size =gt; 8M<br> -- Memory Pools -- <br> read buffer size =gt; 131072 <br> sort buffer size =gt; 65528 <br> table cache =gt; 4 <br> -- Connections -- <br> current connections =gt; 3<br> max connections =gt; 100</pre>
<p><font face="Courier New, Courier, mono">function <b>Poll</b>($pollSecs=5)
</font> </p>
<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:
</p>
<pre>Accumulating statistics...<br> Time WS-CPU% Hit% Sess Reads/s Writes/s<br>11:08:30 0.7 56.56 1 0.0000 0.0000<br>11:08:33 1.8 56.56 2 0.0000 0.0000<br>11:08:36 11.1 56.55 3 2.5000 0.0000<br>11:08:39 9.8 56.55 2 3.1121 0.0000<br>11:08:42 2.8 56.55 1 0.0000 0.0000<br>11:08:45 7.4 56.55 2 0.0000 1.5000<br></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>
<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>
<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-&gt;LogSQL(true) is enabled. The adodb_logsql table is
populated using <a href="docs-adodb.htm#logsql">$conn-&gt;LogSQL</a>.
</p>
<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>
<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>
<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-&gt;LogSQL(true) is enabled. The adodb_logsql table is
populated using <a href="docs-adodb.htm#logsql">$conn-&gt;LogSQL</a>.
</p>
<p>For Oracle, Ixora Expensive SQL returns a list of SQL statements
that are taking the most CPU load when run.
</p>
<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>
<p>Data is taken from the adodb_logsql table, where the sql statements
are logged when
$connection-&gt;LogSQL(true) is enabled.
</p>
<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("data cache size").</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>$ADODB_PERF_MIN</h3>
<p>New in adodb 4.97/5.03 is this global variable, which controls whether sql timings which are too small are not saved. Currently it defaults
to 0.05 (seconds). This means that all sql's which are faster than 0.05 seconds to execute are not saved.
<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-&gt;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-&gt;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<br> array("show variables", 'table_cache'), # array (type 1b)<br> '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 bgcolor="white" border="1">
<tbody>
<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>
</tbody>
</table>
<p>&nbsp;</p>
<p><a name="informix"></a>
<table bgcolor="white" border="1">
<tbody>
<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>
</tbody>
</table>
</p>
<p>&nbsp;</p>
<p><a name="mysql" id="mysql"></a></p>
<table bgcolor="white" border="1">
<tbody>
<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>
</tbody>
</table>
<p>&nbsp;</p>
<p><a name="mssql" id="mssql"></a></p>
<table bgcolor="white" border="1">
<tbody>
<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>
</tbody>
</table>
<p>&nbsp;</p>
<p><a name="oci8" id="oci8"></a></p>
<table bgcolor="white" border="1">
<tbody>
<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 &lt; 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>
</tbody>
</table>
<h3>Suspicious SQL</h3>
<table bgcolor="white" border="1">
<tbody>
<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>
</tbody>
</table>
<h3>Expensive SQL</h3>
<table bgcolor="white" border="1">
<tbody>
<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>
</tbody>
</table>
<p><a name="postgres" id="postgres"></a></p>
<table bgcolor="white" border="1">
<tbody>
<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>
</tbody>
</table>
</body>
</html>
-336
View File
@@ -1,336 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ADODB Session Management 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;
background-color: #EEEEEE; padding: .5em; margin: 0px;
}
.toplink {
font-size: 8pt;
}
</style>
</head>
<body style="background-color: rgb(255, 255, 255);">
<h1>ADODB Session 2 Management Manual</h1>
<p>
V5.06 16 Oct 2008 (c) 2000-2009 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>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a>
&nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
</p>
<h2>Introduction</h2>
<p> This document discusses the newer session handler adodb-session2.php. If
you have used the older adodb-session.php, then be forewarned that you will
need to alter your session table format. Otherwise everything is <a href="#compat">backward
compatible</a>.
Here are the <a href="docs-session.old.htm">older
docs</a> for
adodb-session.php.</p>
<h2>Why Session Variables in a Database? </h2>
<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>
<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>
<p>The default method of storing sessions is to store it in a file.
However if you have special needs such as you:
</p>
<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>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>
<p>These records will be garbage collected based on the php.ini [session] timeout settings.
You can register a notification function to notify you when the record has expired and
is about to be freed by the garbage collector.</p>
<p>An alternative to using a database backed session handler is to use <a href="http://www.danga.com/memcached/">memcached</a>.
This is a distributed memory based caching system suitable for storing session
information.
</p>
<h2> The Improved Session Handler</h2>
<p>In ADOdb 4.91, we added a new session handler, in adodb-session2.php.
It features the following improvements:
<ul>
<li>Fully supports server farms using a new database table format. The
previous version used the web server time for timestamps, which can cause problems
on a system with multiple web servers with possibly inconsistent
times. The new version uses the database server time instead for all timestamps.
<li>The older database table format is obsolete. The database table must be modified
to support storage of the database server time mentioned above. Also the field
named DATA has been changed to SESSDATA. In some databases, DATA is a reserved
word.
<li>The functions dataFieldName() and syncSeconds() is obsolete.
</ul>
<p>Usage is
<pre>
include_once("adodb/session/adodb-session2.php");
ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);
session_start();
<font
color="#004040">#<br># Test session vars, the following should increment on refresh<br>#<br>$_SESSION['AVAR'] += 1;<br>print "&lt;p&gt;\$_SESSION['AVAR']={$_SESSION['AVAR']}&lt;/p&gt;";</font>
</pre>
<p>When the session is created in session_start( ), the global variable $<b>ADODB_SESS_CONN</b> holds
the connection object.
<p>The default name of the table is sessions2. If you want to override it:
<pre>
include_once("adodb/session/adodb-session2.php");
$options['table'] = 'mytablename';
ADOdb_Session::config($driver, $host, $user, $password, $database,$options);
session_start();
</pre>
<h3>ADOdb Session Handler Features</h3>
<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>
<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>
<li>Support for large amounts of session data with CLOBs (see
adodb-session-clob2.php). Useful
for Oracle. </li>
<li>Support for encrypted session data, see
adodb-cryptsession2.php. Enabling encryption is simply a matter of
including adodb-cryptsession2.php instead of adodb-session2.php. </li>
</ul>
<h3>Session Handler Files </h3>
<p>There are 3 session management files that you can use:
</p>
<pre>adodb-session2.php : The default<br>adodb-cryptsession2.php : Use this if you want to store encrypted session data in the database<br>adodb-session-clob2.php : Use this if you are storing DATA in clobs and you are NOT using oci8 driver</pre>
<h2><strong>Usage Examples</strong></h2>
<p>To force non-persistent connections, call <font color="#004040"><b>Persist</b></font>() first before session_start():
<pre>
<font color="#004040">
include_once("adodb/session/adodb-session2.php");
$driver = 'mysql'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);<b><br>ADOdb_session::Persist($connectMode=false);</b>
session_start();<br> </font>
</pre>
<p> The parameter to the Persist( ) method sets the connection mode. You can
pass the following:</p>
<table width="50%" border="1">
<tr>
<td><b>$connectMode</b></td>
<td><b>Connection Method</b></td>
</tr>
<tr>
<td>true</td>
<td><p>PConnect( )</p></td>
</tr>
<tr>
<td>false</td>
<td>Connect( )</td>
</tr>
<tr>
<td>'N'</td>
<td>NConnect( )</td>
</tr>
<tr>
<td>'P'</td>
<td>PConnect( )</td>
</tr>
<tr>
<td>'C'</td>
<td>Connect( )</td>
</tr>
</table>
<p>To use a encrypted sessions, simply replace the file adodb-session2.php:</p>
<pre> <font
color="#004040"><b><br>include('adodb/session/adodb-cryptsession2.php');</b><br>$driver = 'mysql'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);<b><br>adodb_sess_open(false,false,$connectMode=false);</b>
session_start();<br></font></pre>
<p>And the same technique for adodb-session-clob2.php:</p>
<pre> <font
color="#004040"><br><b>include('adodb/session/adodb-session2-clob2.php');</b><br>$driver = 'oci8'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);<b><br>adodb_sess_open(false,false,$connectMode=false);</b>
session_start();</font></pre>
<h2>Installation</h2>
<p>1. Create this table in your database. Here is the MySQL version:
<pre> <a
name="sessiontab"></a> <font color="#004040">
CREATE TABLE sessions2(
sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
expiry DATETIME NOT NULL ,
expireref VARCHAR( 250 ) DEFAULT '',
created DATETIME NOT NULL ,
modified DATETIME NOT NULL ,
sessdata LONGTEXT,
PRIMARY KEY ( sesskey ) ,
INDEX sess2_expiry( expiry ),
INDEX sess2_expireref( expireref )
)</font></pre>
<p> For PostgreSQL, use:
<pre>CREATE TABLE sessions2(
sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
expiry TIMESTAMP NOT NULL ,
expireref VARCHAR( 250 ) DEFAULT '',
created TIMESTAMP NOT NULL ,
modified TIMESTAMP NOT NULL ,
sessdata TEXT DEFAULT '',
PRIMARY KEY ( sesskey )
);
</pre>
<pre>create INDEX sess2_expiry on sessions2( expiry );
create INDEX sess2_expireref on sessions2 ( expireref );</pre>
<p>Here is the Oracle definition, which uses a CLOB for the SESSDATA field:
<pre>
<font
color="#004040">CREATE TABLE SESSIONS2<br>(<br> SESSKEY VARCHAR2(48 BYTE) NOT NULL,<br> EXPIRY DATE NOT NULL,<br> EXPIREREF VARCHAR2(200 BYTE),<br> CREATED DATE NOT NULL,<br> MODIFIED DATE NOT NULL,<br> SESSDATA CLOB,<br> PRIMARY KEY(SESSKEY)<br>);
<br>CREATE INDEX SESS2_EXPIRY ON SESSIONS2(EXPIRY);
CREATE INDEX SESS2_EXPIREREF ON SESSIONS2(EXPIREREF);</font></pre>
<p> We need to use a CLOB here because for text greater than 4000 bytes long,
Oracle requires you to use the CLOB data type. If you are using the oci8 driver,
ADOdb will automatically enable CLOB handling. So you can use either adodb-session2.php
or adodb-session-clob2.php - in this case it doesn't matter. <br>
<h2>Notifications</h2>
<p>You can receive notification when your session is cleaned up by the session garbage collector or
when you call session_destroy().
<p>PHP's session extension will automatically run a special garbage collection function based on
your php.ini session.cookie_lifetime and session.gc_probability settings. This will in turn call
adodb's garbage collection function, which can be setup to do notification.
<p>
<pre>
PHP Session --> ADOdb Session --> Find all recs --> Send --> Delete queued
GC Function GC Function to be deleted notification records
executed at called by for all recs
random time Session Extension queued for deletion
</pre>
<p>When a session is created, we need to store a value in the session record (in the EXPIREREF field), typically
the userid of the session. Later when the session has expired, just before the record is deleted,
we reload the EXPIREREF field and call the notification function with the value of EXPIREREF, which
is the userid of the person being logged off.
<p>ADOdb uses a global variable $ADODB_SESSION_EXPIRE_NOTIFY that you must predefine before session
start to store the notification configuration.
$ADODB_SESSION_EXPIRE_NOTIFY 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>
<p>For example, suppose we want to be notified when a user's session has expired,
based on the userid. When the user logs in, we store the id in the global session variable
$USERID. The function name is 'NotifyFn'.
<p>
So we define (before session_start() is called): </p>
<pre> <font color="#004040">
$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
</font></pre>
And when the NotifyFn is called (when the session expires), the
$EXPIREREF holding the user id is passed in 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: </p>
<pre><font color="#004040">
function NotifyFn($expireref, $sesskey)
{
global $ADODB_SESS_CONN; # the session connection object
$user = $ADODB_SESS_CONN-&gt;qstr($expireref);
$ADODB_SESS_CONN-&gt;Execute("delete from shopping_cart where user=$user");
system("rm /work/tmpfiles/$expireref/*");
}</font>
</pre>
<p> NOTE 1: If you have register_globals disabled in php.ini, then you
will have to manually set the EXPIREREF. E.g. </p>
<pre> <font color="#004040">
$GLOBALS['USERID'] = GetUserID();
$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');</font>
</pre>
<p> NOTE 2: 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.
</p>
<h3>Neat Notification Tricks</h3>
<p><i>ExpireRef</i> normally holds the user id of the current session.
</p>
<p>1. You can then write a session monitor, scanning expireref to see
who is currently logged on.
</p>
<p>2. If you delete the sessions record for a specific user, eg.
</p>
<pre>delete from sessions where expireref = '$USER'<br></pre>
then the user is logged out. Useful for ejecting someone from a
site.
<p>3. You can scan the sessions table to ensure no user
can be logged in twice. Useful for security reasons.
</p>
<h2>Compression/Encryption Schemes</h2>
Since ADOdb 4.05, thanks to Ross Smith, multiple encryption and
compression schemes are supported. Currently, supported are:
<p>
<pre> MD5Crypt (crypt.inc.php)<br> MCrypt<br> Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)<br> GZip<br> BZip2<br></pre>
<p>These are stackable. E.g.
<pre>ADODB_Session::filter(new ADODB_Compress_Bzip2());<br>ADODB_Session::filter(new ADODB_Encrypt_MD5());<br></pre>
will compress and then encrypt the record in the database.
<h2>Session Cookie Regeneration: adodb_session_regenerate_id()</h2>
<p>Dynamically change the current session id with a newly generated one and update
database. Currently only works with cookies. Useful to improve security by
reducing the risk of session-hijacking. See this article on <a href=http://shiflett.org/articles/security-corner-feb2004>Session
Fixation</a> for more info
on the theory behind this feature. Usage:<pre>
include('path/to/adodb/session/adodb-session2.php');
session_start();
# Approximately every 10 page loads, reset cookie for safety.
# This is extremely simplistic example, better
# to regenerate only when the user logs in or changes
# user privilege levels.
if ((rand()%10) == 0) adodb_session_regenerate_id();
</pre>
<p>This function calls session_regenerate_id() internally or simulates it if the function does not exist.
<h2>Vacuum/Optimize Database</h2>
<p>During session garbage collection, if postgresql is detected,
ADOdb can be set to run VACUUM. If mysql is detected, then optimize database
could be called.You can turn this on or off using:</p>
<pre>$turnOn = true; # or false
ADODB_Session::optimize($turnOn);
</pre>
<p>The default is optimization is disabled.</p>
<h2><a name=compat></a>Backwards Compatability </h2>
<p>The older method of connecting to ADOdb using global variables is still supported:</p>
<pre> $ADODB_SESSION_DRIVER='mysql';
$ADODB_SESSION_CONNECT='localhost';
$ADODB_SESSION_USER ='root';
$ADODB_SESSION_PWD ='abc';
$ADODB_SESSION_DB ='phplens';
include('path/to/adodb/session/adodb-<strong>session2</strong>.php'); </pre>
<p>In the above example, the only things you need to change in your code to upgrade
is </p>
<ul>
<li>your session table format to the new one.</li>
<li>the include file from adodb-session.php to adodb-session2.php. </li>
</ul>
<h2>More Info</h2>
<p>Also see the <a href="docs-adodb.htm">core ADOdb documentation</a>. And if
you are interested in the obsolete adodb-session.php, see <a href="docs-session.old.htm">old
session documentation</a>. </p>
</body>
</html>
-313
View File
@@ -1,313 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ADODB Old Session Management 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;
background-color: #EEEEEE; padding: .5em; margin: 0px;
}
.toplink {
font-size: 8pt;
}
</style>
</head>
<body style="background-color: rgb(255, 255, 255);">
<h3>ADODB Session Management Manual</h3>
<p>
V5.06 16 Oct 2008 (c) 2000-2009 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>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a>
&nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
</p>
<h3>Introduction</h3>
<p>This documentation discusses the old adodb-session.php.
Here is the <a href=docs-session.htm>new documentation</a> on the newer adodb-session2.php.
<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>
<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>
<p>The default method of storing sessions is to store it in a file.
However if you have special needs such as you:
</p>
<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>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>
<p>These records will be garbage collected based on the php.ini [session] timeout settings.
You can register a notification function to notify you when the record has expired and
is about to be freed by the garbage collector.</p>
<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. </p>
<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>
<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>
<li>Support for large amounts of session data with CLOBs (see
adodb-session-clob.php). Useful
for Oracle. </li>
<li>Support for encrypted session data, see
adodb-cryptsession.php. Enabling encryption is simply a matter of
including adodb-cryptsession.php instead of adodb-session.php. </li>
</ul>
<h3>Setup</h3>
<p>There are 3 session management files that you can use:
</p>
<pre>adodb-session.php : The default<br>adodb-session-clob.php : Use this if you are storing DATA in clobs<br>adodb-cryptsession.php : Use this if you want to store encrypted session data in the database<br><br>
</pre>
<p><strong>Examples</strong>
<p><pre>
<font
color="#004040"> include('adodb/adodb.inc.php');<br> <br><b> $ADODB_SESSION_DRIVER='mysql';<br> $ADODB_SESSION_CONNECT='localhost';<br> $ADODB_SESSION_USER ='scott';<br> $ADODB_SESSION_PWD ='tiger';<br> $ADODB_SESSION_DB ='sessiondb';</b><br> <br> <b>include('adodb/session/adodb-session.php');</b><br> session_start();<br> <br> #<br> # Test session vars, the following should increment on refresh<br> #<br> $_SESSION['AVAR'] += 1;<br> print "&lt;p&gt;\$_SESSION['AVAR']={$_SESSION['AVAR']}&lt;/p&gt;";<br></font></pre>
<p>To force non-persistent connections, call adodb_session_open() first before session_start():
<p>
<pre>
<font color="#004040"><br> include('adodb/adodb.inc.php');<br> <br><b> $ADODB_SESSION_DRIVER='mysql';<br> $ADODB_SESSION_CONNECT='localhost';<br> $ADODB_SESSION_USER ='scott';<br> $ADODB_SESSION_PWD ='tiger';<br> $ADODB_SESSION_DB ='sessiondb';</b><br> <br> <b>include('adodb/session/adodb-session.php');<br> adodb_sess_open(false,false,false);</b><br> session_start();<br> </font>
</pre>
<p> The 3rd parameter to adodb_sess_open($path, $sessname, $connectMode) sets the connection method. You can pass in the following:</p>
<table width="50%" border="1">
<tr>
<td><b>$connectMode</b></td>
<td><b>Connection Method</b></td>
</tr>
<tr>
<td>true</td>
<td><p>PConnect( )</p></td>
</tr>
<tr>
<td>false</td>
<td>Connect( )</td>
</tr>
<tr>
<td>'N'</td>
<td>NConnect( )</td>
</tr>
<tr>
<td>'P'</td>
<td>PConnect( )</td>
</tr>
<tr>
<td>'C'</td>
<td>Connect( )</td>
</tr>
</table>
<p>To use a encrypted sessions, simply replace the file adodb-session.php:</p>
<pre> <font
color="#004040"><br> include('adodb/adodb.inc.php');<br> <br><b> $ADODB_SESSION_DRIVER='mysql';<br> $ADODB_SESSION_CONNECT='localhost';<br> $ADODB_SESSION_USER ='scott';<br> $ADODB_SESSION_PWD ='tiger';<br> $ADODB_SESSION_DB ='sessiondb';<br> <br> include('adodb/session/adodb-cryptsession.php');</b><br> session_start();</font><br>
</pre>
<p>And the same technique for adodb-session-clob.php:</p>
<pre> <font
color="#004040"><br> include('adodb/adodb.inc.php');<br> <br><b> $ADODB_SESSION_DRIVER='mysql';<br> $ADODB_SESSION_CONNECT='localhost';<br> $ADODB_SESSION_USER ='scott';<br> $ADODB_SESSION_PWD ='tiger';<br> $ADODB_SESSION_DB ='sessiondb';<br> <br> include('adodb/session/adodb-session-clob.php');</b><br> session_start();</font>
</pre>
<p>An alternative way to set persistant or non-persistent connections is to call the following function before session_start() is called.
<pre>
ADODB_Session::persist('P'); # 'C' for non-persistent connections
</pre>
<h4>Installation</h4>
<p>1. Create this table in your database (MySQL syntax):
<p><pre> <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>
</pre>
<p>You may want to rename the 'data' field to 'session_data' as
'data' appears to be a reserved word for one or more of the following:
<ul>
<li> ANSI SQL
<li> IBM DB2
<li> MS SQL Server
<li> Postgres
<li> SAP
</ul>
<p>
If you do, then execute:
<pre>
ADODB_Session::dataFieldName('session_data');
</pre>
<p> For the adodb-session-clob.php version, create this:
<p> <pre>
<font
color="#004040"><br> create table sessions (<br> SESSKEY char(32) not null,<br> EXPIRY int(11) unsigned not null,<br> EXPIREREF varchar(64),<br> DATA CLOB,<br> primary key (sesskey)<br> );</font>
</pre>
<p>2. Then define the following parameters. You can either modify this file, or define them before this file is included:
<pre> <font
color="#004040"><br> $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';<br> $ADODB_SESSION_CONNECT='server to connect to';<br> $ADODB_SESSION_USER ='user';<br> $ADODB_SESSION_PWD ='password';<br> $ADODB_SESSION_DB ='database';<br> $ADODB_SESSION_TBL = 'sessions'; # setting this is optional<br> </font>
</pre><p>
When the session is created, $<b>ADODB_SESS_CONN</b> holds the connection object.<br> <br> 3. Recommended is PHP 4.0.6 or later. There are documented session bugs in earlier versions of PHP.
<h3>Notifications</h3>
<p>You can receive notification when your session is cleaned up by the session garbage collector or
when you call session_destroy().
<p>PHP's session extension will automatically run a special garbage collection function based on
your php.ini session.cookie_lifetime and session.gc_probability settings. This will in turn call
adodb's garbage collection function, which can be setup to do notification.
<p>
<pre>
PHP Session --> ADOdb Session --> Find all recs --> Send --> Delete queued
GC Function GC Function to be deleted notification records
executed at called by for all recs
random time Session Extension queued for deletion
</pre>
<p>When a session is created, we need to store a value in the session record (in the EXPIREREF field), typically
the userid of the session. Later when the session has expired, just before the record is deleted,
we reload the EXPIREREF field and call the notification function with the value of EXPIREREF, which
is the userid of the person being logged off.
<p>ADOdb uses a global variable $ADODB_SESSION_EXPIRE_NOTIFY that you must predefine before session
start to store the notification configuration.
$ADODB_SESSION_EXPIRE_NOTIFY 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>
<p>For example, suppose we want to be notified when a user's session has expired,
based on the userid. When the user logs in, we store the id in the global session variable
$USERID. The function name is 'NotifyFn'.
<p>
So we define (before session_start() is called): </p>
<pre> <font color="#004040">
$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
</font></pre>
And when the NotifyFn is called (when the session expires), the
$USERID is passed in 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: </p>
<pre><font color="#004040">
function NotifyFn($expireref, $sesskey)
{
global $ADODB_SESS_CONN; # the session connection object
$user = $ADODB_SESS_CONN-&gt;qstr($expireref);
$ADODB_SESS_CONN-&gt;Execute("delete from shopping_cart where user=$user");
system("rm /work/tmpfiles/$expireref/*");
}</font>
</pre>
<p> NOTE 1: If you have register_globals disabled in php.ini, then you
will have to manually set the EXPIREREF. E.g. </p>
<pre> <font color="#004040">
$GLOBALS['USERID'] = GetUserID();
$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');</font>
</pre>
<p> NOTE 2: 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.
</p>
<h4>Neat Notification Tricks</h4>
<p><i>ExpireRef</i> normally holds the user id of the current session.
</p>
<p>1. You can then write a session monitor, scanning expireref to see
who is currently logged on.
</p>
<p>2. If you delete the sessions record for a specific user, eg.
</p>
<pre>delete from sessions where expireref = '$USER'<br></pre>
then the user is logged out. Useful for ejecting someone from a
site.
<p>3. You can scan the sessions table to ensure no user
can be logged in twice. Useful for security reasons.
</p>
<h3>Using Oracle CLOBs</h3>
<p>Suppose you are storing the DATA field in a CLOB:
<pre><font color="#004040">
CREATE TABLE sessions (
SESSKEY VARCHAR(32) NOT NULL,
EXPIRY NUMBER(16) NOT NULL,
EXPIREREF VARCHAR(64),
DATA CLOB,
PRIMARY KEY (sesskey)
);</font>
</pre>
<p>Then your PHP code could look like this:
<pre>
ADODB_SESSION_DRIVER='oci8';
$ADODB_SESSION_CONNECT=$tnsname;
$ADODB_SESSION_USER ='scott';
$ADODB_SESSION_PWD = 'tiger';
$ADODB_SESSION_DB ='';
$ADODB_SESSION_USE_LOBS = 'clob';
$ADODB_SESSION_TBL = 'sessions';
$ADODB_SESS_DEBUG=0;
include(ADODB_DIR.'/session/adodb-session.php');
ADODB_Session::persist('P'); # use 'C' for non-persistent connects
session_start();
</pre>
<p>Note that you can set persistance using ADODB_Session::persist('P').
<h3>Compression/Encryption Schemes</h3>
Since ADOdb 4.05, thanks to Ross Smith, multiple encryption and
compression schemes are supported. Currently, supported are:
<p>
<pre> MD5Crypt (crypt.inc.php)<br> MCrypt<br> Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)<br> GZip<br> BZip2<br></pre>
<p>These are stackable. E.g.
<p><pre>ADODB_Session::filter(new ADODB_Compress_Bzip2());<br>ADODB_Session::filter(new ADODB_Encrypt_MD5());<br></pre>
will compress and then encrypt the record in the database.
<h3>adodb_session_regenerate_id()</h3>
<p>Dynamically change the current session id with a newly generated one and update database. Currently only
works with cookies. Useful to improve security by reducing the risk of session-hijacking.
See this article on <a href=http://shiflett.org/articles/security-corner-feb2004>Session Fixation</a> for more info
on the theory behind this feature. Usage:
<pre>
$ADODB_SESSION_DRIVER='mysql';
$ADODB_SESSION_CONNECT='localhost';
$ADODB_SESSION_USER ='root';
$ADODB_SESSION_PWD ='abc';
$ADODB_SESSION_DB ='phplens';
include('path/to/adodb/session/adodb-session.php');
session_start();
# Every 10 page loads, reset cookie for safety.
# This is extremely simplistic example, better
# to regenerate only when the user logs in or changes
# user privilege levels.
if ((rand()%10) == 0) adodb_session_regenerate_id();
</pre>
<p>This function calls session_regenerate_id() internally or simulates it if the function does not exist.
<h3>Vacuum/Optimize Database</h3>
<p>During session garbage collection, if postgresql is detected,
ADOdb can be set to run VACUUM. If mysql is detected, then optimize database
could be called.You can turn this on or off using:</p>
<pre>$turnOn = true; # or false
ADODB_Session::optimize($turnOn);
</pre>
<p>The default for optimization is it is disabled.</p>
<h2>More Info</h2>
<p>Also see the <a href="docs-adodb.htm">core ADOdb documentation</a>.
</p>
</body>
</html>
-822
View File
@@ -1,822 +0,0 @@
<html><title>Old Changelog: ADOdb</title><body>
<h3>Old Changelog</h3>
</p><p><b>3.92 22 Sept 2003</b>
</p><p>Added GetAssoc and CacheGetAssoc to connection object.
</p><p>Removed TextMax and CharMax functions from adodb.inc.php.
</p><p>HasFailedTrans() returned false when trans failed. Fixed.
</p><p>Moved perf driver classes into adodb/perf/*.php.
</p><p>Misc improvements to performance monitoring, including UI().
</p><p>RETVAL in mssql Parameter(), we do not append @ now.
</p><p>Added Param($name) to connection class, returns '?' or ":$name", for defining
bind parameters portably.
</p><p>LogSQL traps affected_rows() and saves its value properly now. Also fixed oci8
_stmt and _affectedrows() bugs.
</p><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-&gt;datetime field to oci8, controls whether MetaType() returns
'D' ($this-&gt;datetime==false) or 'T' ($this-&gt;datetime == true) for DATE type.
</p><p>Fixed bugs in adodb-cryptsession.inc.php and adodb-session-clob.inc.php.
</p><p>Fixed misc bugs in adodb_key_exists, GetInsertSQL() and GetUpdateSQL().
</p><p>Tuned include_once handling to reduce file-system checking overhead.
</p><p><b>3.91 9 Sept 2003</b>
</p><p>Only released to InterAkt
</p><p>Added LogSQL() for sql logging and $ADODB_NEWCONNECTION to override factory
for driver instantiation.
</p><p>Added IfNull($field,$ifNull) function, thx to johnwilk#juno.com
</p><p>Added portable substr support.
</p><p>Now rs2html() has new parameter, $echo. Set to false to return $html instead
of echoing it.
</p><p><b>3.90 5 Sept 2003</b>
</p><p>First beta of performance monitoring released.
</p><p>MySQL supports MetaTable() masking.
</p><p>Fixed key_exists() bug in adodb-lib.inc.php
</p><p>Added sp_executesql Prepare() support to mssql.
</p><p>Added bind support to db2.
</p><p>Added swedish language file - Christian Tiberg" christian#commsoft.nu
</p><p>Bug in drop index for mssql data dict fixed. Thx to Gert-Rainer Bitterlich.
</p><p>Left join setting for oci8 was wrong. Thx to johnwilk#juno.com
</p><p><b>3.80 27 Aug 2003</b>
</p><p>Patch for PHP 4.3.3 cached recordset csv2rs() fread loop incompatibility.
</p><p>Added matching mask for MetaTables. Only for oci8, mssql and postgres currently.
</p><p>Rewrite of "oracle" driver connection code, merging with "oci8", by Gaetano.
</p><p>Added better debugging for Smart Transactions.
</p><p>Postgres DBTimeStamp() was wrongly using TO_DATE. Changed to TO_TIMESTAMP.
</p><p>ADODB_FETCH_CASE check pushed to ADONewConnection to allow people to define
it after including adodb.inc.php.
</p><p>Added portugese (brazilian) to languages. Thx to "Levi Fukumori".
</p><p>Removed arg3 parameter from Execute/SelectLimit/Cache* functions.
</p><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><p>Added MONEY to MetaType in PostgreSQL.
</p><p>Added more debugging output to CacheFlush().
</p><p><b>3.72 9 Aug 2003</b>
</p><p>Added qmagic($str), which is a qstr($str) that auto-checks for magic quotes
and does the right thing...
</p><p>Fixed CacheFlush() bug - Thx to martin#gmx.de
</p><p>Walt Boring contributed MetaForeignKeys for postgres7.
</p><p>_fetch() called _BlobDecode() wrongly in interbase. Fixed.
</p><p>adodb_time bug fixed with dates after 2038 fixed by Jason Pell. http://phplens.com/lens/lensforum/msgs.php?id=6980
</p><p><b>3.71 4 Aug 2003</b>
</p><p>The oci8 driver, MetaPrimaryKeys() did not check the owner correctly when $owner
== false.
</p><p>Russian language file contributed by "Cyrill Malevanov" cyrill#malevanov.spb.ru.
</p><p>Spanish language file contributed by "Horacio Degiorgi" horaciod#codigophp.com.
</p><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><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><p><b>3.70 29 July 2003</b>
</p><p>Added new SQLite driver. Tested on PHP 4.3 and PHP 5.
</p><p>Added limited "sapdb" driver support - mainly date support.
</p><p>The oci8 driver did not identify NUMBER with no defined precision correctly.
</p><p>Added ADODB_FORCE_NULLS, if set, then PHP nulls are converted to SQL nulls
in GetInsertSQL/GetUpdateSQL.
</p><p>DBDate() and DBTimeStamp() format for postgresql had problems. Fixed.
</p><p>Added tableoptions to ChangeTableSQL(). Thx to Mike Benoit.
</p><p>Added charset support to postgresql. Thx to Julian Tarkhanov.
</p><p>Changed OS check for MS-Windows to prevent confusion with darWIN (MacOS)
</p><p>Timestamp format for db2 was wrong. Changed to yyyy-mm-dd-hh.mm.ss.nnnnnn.
</p><p>adodb-cryptsession.php includes wrong. Fixed.
</p><p>Added MetaForeignKeys(). Supported by mssql, odbc_mssql and oci8.
</p><p>Fixed some oci8 MetaColumns/MetaPrimaryKeys bugs. Thx to Walt Boring.
</p><p>adodb_getcount() did not init qryRecs to 0. Missing "WHERE" clause checking
in GetUpdateSQL fixed. Thx to Sebastiaan van Stijn.
</p><p>Added support for only 'VIEWS' and "TABLES" in MetaTables. From Walt Boring.
</p><p>Upgraded to adodb-xmlschema.inc.php 0.0.2.
</p><p>NConnect for mysql now returns value. Thx to Dennis Verspuij.
</p><p>ADODB_FETCH_BOTH support added to interbase/firebird.
</p><p>Czech language file contributed by Kamil Jakubovic jake#host.sk.
</p><p>PostgreSQL BlobDecode did not use _connectionID properly. Thx to Juraj Chlebec.
</p><p>Added some new initialization stuff for Informix. Thx to "Andrea Pinnisi" pinnisi#sysnet.it
</p><p>ADODB_ASSOC_CASE constant wrong in sybase _fetch(). Fixed.
</p><p><b>3.60 16 June 2003</b>
</p><p>We now SET CONCAT_NULL_YIELDS_NULL OFF for odbc_mssql driver to be compat with
mssql driver.
</p><p>The property $emptyDate missing from connection class. Also changed 1903 to
constant (TIMESTAMP_FIRST_YEAR=100). Thx to Sebastiaan van Stijn.
</p><p>ADOdb speedup optimization - we now return all arrays by reference.
</p><p>Now DBDate() and DBTimeStamp() now accepts the string 'null' as a parameter.
Suggested by vincent.
</p><p>Added GetArray() to connection class.
</p><p>Added not_null check in informix metacolumns().
</p><p>Connection parameters for postgresql did not work correctly when port was defined.
</p><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><p>The odbc driver's FetchField() field names did not obey ADODB_ASSOC_CASE. Fixed.
</p><p>Some bugs in adodb_backtrace() fixed.
</p><p>Added "INT IDENTITY" type to adorecordset::MetaType() to support odbc_mssql
properly.
</p><p>MetaColumns() for oci8, mssql, odbc revised to support scale. Also minor revisions
to odbc MetaColumns() for vfp and db2 compat.
</p><p>Added unsigned support to mysql datadict class. Thx to iamsure.
</p><p>Infinite loop in mssql MoveNext() fixed when ADODB_FETCH_ASSOC used. Thx to
Josh R, Night_Wulfe#hotmail.com.
</p><p>ChangeTableSQL contributed by Florian Buzin.
</p><p>The odbc_mssql driver now sets CONCAT_NULL_YIELDS_NULL OFF for compat with
mssql driver.
</p>
<p><b>3.50 19 May 2003</b></p>
<p>Fixed mssql compat with FreeTDS. FreeTDS does not implement mssql_fetch_assoc().
<p>Merged back connection and recordset code into adodb.inc.php.
<p>ADOdb sessions using oracle clobs contributed by achim.gosse#ddd.de. See adodb-session-clob.php.
<p>Added /s modifier to preg_match everywhere, which ensures that regex does not
stop at /n. Thx Pao-Hsi Huang.
<p>Fixed error in metacolumns() for mssql.
<p>Added time format support for SQLDate.
<p>Image => B added to metatype.
<p>MetaType now checks empty($this->blobSize) instead of empty($this).
<p>Datadict has beta support for informix, sybase (mapped to mssql), db2 and generic
(which is a fudge).
<p>BlobEncode for postgresql uses pg_escape_bytea, if available. Needed for compat
with 7.3.
<p>Added $ADODB_LANG, to support multiple languages in MetaErrorMsg().
<p>Datadict can now parse table definition as declarative text.
<p>For DataDict, oci8 autoincrement trigger missing semi-colon. Fixed.
<p>For DataDict, when REPLACE flag enabled, drop sequence in datadict for autoincrement
field in postgres and oci8.s
<p>Postgresql defaults to template1 database if no database defined in connect/pconnect.
<p>We now clear _resultid in postgresql if query fails.
<p><b>3.40 19 May 2003</b></p>
<p>Added insert_id for odbc_mssql.
<p>Modified postgresql UpdateBlobFile() because it did not work in safe mode.
<p>Now connection object is passed to raiseErrorFn as last parameter. Needed by
StartTrans().
<p>Added StartTrans() and CompleteTrans(). It is recommended that you do not modify
transOff, but use the above functions.
<p>oci8po now obeys ADODB_ASSOC_CASE settings.
<p>Added virtualized error codes, using PEAR DB equivalents. Requires you to manually
include adodb-error.inc.php yourself, with MetaError() and MetaErrorMsg($errno).
<p>GetRowAssoc for mysql and pgsql were flawed. Fix by Ross Smith.
<p>Added to datadict types I1, I2, I4 and I8. Changed datadict type 'T' to map
to timestamp instead of datetime for postgresql.
<p>Error handling in ExecuteSQLArray(), adodb-datadict.inc.php did not work.
<p>We now auto-quote postgresql connection parameters when building connection
string.
<p>Added session expiry notification.
<p>We now test with odbc mysql - made some changes to odbc recordset constructor.
<p>MetaColumns now special cases access and other databases for odbc.
<p><b>3.31 17 March 2003</b></p>
<p>Added row checking for _fetch in postgres.
<p>Added Interval type to MetaType for postgres.
<p>Remapped postgres driver to call postgres7 driver internally.
<p>Adorecordset_array::getarray() did not return array when nRows >= 0.
<p>Postgresql: at times, no error message returned by pg_result_error() but error
message returned in pg_last_error(). Recoded again.
<p>Interbase blob's now use chunking for updateblob.
<p>Move() did not set EOF correctly. Reported by Jorma T.
<p>We properly support mysql timestamp fields when we are creating mysql tables
using the data-dict interface.
<p>Table regex includes backticks character now.
<p><b>3.30 3 March 2003</b></p>
<p>Added $ADODB_EXTENSION and $ADODB_COMPAT_FETCH constant.
<p>Made blank1stItem configurable using syntax "value:text" in GetMenu/GetMenu2.
Thx to Gabriel Birke.
<p>Previously ADOdb differed from the Microsoft standard because it did not define
what to set $this->fields when EOF was reached. Now at EOF, ADOdb sets $this->fields
to false for all databases, which is consist with Microsoft's implementation.
Postgresql and mysql have always worked this way (in 3.11 and earlier). If you
are experiencing compatibility problems (and you are not using postgresql nor
mysql) on upgrading to 3.30, try setting the global variables $ADODB_COUNTRECS
= true (which is the default) and $ADODB_FETCH_COMPAT = true (this is a new
global variable).
<p>We now check both pg_result_error and pg_last_error as sometimes pg_result_error
does not display anything. Iman Mayes
<p> We no longer check for magic quotes gpc in Quote().
<p> Misc fixes for table creation in adodb-datadict.inc.php. Thx to iamsure.
<p> Time calculations use adodb_time library for all negative timestamps due to
problems in Red Hat 7.3 or later. Formerly, only did this for Windows.
<p> In mssqlpo, we now check if $sql in _query is a string before we change ||
to +. This is to support prepared stmts.
<p> Move() and MoveLast() internals changed to support to support EOF and $this->fields
change.
<p> Added ADODB_FETCH_BOTH support to mssql. Thx to Angel Fradejas afradejas#mediafusion.es
<p> We now check if link resource exists before we run mysql_escape_string in
qstr().
<p> Before we flock in csv code, we check that it is not a http url.
<p><b>3.20 17 Feb 2003</b></p>
<p>Added new Data Dictionary classes for creating tables and indexes. Warning
- this is very much alpha quality code. The API can still change. See adodb/tests/test-datadict.php
for more info.
<p>We now ignore $ADODB_COUNTRECS for mysql, because PHP truncates incomplete
recordsets when mysql_unbuffered_query() is called a second time.
<p>Now postgresql works correctly when $ADODB_COUNTRECS = false.
<p>Changed _adodb_getcount to properly support SELECT DISTINCT.
<p>Discovered that $ADODB_COUNTRECS=true has some problems with prepared queries
- suspect PHP bug.
<p>Now GetOne and GetRow run in $ADODB_COUNTRECS=false mode for better performance.
<p>Added support for mysql_real_escape_string() and pg_escape_string() in qstr().
<p>Added an intermediate variable for mysql _fetch() and MoveNext() to store fields,
to prevent overwriting field array with boolean when mysql_fetch_array() returns
false.
<p>Made arrays for getinsertsql and getupdatesql case-insensitive. Suggested by
Tim Uckun" tim#diligence.com
<p><b>3.11 11 Feb 2003</b></p>
<p>Added check for ADODB_NEVER_PERSIST constant in PConnect(). If defined, then
PConnect() will actually call non-persistent Connect().
<p>Modified interbase to properly work with Prepare().
<p>Added $this->ibase_timefmt to allow you to change the date and time format.
<p>Added support for $input_array parameter in CacheFlush().
<p>Added experimental support for dbx, which was then removed when i found that
it was slower than using native calls.
<p>Added MetaPrimaryKeys for mssql and ibase/firebird.
<p>Added new $trim parameter to GetCol and CacheGetCol
<p>Uses updated adodb-time.inc.php 0.06.
<p><b>3.10 27 Jan 2003</b>
<p>Added adodb_date(), adodb_getdate(), adodb_mktime() and adodb-time.inc.php.
<p>For interbase, added code to handle unlimited number of bind parameters. From
Daniel Hasan daniel#hasan.cl.
<p>Added BlobDecode and UpdateBlob for informix. Thx to Fernando Ortiz.
<p>Added constant ADODB_WINDOWS. If defined, means that running on Windows.
<p>Added constant ADODB_PHPVER which stores php version as a hex num. Removed
$ADODB_PHPVER variable.
<p>Felho Bacsi reported a minor white-space regular expression problem in GetInsertSQL.
<p>Modified ADO to use variant to store _affectedRows
<p>Changed ibase to use base class Replace(). Modified base class Replace() to
support ibase.
<p>Changed odbc to auto-detect when 0 records returned is wrong due to bad odbc
drivers.
<p>Changed mssql to use datetimeconvert ini setting only when 4.30 or later (does
not work in 4.23).
<p>ExecuteCursor($stmt, $cursorname, $params) now accepts a new $params array
of additional bind parameters -- William Lovaton walovaton#yahoo.com.mx.
<p>Added support for sybase_unbuffered_query if ADODB_COUNTRECS == false. Thx
to chuck may.
<p>Fixed FetchNextObj() bug. Thx to Jorma Tuomainen.
<p>We now use SCOPE_IDENTITY() instead of @@IDENTITY for mssql - thx to marchesini#eside.it
<p>Changed postgresql movenext logic to prevent illegal row number from being
passed to pg_fetch_array().
<p>Postgresql initrs bug found by "Bogdan RIPA" bripa#interakt.ro $f1 accidentally
named $f
<p><b>3.00 6 Jan 2003</b>
<p>Fixed adodb-pear.inc.php syntax error.
<p>Improved _adodb_getcount() to use SELECT COUNT(*) FROM ($sql) for languages
that accept it.
<p>Fixed _adodb_getcount() caching error.
<p>Added sql to retrive table and column info for odbc_mssql.
<p><strong>2.91 3 Jan 2003</strong>
<p>Revised PHP version checking to use $ADODB_PHPVER with legal values 0x4000,
0x4050, 0x4200, 0x4300.
<p>Added support for bytea fields and oid blobs in postgres by allowing BlobDecode()
to detect and convert non-oid fields. Also added BlobEncode to postgres when
you want to encode oid blobs.
<p>Added blobEncodeType property for connections to inform phpLens what encoding
method to use for blobs.
<p>Added BlobDecode() and BlobEncode() to base ADOConnection class.
<p>Added umask() to _gencachename() when creating directories.
<p>Added charPage for ado drivers, so you can set the code page.
<pre>
$conn->charPage = CP_UTF8;
$conn->Connect($dsn);
</pre>
<p>Modified _seek in mysql to check for num rows=0.
<p>Added to metatypes new informix types for IDS 9.30. Thx Fernando Ortiz.
<p>_maxrecordcount returned in CachePageExecute $rsreturn
<p>Fixed sybase cacheselectlimit( ) problems
<p>MetaColumns() max_length should use precision for types X and C for ms access.
Fixed.
<p>Speedup of odbc non-SELECT sql statements.
<p>Added support in MetaColumns for Wide Char types for ODBC. We halve max_length
if unicode/wide char.
<p>Added 'B' to types handled by GetUpdateSQL/GetInsertSQL.
<p>Fixed warning message in oci8 driver with $persist variable when using PConnect.
<p><b>2.90 11 Dec 2002</b>
<p>Mssql and mssqlpo and oci8po now support ADODB_ASSOC_CASE.
<p>Now MetaType() can accept a field object as the first parameter.
<p>New $arr = $db-&gt;ServerInfo( ) function. Returns $arr['description'] which
is the string description, and $arr['version'].
<p>PostgreSQL and MSSQL speedups for insert/updates.
<p> Implemented new SetFetchMode() that removes the need to use $ADODB_FETCH_MODE.
Each connection has independant fetchMode.
<p>ADODB_ASSOC_CASE now defaults to 2, use native defaults. This is because we
would break backward compat for too many applications otherwise.
<p>Patched encrypted sessions to use replace()
<p>The qstr function supports quoting of nulls when escape character is \
<p>Rewrote bits and pieces of session code to check for time synch and improve
reliability.
<p>Added property ADOConnection::hasTransactions = true/false;
<p>Added CreateSequence and DropSequence functions
<p>Found misplaced MoveNext() in adodb-postgres.inc.php. Fixed.
<p>Sybase SelectLimit not reliable because 'set rowcount' not cached - fixed.
<p>Moved ADOConnection to adodb-connection.inc.php and ADORecordSet to adodb-recordset.inc.php.
This allows us to use doxygen to generate documentation. Doxygen doesn't like
the classes in the main adodb.inc.php file for some mysterious reason.
<p><b>2.50, 14 Nov 2002</b>
<p>Added transOff and transCnt properties for disabling (transOff = true) and
tracking transaction status (transCnt>0).
<p>Added inputarray handling into _adodb_pageexecute_all_rows - "Ross Smith" RossSmith#bnw.com.
<p>Fixed postgresql inconsistencies in date handling.
<p>Added support for mssql_fetch_assoc.
<p>Fixed $ADODB_FETCH_MODE bug in odbc MetaTables() and MetaPrimaryKeys().
<p>Accidentally declared UnixDate() twice, making adodb incompatible with php
4.3.0. Fixed.
<p>Fixed pager problems with some databases that returned -1 for _currentRow on
MoveLast() by switching to MoveNext() in adodb-lib.inc.php.
<p>Also fixed uninited $discard in adodb-lib.inc.php.
<p><b>2.43, 25 Oct 2002</b></p>
Added ADODB_ASSOC_CASE constant to better support ibase and odbc field names.
<p>Added support for NConnect() for oracle OCINLogin.
<p>Fixed NumCols() bug.
<p>Changed session handler to use Replace() on write.
<p>Fixed oci8 SelectLimit aggregate function bug again.
<p>Rewrote pivoting code.
<p><b>2.42, 4 Oct 2002</b></p>
<p>Fixed ibase_fetch() problem with nulls. Also interbase now does automatic blob
decoding, and is backward compatible. Suggested by Heinz Hombergs heinz#hhombergs.de.
<p>Fixed postgresql MoveNext() problems when called repeatedly after EOF. Also
suggested by Heinz Hombergs.
<p>PageExecute() does not rewrite queries if SELECT DISTINCT is used. Requested
by hans#velum.net
<p>Added additional fixes to oci8 SelectLimit handling with aggregate functions
- thx to Christian Bugge for reporting the problem.
<p><b>2.41, 2 Oct 2002</b></p>
<p>Fixed ADODB_COUNTRECS bug in odbc. Thx to Joshua Zoshi jzoshi#hotmail.com.
<p>Increased buffers for adodb-csvlib.inc.php for extremely long sql from 8192
to 32000.
<p>Revised pivottable.inc.php code. Added better support for aggregate fields.
<p>Fixed mysql text/blob types problem in MetaTypes base class - thx to horacio
degiorgi.
<p>Added SQLDate($fmt,$date) function, which allows an sql date format string
to be generated - useful for group by's.
<p>Fixed bug in oci8 SelectLimit when offset>100.
<p><b>2.40 4 Sept 2002</b></p>
<p>Added new NLS_DATE_FORMAT property to oci8. Suggested by Laurent NAVARRO ln#altidev.com
<p>Now use bind parameters in oci8 selectlimit for better performance.
<p>Fixed interbase replaceQuote for dialect != 1. Thx to "BEGUIN Pierre-Henri
- INFOCOB" phb#infocob.com.
<p>Added white-space check to QA.
<p>Changed unixtimestamp to support fractional seconds (we always round down/floor
the seconds). Thanks to beezly#beezly.org.uk.
<p>Now you can set the trigger_error type your own user-defined type in adodb-errorhandler.inc.php.
Suggested by Claudio Bustos clbustos#entelchile.net.
<p>Added recordset filters with rsfilter.inc.php.
<p>$conn->_rs2rs does not create a new recordset when it detects it is of type
array. Some trickery there as there seems to be a bug in Zend Engine
<p>Added render_pagelinks to adodb-pager.inc.php. Code by "Pablo Costa" pablo#cbsp.com.br.
<p>MetaType() speedup in adodb.inc.php by using hashing instead of switch. Best
performance if constant arrays are supported, as they are in PHP5.
<p>adodb-session.php now updates only the expiry date if the crc32 check indicates
that the data has not been modified.
<p><b>2.31 20 Aug 2002</b></p>
<p>Made changes to pivottable.inc.php due to daniel lucuzaeu's suggestions (we sum the pivottable column if desired).
<p>Fixed ErrorNo() in postgres so it does not depend on _errorMsg property.
<p>Robert Tuttle added support for oracle cursors. See ExecuteCursor().
<p>Fixed Replace() so it works with mysql when updating record where data has not changed. Reported by
Cal Evans (cal#calevans.com).
<p><b>2.30 1 Aug 2002</b></p>
<p>Added pivottable.inc.php. Thanks to daniel.lucazeau#ajornet.com for the original
concept.
<p>Added ADOConnection::outp($msg,$newline) to output error and debugging messages. Now
you can override this using the ADODB_OUTP constant and use your own output handler.
<p>Changed == to === for 'null' comparison. Reported by ericquil#yahoo.com
<p>Fixed mssql SelectLimit( ) bug when distinct used.
<p><b>2.30 1 Aug 2002</b></p>
<p>New GetCol() and CacheGetCol() from ross#bnw.com that returns the first field as a 1 dim array.
<p>We have an empty recordset, but RecordCount() could return -1. Fixed. Reported by "Jonathan Polansky" jonathan#polansky.com.
<p>We now check for session variable changes using strlen($sessval).crc32($sessval).
Formerly we only used crc32().
<p>Informix SelectLimit() problem with $ADODB_COUNTRECS fixed.
<p>Fixed informix SELECT FIRST x DISTINCT, and not SELECT DISTINCT FIRST x - reported by F Riosa
<p>Now default adodb error handlers ignores error if @ used.
<p>If you set $conn->autoRollback=true, we auto-rollback persistent connections for odbc, mysql, oci8, mssql.
Default for autoRollback is false. No need to do so for postgres.
As interbase requires a transaction id (what a flawed api), we don't do it for interbase.
<p>Changed PageExecute() to use non-greedy preg_match when searching for "FROM" keyword.
<p><b>2.20 9 July 2002</b></p>
<p>Added CacheGetOne($secs2cache,$sql), CacheGetRow($secs2cache,$sql), CacheGetAll($secs2cache,$sql).
<p>Added $conn->OffsetDate($dayFraction,$date=false) to generate sql that calcs
date offsets. Useful for scheduling appointments.
<p>Added connection properties: leftOuter, rightOuter that hold left and right
outer join operators.
<p>Added connection property: ansiOuter to indicate whether ansi outer joins supported.
<p>New driver <i>mssqlpo</i>, the portable mssql driver, which converts string
concat operator from || to +.
<p>Fixed ms access bug - SelectLimit() did not support ties - fixed.
<p>Karsten Kraus (Karsten.Kraus#web.de), contributed error-handling code to ADONewConnection.
Unfortunately due to backward compat problems, had to rollback most of the changes.
<p>Added new parameter to GetAssoc() to allow returning an array of key-value pairs,
ignoring any additional columns in the recordset. Off by default.
<p>Corrected mssql $conn->sysDate to return only date using convert().
<p>CacheExecute() improved debugging output.
<p>Changed rs2html() so newlines are converted to BR tags. Also optimized rs2html() based
on feedback by "Jerry Workman" jerry#mtncad.com.
<p>Added support for Replace() with Interbase, using DELETE and INSERT.
<p>Some minor optimizations (mostly removing & references when passing arrays).
<p>Changed GenID() to allows id's larger than the size of an integer.
<p>Added force_session property to oci8 for better updateblob() support.
<p>Fixed PageExecute() which did not work properly with sql containing GROUP BY.
<p><b>2.12 12 June 2002</b></p>
<p>Added toexport.inc.php to export recordsets in CSV and tab-delimited format.
<p>CachePageExecute() does not work - fixed - thx John Huong.
<p>Interbase aliases not set properly in FetchField() - fixed. Thx Stefan Goethals.
<p>Added cache property to adodb pager class. The number of secs to cache recordsets.
<p>SQL rewriting bug in pageexecute() due to skipping of newlines due to missing /s modifier. Fixed.
<p>Max size of cached recordset due to a bug was 256000 bytes. Fixed.
<p>Speedup of 1st invocation of CacheExecute() by tuning code.
<p>We compare $rewritesql with $sql in pageexecute code in case of rewrite failure.
<p><b>2.11 7 June 2002</b></p>
<p>Fixed PageExecute() rewrite sql problem - COUNT(*) and ORDER BY don't go together with
mssql, access and postgres. Thx to Alexander Zhukov alex#unipack.ru
<p>DB2 support for CHARACTER type added - thx John Huong huongch#bigfoot.com
<p>For ado, $argProvider not properly checked. Fixed - kalimero#ngi.it
<p>Added $conn->Replace() function for update with automatic insert if the record does not exist.
Supported by all databases except interbase.
<p><b>2.10 4 June 2002</b></p>
<p>Added uniqueSort property to indicate mssql ORDER BY cols must be unique.
<p>Optimized session handler by crc32 the data. We only write if session data has changed.
<p>adodb_sess_read in adodb-session.php now returns ''correctly - thanks to Jorma Tuomainen, webmaster#wizactive.com
<p>Mssql driver did not throw EXECUTE errors correctly because ErrorMsg() and ErrorNo() called in wrong order.
Pointed out by Alexios Fakos. Fixed.
<p>Changed ado to use client cursors. This fixes BeginTran() problems with ado.
<p>Added handling of timestamp type in ado.
<p>Added to ado_mssql support for insert_id() and affected_rows().
<p>Added support for mssql.datetimeconvert=0, available since php 4.2.0.
<p>Made UnixDate() less strict, so that the time is ignored if present.
<p>Changed quote() so that it checks for magic_quotes_gpc.
<p>Changed maxblobsize for odbc to default to 64000.
<p><b>2.00 13 May 2002</b></p>
<p>Added drivers <i>informix72</i> for pre-7.3 versions, and <i>oci805</i> for
oracle 8.0.5, and postgres64 for postgresql 6.4 and earlier. The postgres and postgres7 drivers
are now identical.
<p>Interbase now partially supports ADODB_FETCH_BOTH, by defaulting to ASSOC mode.
<p>Proper support for blobs in mssql. Also revised blob support code
is base class. Now UpdateBlobFile() calls UpdateBlob() for consistency.
<p>Added support for changed odbc_fetch_into api in php 4.2.0
with $conn-&gt;_has_stupid_odbc_fetch_api_change.
<p>Fixed spelling of tablock locking hint in GenID( ) for mssql.
<p>Added RowLock( ) to several databases, including oci8, informix, sybase, etc.
Fixed where error in mssql RowLock().
<p>Added sysDate and sysTimeStamp properties to most database drivers. These are the sql
functions/constants for that database that return the current date and current timestamp, and
are useful for portable inserts and updates.
<p>Support for RecordCount() caused date handling in sybase and mssql to break.
Fixed, thanks to Toni Tunkkari, by creating derived classes for ADORecordSet_array for
both databases. Generalized using arrayClass property. Also to support RecordCount(),
changed metatype handling for ado drivers. Now the type returned in FetchField
is no longer a number, but the 1-char data type returned by MetaType.
At the same time, fixed a lot of date handling. Now mssql support dmy and mdy date formats.
Also speedups in sybase and mssql with preg_match and ^ in date/timestamp handling.
Added support in sybase and mssql for 24 hour clock in timestamps (no AM/PM).
<p>Extensive revisions to informix driver - thanks to Samuel CARRIERE samuel_carriere#hotmail.com
<p>Added $ok parameter to CommitTrans($ok) for easy rollbacks.
<p>Fixed odbc MetaColumns and MetaTables to save and restore $ADODB_FETCH_MODE.
<p>Some odbc drivers did not call the base connection class constructor. Fixed.
<p>Fixed regex for GetUpdateSQL() and GetInsertSQL() to support more legal character combinations.
<p><b>1.99 21 April 2002</b></p>
<p>Added emulated RecordCount() to all database drivers if $ADODB_COUNTRECS = true
(which it is by default). Inspired by Cristiano Duarte (cunha17#uol.com.br).
<p>Unified stored procedure support for mssql and oci8. Parameter() and PrepareSP()
functions implemented.
<p>Added support for SELECT FIRST in informix, modified hasTop property to support
this.
<p>Changed csv driver to handle updates/deletes/inserts properly (when Execute() returns true).
Bind params also work now, and raiseErrorFn with csv driver. Added csv driver to QA process.
<p>Better error checking in oci8 UpdateBlob() and UpdateBlobFile().
<p>Added TIME type to MySQL - patch by Manfred h9125297#zechine.wu-wien.ac.at
<p>Prepare/Execute implemented for Interbase/Firebird
<p>Changed some regular expressions to be anchored by /^ $/ for speed.
<p>Added UnixTimeStamp() and UnixDate() to ADOConnection(). Now these functions
are in both ADOConnection and ADORecordSet classes.
<p>Empty recordsets were not cached - fixed.
<p>Thanks to Gaetano Giunta (g.giunta#libero.it) for the oci8 code review. We
didn't agree on everything, but i hoped we agreed to disagree!
<p><b>1.90 6 April 2002</b></p>
<p>Now all database drivers support fetch modes ADODB_FETCH_NUM and ADODB_FETCH_ASSOC, though
still not fully tested. Eg. Frontbase, Sybase, Informix.
<p>NextRecordSet() support for mssql. Contributed by "Sven Axelsson" sven.axelsson#bokochwebb.se
<p>Added blob support for SQL Anywhere. Contributed by Wade Johnson wade#wadejohnson.de
<p>Fixed some security loopholes in server.php. Server.php also supports fetch mode.
<p>Generalized GenID() to support odbc and mssql drivers. Mssql no longer generates GUID's.
<p>Experimental RowLock($table,$where) for mssql.
<p>Properly implemented Prepare() in oci8 and ODBC.
<p>Added Bind() support to oci8 to support Prepare().
<p>Improved error handler. Catches CacheExecute() and GenID() errors now.
<p>Now if you are running php from the command line, debugging messages do not output html formating.
Not 100% complete, but getting there.
<p><b>1.81 22 March 2002</b></p>
<p>Restored default $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT for backward compatibility.
<p>SelectLimit for oci8 improved - Our FIRST_ROWS optimization now does not overwrite existing hint.
<p>New Sybase SQL Anywhere driver. Contributed by Wade Johnson wade#wadejohnson.de
<p><b>1.80 15 March 2002</b></p>
<p>Redesigned directory structure of ADOdb files. Added new driver directory where
all database drivers reside.
<p>Changed caching algorithm to create subdirectories. Now we scale better.
<p>Informix driver now supports insert_id(). Contribution by "Andrea Pinnisi" pinnisi#sysnet.it
<p>Added experimental ISO date and FetchField support for informix.
<p>Fixed a quoting bug in Execute() with bind parameters, causing problems with blobs.
<p>Mssql driver speedup by 10-15%.
<p>Now in CacheExecute($secs2cache,$sql,...), $secs2cache is optional. If missing, it will
take the value defined in $connection->cacheSecs (default is 3600 seconds). Note that
CacheSelectLimit(), the secs2cache is still compulsory - sigh.
<p>Sybase SQL Anywhere driver (using ODBC) contributed by Wade Johnson wade#wadejohnson.de
<p><b>1.72 8 March 2002</b></p>
<p>Added @ when returning Fields() to prevent spurious error - "Michael William Miller" mille562#pilot.msu.edu
<p>MetaDatabases() for postgres contributed by Phil pamelant#nerim.net
<p>Mitchell T. Young (mitch#youngfamily.org) contributed informix driver.
<p>Fixed rs2html() problem. I cannot reproduce, so probably a problem with pre PHP 4.1.0 versions,
when supporting new ADODB_FETCH_MODEs.
<p>Mattia Rossi (mattia#technologist.com) contributed BlobDecode() and UpdateBlobFile() for postgresql
using the postgres specific pg_lo_import()/pg_lo_open() - i don't use them but hopefully others will
find this useful. See <a href="http://phplens.com/lens/lensforum/msgs.php?id=1262">this posting</a>
for an example of usage.
<p>Added UpdateBlobFile() for uploading files to a database.
<p>Made UpdateBlob() compatible with oci8po driver.
<p>Added noNullStrings support to oci8 driver. Oracle changes all ' ' strings to nulls,
so you need to set strings to ' ' to prevent the nullifying of strings. $conn->noNullStrings = true;
will do this for you automatically. This is useful when you define a char column as NOT NULL.
<p>Fixed UnixTimeStamp() bug - wasn't setting minutes and seconds properly. Patch from Agusti Fita i Borrell agusti#anglatecnic.com.
<p>Toni Tunkkari added patch for sybase dates. Problem with spaces in day part of date fixed.
<p><b>1.71 18 Jan 2002</b></p>
<p>Sequence start id support. Now $conn->Gen_ID('seqname', 50) to start sequence from 50.
<p>CSV driver fix for selectlimit, from Andreas - akaiser#vocote.de.
<P>Gam3r spotted that a global variable was undefined in the session handler.
<p>Mssql date regex had error. Fixed - reported by Minh Hoang vb_user#yahoo.com.
<p>DBTimeStamp() and DBDate() now accept iso dates and unix timestamps. This means
that the PostgreSQL handling of dates in GetInsertSQL() and GetUpdateSQL() can
be removed. Also if these functions are passed '' or null or false, we return a SQL null.
<p>GetInsertSQL() and GetUpdateSQL() now accept a new parameter, $magicq to
indicate whether quotes should be inserted based on magic quote settings - suggested by
dj#4ict.com.
<p>Reformated docs slightly based on suggestions by Chris Small.
<p><b>1.65 28 Dec 2001</b></p>
<p>Fixed borland_ibase class naming bug.
<p>Now instead of using $rs->fields[0] internally, we use reset($rs->fields) so
that we are compatible with ADODB_FETCH_ASSOC mode. Reported by Nico S.
<p>Changed recordset constructor and _initrs() for oci8 so that it returns the field definitions even
if no rows in the recordset. Reported by Rick Hickerson (rhickers#mv.mv.com).
<p>Improved support for postgresql in GetInsertSQL and GetUpdateSQL by
"mike" mike#partner2partner.com and "Ryan Bailey" rebel#windriders.com
<p><b>1.64 20 Dec 2001</b></p>
<p>Danny Milosavljevic &lt;danny.milo#gmx.net> added some patches for MySQL error handling
and displaying default values.
<p>Fixed some ADODB_FETCH_BOTH inconsistencies in odbc and interbase.
<p>Added more tests to test suite to cover ADODB_FETCH_* and ADODB_ERROR_HANDLER.
<p>Added firebird (ibase) driver
<p>Added borland_ibase driver for interbase 6.5
<p><b>1.63 13 Dec 2001</b></p>
Absolute to the adodb-lib.inc.php file not set properly. Fixed.<p>
<p><b>1.62 11 Dec 2001</b></p>
<p>Major speedup of ADOdb for low-end web sites by reducing the php code loading and compiling
cycle. We conditionally compile not so common functions.
Moved csv code to adodb-csvlib.inc.php to reduce adodb.inc.php parsing. This file
is loaded only when the csv/proxy driver is used, or CacheExecute() is run.
Also moved PageExecute(), GetSelectSQL() and GetUpdateSQL() core code to adodb-lib.inc.php.
This reduced the 70K main adodb.inc.php file to 55K, and since at least 20K of the file
is comments, we have reduced 50K of code in adodb.inc.php to 35K. There
should be 35% reduction in memory and thus 35% speedup in compiling the php code for the
main adodb.inc.php file.
<p>Highly tuned SelectLimit() for oci8 for massive speed improvements on large files.
Selecting 20 rows starting from the 20,000th row of a table is now 7 times faster.
Thx to Tomas V V Cox.
<p>Allow . and # in table definitions in GetInsertSQL and GetUpdateSQL.
See ADODB_TABLE_REGEX constant. Thx to Ari Kuorikoski.
<p>Added ADODB_PREFETCH_ROWS constant, defaulting to 10. This determines the number
of records to prefetch in a SELECT statement. Only used by oci8.</p>
<p>Added high portability Oracle class called oci8po. This uses ? for bind variables, and
lower cases column names.</p>
<p>Now all database drivers support $ADODB_FETCH_MODE, including interbase, ado, and odbc:
ADODB_FETCH_NUM and ADODB_FETCH_ASSOC. ADODB_FETCH_BOTH is not fully implemented for all
database drivers.
<p><b>1.61 Nov 2001</b></p>
<p>Added PO_RecordCount() and PO_Insert_ID(). PO stands for portable. Pablo Roca
[pabloroca#mvps.org]</p>
<p>GenID now returns 0 if not available. Safer is that you should check $conn->hasGenID
for availability.</p>
<p>M'soft ADO we now correctly close recordset in _close() peterd#telephonetics.co.uk</p>
<p>MSSQL now supports GenID(). It generates a 16-byte GUID from mssql newid()
function.</p>
<p>Changed ereg_replace to preg_replace in SelectLimit. This is a fix for mssql.
Ereg doesn't support t or n! Reported by marino Carlos xaplo#postnuke-espanol.org</p>
<p>Added $recordset->connection. This is the ADOConnection object for the recordset.
Works with cached and normal recordsets. Surprisingly, this had no affect on performance!</p>
<p><b>1.54 15 Nov 2001</b></p>
Fixed some more bugs in PageExecute(). I am getting sick of bug in this and will have to
reconsider my QA here. The main issue is that I don't use PageExecute() and
to check whether it is working requires a visual inspection of the html generated currently.
It is possible to write a test script but it would be quite complicated :(
<p> More speedups of SelectLimit() for DB2, Oci8, access, vfp, mssql.
<p>
<p><b>1.53 7 Nov 2001</b></p>
Added support for ADODB_FETCH_ASSOC for ado and odbc drivers.<p>
Tuned GetRowAssoc(false) in postgresql and mysql.<p>
Stephen Van Dyke contributed ADOdb icon, accepted with some minor mods.<p>
Enabled Affected_Rows() for postgresql<p>
Speedup for Concat() using implode() - Benjamin Curtis ben_curtis#yahoo.com<p>
Fixed some more bugs in PageExecute() to prevent infinite loops<p>
<p><b>1.52 5 Nov 2001</b></p>
Spelling error in CacheExecute() caused it to fail. $ql should be $sql in line 625!<p>
Added fixes for parsing [ and ] in GetUpdateSQL().
<p><b>1.51 5 Nov 2001</b></p>
<p>Oci8 SelectLimit() speedup by using OCIFetch().
<p>Oci8 was mistakenly reporting errors when $db->debug = true.
<p>If a connection failed with ODBC, it was not correctly reported - fixed.
<p>_connectionID was inited to -1, changed to false.
<p>Added $rs->FetchRow(), to simplify API, ala PEAR DB
<p>Added PEAR DB compat mode, which is still faster than PEAR! See adodb-pear.inc.php.
<p>Removed postgres pconnect debugging statement.
<p><b>1.50 31 Oct 2001</b></p>
<p>ADOdbConnection renamed to ADOConnection, and ADOdbFieldObject to ADOFieldObject.
<p>PageExecute() now checks for empty $rs correctly, and the errors in the docs on this subject have been fixed.
<p>odbc_error() does not return 6 digit error correctly at times. Implemented workaround.
<p>Added ADORecordSet_empty class. This will speedup INSERTS/DELETES/UPDATES because the return
object created is much smaller.
<p>Added Prepare() to odbc, and oci8 (but doesn't work properly for oci8 still).
<p>Made pgsql a synonym for postgre7, and changed SELECT LIMIT to use OFFSET for compat with
postgres 7.2.
<p>Revised adodb-cryptsession.php thanks to Ari.
<p>Set resources to false on _close, to force freeing of resources.
<p>Added adodb-errorhandler.inc.php, adodb-errorpear.inc.php and raiseErrorFn on Freek's urging.
<p>GetRowAssoc($toUpper=true): $toUpper added as default.
<p>Errors when connecting to a database were not captured formerly. Now we do it correctly.
<p><b>1.40 19 September 2001</b></p>
<p>PageExecute() to implement page scrolling added. Code and idea by Iv&aacute;n Oliva.</p>
<p>Some minor postgresql fixes.</p>
<p>Added sequence support using GenID() for postgresql, oci8, mysql, interbase.</p>
<p>Added UpdateBlob support for interbase (untested).</p>
<p>Added encrypted sessions (see adodb-cryptsession.php). By Ari Kuorikoski &lt;kuoriari#finebyte.com></p>
<p><b>1.31 21 August 2001</b></p>
<p>Many bug fixes thanks to "GaM3R (Cameron)" &lt;gamr#outworld.cx>. Some session changes due to Gam3r.
<p>Fixed qstr() to quote also.
<p>rs2html() now pretty printed.
<p>Jonathan Younger jyounger#unilab.com contributed the great idea GetUpdateSQL() and GetInsertSQL() which
generates SQL to update and insert into a table from a recordset. Modify the recordset fields
array, then can this function to generate the SQL (the SQL is not executed).
<p>"Nicola Fankhauser" &lt;nicola.fankhauser#couniq.com> found some bugs in date handling for mssql.</p>
<p>Added minimal Oracle support for LOBs. Still under development.</p>
Added $ADODB_FETCH_MODE so you can control whether recordsets return arrays which are
numeric, associative or both. This is a global variable you set. Currently only MySQL, Oci8, Postgres
drivers support this.
<p>PostgreSQL properly closes recordsets now. Reported by several people.
<p>
Added UpdateBlob() for Oracle. A hack to make it easier to save blobs.
<p>
Oracle timestamps did not display properly. Fixed.
<p><b>1.20 6 June 2001</b></p>
<p>Now Oracle can connect using tnsnames.ora or server and service name</p>
<p>Extensive Oci8 speed optimizations.
Oci8 code revised to support variable binding, and /*+ FIRST_ROWS */ hint.</p>
<p>Worked around some 4.0.6 bugs in odbc_fetch_into().</p>
<p>Paolo S. Asioli paolo.asioli#libero.it suggested GetRowAssoc().</p>
<p>Escape quotes for oracle wrongly set to '. Now '' is used.</p>
<p>Variable binding now works in ODBC also.</p>
<p>Jumped to version 1.20 because I don't like 13 :-)</p>
<p><b>1.12 6 June 2001</b></p>
<p>Changed $ADODB_DIR to ADODB_DIR constant to plug a security loophole.</p>
<p>Changed _close() to close persistent connections also. Prevents connection leaks.</p>
<p>Major revision of oracle and oci8 drivers.
Added OCI_RETURN_NULLS and OCI_RETURN_LOBS to OCIFetchInto(). BLOB, CLOB and VARCHAR2 recognition
in MetaType() improved. MetaColumns() returns columns in correct sort order.</p>
<p>Interbase timestamp input format was wrong. Fixed.</p>
<p><b>1.11 20 May 2001</b></p>
<p>Improved file locking for Windows.</p>
<p>Probabilistic flushing of cache to avoid avalanche updates when cache timeouts.</p>
<p>Cached recordset timestamp not saved in some scenarios. Fixed.</p>
<p><b>1.10 19 May 2001</b></p>
<p>Added caching. CacheExecute() and CacheSelectLimit().
<p>Added csv driver. See <a href="http://php.weblogs.com/adodb_csv">http://php.weblogs.com/ADODB_csv</a>.
<p>Fixed SelectLimit(), SELECT TOP not working under certain circumstances.
<p>Added better Frontbase support of MetaTypes() by Frank M. Kromann.
<p><b>1.01 24 April 2001</b></p>
<p>Fixed SelectLimit bug. not quoted properly.
<p>SelectLimit: SELECT TOP -1 * FROM TABLE not support by Microsoft. Fixed.</p>
<p>GetMenu improved by glen.davies#cce.ac.nz to support multiple hilited items<p>
<p>FetchNextObject() did not work with only 1 record returned. Fixed bug reported by $tim#orotech.net</p>
<p>Fixed mysql field max_length problem. Fix suggested by Jim Nicholson (jnich#att.com)</p>
<p><b>1.00 16 April 2001</b></p>
<p>Given some brilliant suggestions on how to simplify ADOdb by akul. You no longer need to
setup $ADODB_DIR yourself, and ADOLoadCode() is automatically called by ADONewConnection(),
simplifying the startup code.</p>
<p>FetchNextObject() added. Suggested by Jakub Marecek. This makes FetchObject() obsolete, as
this is more flexible and powerful.</p>
<p>Misc fixes to SelectLimit() to support Access (top must follow distinct) and Fields()
in the array recordset. From Reinhard Balling.</p>
<p><b>0.96 27 Mar 2001</b></p>
<p>ADOConnection Close() did not return a value correctly. Thanks to akul#otamedia.com.</p>
<p>When the horrible magic_quotes is enabled, back-slash () is changed to double-backslash (\).
This doesn't make sense for Microsoft/Sybase databases. We fix this in qstr().</p>
<p>Fixed Sybase date problem in UnixDate() thanks to Toni Tunkkari. Also fixed MSSQL problem
in UnixDate() - thanks to milhouse31#hotmail.com.</p>
<p>MoveNext() moved to leaf classes for speed in MySQL/PostgreSQL. 10-15% speedup.</p>
<p>Added null handling in bindInputArray in Execute() -- Ron Baldwin suggestion.</p>
<p>Fixed some option tags. Thanks to john#jrmstudios.com.</p>
<p><b>0.95 13 Mar 2001</b></p>
<p>Added postgres7 database driver which supports LIMIT and other version 7 stuff in the future.</p>
<p>Added SelectLimit to ADOConnection to simulate PostgreSQL's "select * from table limit 10 offset 3".
Added helper function GetArrayLimit() to ADORecordSet.</p>
<p>Fixed mysql metacolumns bug. Thanks to Freek Dijkstra (phpeverywhere#macfreek.com).</p>
<p>Also many PostgreSQL changes by Freek. He almost rewrote the whole PostgreSQL driver!</p>
<p>Added fix to input parameters in Execute for non-strings by Ron Baldwin.</p>
<p>Added new metatype, X for TeXt. Formerly, metatype B for Blob also included
text fields. Now 'B' is for binary/image data. 'X' for textual data.</p>
<p>Fixed $this->GetArray() in GetRows().</p>
<p>Oracle and OCI8: 1st parameter is always blank -- now warns if it is filled.</p>
<p>Now <i>hasLimit</i> and <i>hasTop</i> added to indicate whether
SELECT * FROM TABLE LIMIT 10 or SELECT TOP 10 * FROM TABLE are supported.</p>
<p><b>0.94 04 Feb 2001</b></p>
<p>Added ADORecordSet::GetRows() for compatibility with Microsoft ADO. Synonym for GetArray().</p>
<p>Added new metatype 'R' to represent autoincrement numbers.</p>
<p>Added ADORecordSet.FetchObject() to return a row as an object.</p>
<p>Finally got a Linux box to test PostgreSql. Many fixes.</p>
<p>Fixed copyright misspellings in 0.93.</p>
<p>Fixed mssql MetaColumns type bug.</p>
<p>Worked around odbc bug in PHP4 for sessions.</p>
<p>Fixed many documentation bugs (affected_rows, metadatabases, qstr).</p>
<p>Fixed MySQL timestamp format (removed comma).</p>
<p>Interbase driver did not call ibase_pconnect(). Fixed.</p>
<p><b>0.93 18 Jan 2002</b></p>
<p>Fixed GetMenu bug.</p>
<p>Simplified Interbase commit and rollback.</p>
<p>Default behaviour on closing a connection is now to rollback all active transactions.</p>
<p>Added field object handling for array recordset for future XML compatibility.</p>
<p>Added arr2html() to convert array to html table.</p>
<p><b>0.92 2 Jan 2002</b></p>
<p>Interbase Commit and Rollback should be working again.</p>
<p>Changed initialisation of ADORecordSet. This is internal and should not affect users. We
are doing this to support cached recordsets in the future.</p>
<p>Implemented ADORecordSet_array class. This allows you to simulate a database recordset
with an array.</p>
<p>Added UnixDate() and UnixTimeStamp() to ADORecordSet.</p>
<p><b>0.91 21 Dec 2000</b></p>
<p>Fixed ODBC so ErrorMsg() is working.</p>
<p>Worked around ADO unrecognised null (0x1) value problem in COM.</p>
<p>Added Sybase support for FetchField() type</p>
<p>Removed debugging code and unneeded html from various files</p>
<p>Changed to javadoc style comments to adodb.inc.php.</p>
<p>Added maxsql as synonym for mysqlt</p>
<p>Now ODBC downloads first 8K of blob by default
<p><b>0.90 15 Nov 2000</b></p>
<p>Lots of testing of Microsoft ADO. Should be more stable now.</p>
<p>Added $ADODB_COUNTREC. Set to false for high speed selects.</p>
<p>Added Sybase support. Contributed by Toni Tunkkari (toni.tunkkari#finebyte.com). Bug in Sybase
API: GetFields is unable to determine date types.</p>
<p>Changed behaviour of RecordSet.GetMenu() to support size parameter (listbox) properly.</p>
<p>Added emptyDate and emptyTimeStamp to RecordSet class that defines how to represent
empty dates.</p>
<p>Added MetaColumns($table) that returns an array of ADOFieldObject's listing
the columns of a table.</p>
<p>Added transaction support for PostgresSQL -- thanks to "Eric G. Werk" egw#netguide.dk.</p>
<p>Added adodb-session.php for session support.</p>
<p><b>0.80 30 Nov 2000</b></p>
<p>Added support for charSet for interbase. Implemented MetaTables for most databases.
PostgreSQL more extensively tested.</p>
<p><b>0.71 22 Nov 2000</b></p>
<p>Switched from using require_once to include/include_once for backward compatability with PHP 4.02 and earlier.</p>
<p><b>0.70 15 Nov 2000</b></p>
<p>Calls by reference have been removed (call_time_pass_reference=Off) to ensure compatibility with future versions of PHP,
except in Oracle 7 driver due to a bug in php_oracle.dll.</p>
<p>PostgreSQL database driver contributed by Alberto Cerezal (acerezalp#dbnet.es).
</p>
<p>Oci8 driver for Oracle 8 contributed by George Fourlanos (fou#infomap.gr).</p>
<p>Added <i>mysqlt</i> database driver to support MySQL 3.23 which has transaction
support. </p>
<p>Oracle default date format (DD-MON-YY) did not match ADOdb default date format (which is YYYY-MM-DD). Use ALTER SESSION to force the default date.</p>
<p>Error message checking is now included in test suite.</p>
<p>MoveNext() did not check EOF properly -- fixed.</p>
<p><b>0.60 Nov 8 2000</b></p>
<p>Fixed some constructor bugs in ODBC and ADO. Added ErrorNo function to ADOConnection
class. </p>
<p><b>0.51 Oct 18 2000</b></p>
<p>Fixed some interbase bugs.</p>
<p><b>0.50 Oct 16 2000</b></p>
<p>Interbase commit/rollback changed to be compatible with PHP 4.03. </p>
<p>CommitTrans( ) will now return true if transactions not supported. </p>
<p>Conversely RollbackTrans( ) will return false if transactions not supported.
</p>
<p><b>0.46 Oct 12</b></p>
Many Oracle compatibility issues fixed.
<p><b>0.40 Sept 26</b></p>
<p>Many bug fixes</p>
<p>Now Code for BeginTrans, CommitTrans and RollbackTrans is working. So is the Affected_Rows
and Insert_ID. Added above functions to test.php.</p>
<p>ADO type handling was busted in 0.30. Fixed.</p>
<p>Generalised Move( ) so it works will all databases, including ODBC.</p>
<p><b>0.30 Sept 18</b></p>
<p>Renamed ADOLoadDB to ADOLoadCode. This is clearer.</p>
<p>Added BeginTrans, CommitTrans and RollbackTrans functions.</p>
<p>Added Affected_Rows() and Insert_ID(), _affectedrows() and _insertID(), ListTables(),
ListDatabases(), ListColumns().</p>
<p>Need to add New_ID() and hasInsertID and hasAffectedRows, autoCommit </p>
<p><b>0.20 Sept 12</b></p>
<p>Added support for Microsoft's ADO.</p>
<p>Added new field to ADORecordSet -- canSeek</p>
<p>Added new parameter to _fetch($ignore_fields = false). Setting to true will
not update fields array for faster performance.</p>
<p>Added new field to ADORecordSet/ADOConnection -- dataProvider to indicate whether
a class is derived from odbc or ado.</p>
<p>Changed class ODBCFieldObject to ADOFieldObject -- not documented currently.</p>
<p>Added benchmark.php and testdatabases.inc.php to the test suite.</p>
<p>Added to ADORecordSet FastForward( ) for future high speed scrolling. Not documented.</p>
<p>Realised that ADO's Move( ) uses relative positioning. ADOdb uses absolute.
</p>
<p><b>0.10 Sept 9 2000</b></p>
<p>First release</p>
</body></html>
-68
View File
@@ -1,68 +0,0 @@
<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">
<h3>ADOdb Library for PHP</h3>
<p>ADOdb is a suite of database libraries that allow you to connect to multiple
databases in a portable manner. Download from <a href=http://adodb.sourceforge.net/>http://adodb.sourceforge.net/</a>.
<ul><li>The ADOdb documentation has moved to <a href=docs-adodb.htm>docs-adodb.htm</a>
This allows you to query, update and insert records using a portable API.
<p><li>The ADOdb data dictionary docs are at <a href=docs-datadict.htm>docs-datadict.htm</a>.
This allows you to create database tables and indexes in a portable manner.
<p><li>The ADOdb database performance monitoring docs are at <a href=docs-perf.htm>docs-perf.htm</a>.
This allows you to perform health checks, tune and monitor your database.
<p><li>The ADOdb database-backed session docs are at <a href=docs-session.htm>docs-session.htm</a>.
</ul>
<p>
<h3>Installation</h3>
Make sure you are running PHP4.0.4 or later. Unpack all the files into a directory accessible by your webserver.
<p>
To test, try modifying some of the tutorial examples. Make sure you customize the connection settings correctly. You can debug using:
<pre>
&lt;?php
include('adodb/adodb.inc.php');
$db = <b>ADONewConnection</b>($driver); # eg. 'mysql' or 'oci8'
$db->debug = true;
$db-><b>Connect</b>($server, $user, $password, $database);
$rs = $db-><b>Execute</b>('select * from some_small_table');
print "&lt;pre>";
print_r($rs-><b>GetRows</b>());
print "&lt;/pre>";
?>
</pre>
<h3>How are people using ADOdb</h3>
Here are some examples of how people are using ADOdb:
<ul>
<li> <strong>PhpLens</strong> 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.
</li>
<li> <strong>PHAkt</strong>: PHP Extension for DreamWeaver Ultradev allows
you to script PHP in the popular Web page editor. Database handling provided
by ADOdb. </li>
<li> <strong>Analysis Console for Intrusion Databases (ACID)</strong>: 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. </li>
<li> <strong>PostNuke</strong> 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. </li>
<li><strong> EasyPublish CMS</strong> is another free content management system
for managing information and integrated modules on your internet, intranet-
and extranet-sites. From Norway. </li>
<li> <strong>NOLA</strong> is a full featured accounting, inventory, and job
tracking application. It is licensed under the GPL, and developed by Noguska.
</li>
</ul>
</body>
</html>
-367
View File
@@ -1,367 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Tips on Writing Portable SQL for Multiple Databases for PHP</title>
</head>
<body bgcolor=white>
<table width=100% border=0><tr><td><h2>Tips on Writing Portable SQL &nbsp;</h2></td><td>
<div align=right><img src="cute_icons_for_site/adodb.gif"></div></td></tr></table>
<p>Updated 6 Oct 2006. Added OffsetDate example.
<p>Updated 18 Sep 2003. Added Portable Native SQL section.
<p>
If you are writing an application that is used in multiple environments and
operating systems, you need to plan to support multiple databases. This article
is based on my experiences with multiple database systems, stretching from 4th
Dimension in my Mac days, to the databases I currently use, which are: Oracle,
FoxPro, Access, MS SQL Server and MySQL. Although most of the advice here applies
to using SQL with Perl, Python and other programming languages, I will focus on PHP and how
the <a href="http://adodb.sourceforge.net/">ADOdb</a> database abstraction library
offers some solutions.<p></p>
<p>Most database vendors practice product lock-in. The best or fastest way to
do things is often implemented using proprietary extensions to SQL. This makes
it extremely hard to write portable SQL code that performs well under all conditions.
When the first ANSI committee got together in 1984 to standardize SQL, the database
vendors had such different implementations that they could only agree on the
core functionality of SQL. Many important application specific requirements
were not standardized, and after so many years since the ANSI effort began,
it looks as if much useful database functionality will never be standardized.
Even though ANSI-92 SQL has codified much more, we still have to implement portability
at the application level.</p>
<h3><b>Selects</b></h3>
<p>The SELECT statement has been standardized to a great degree. Nearly every
database supports the following:</p>
<p>SELECT [cols] FROM [tables]<br>
&nbsp;&nbsp;[WHERE conditions]<br>
&nbsp; [GROUP BY cols]<br>
&nbsp; [HAVING conditions] <br>
&nbsp; [ORDER BY cols]</p>
<p>But so many useful techniques can only be implemented by using proprietary
extensions. For example, when writing SQL to retrieve the first 10 rows for
paging, you could write...</p>
<table width="80%" border="1" cellspacing="0" cellpadding="0" align="center">
<tr>
<td><b>Database</b></td>
<td><b>SQL Syntax</b></td>
</tr>
<tr>
<td>DB2</td>
<td>select * from table fetch first 10 rows only</td>
</tr>
<tr>
<td>Informix</td>
<td>select first 10 * from table</td>
</tr>
<tr>
<td>Microsoft SQL Server and Access</td>
<td>select top 10 * from table</td>
</tr>
<tr>
<td>MySQL and PostgreSQL</td>
<td>select * from table limit 10</td>
</tr>
<tr>
<td>Oracle 8i</td>
<td>select * from (select * from table) where rownum &lt;= 10</td>
</tr>
</table>
<p>This feature of getting a subset of data is so useful that in the PHP class
library ADOdb, we have a SelectLimit( ) function that allows you to hide the
implementation details within a function that will rewrite your SQL for you:</p>
<pre>$connection-&gt;SelectLimit('select * from table', 10);
</pre>
<p><b>Selects: Fetch Modes</b></p>
<p>PHP allows you to retrieve database records as arrays. You can choose to have
the arrays indexed by field name or number. However different low-level PHP
database drivers are inconsistent in their indexing efforts. ADOdb allows you
to determine your prefered mode. You set this by setting the variable $ADODB_FETCH_MODE
to either of the constants ADODB_FETCH_NUM (for numeric indexes) or ADODB_FETCH_ASSOC
(using field names as an associative index).</p>
<p>The default behaviour of ADOdb varies depending on the database you are using.
For consistency, set the fetch mode to either ADODB_FETCH_NUM (for speed) or
ADODB_FETCH_ASSOC (for convenience) at the beginning of your code. </p>
<p><b>Selects: Counting Records</b></p>
<p>Another problem with SELECTs is that some databases do not return the number
of rows retrieved from a select statement. This is because the highest performance
databases will return records to you even before the last record has been found.
</p>
<p>In ADOdb, RecordCount( ) returns the number of rows returned, or will emulate
it by buffering the rows and returning the count after all rows have been returned.
This can be disabled for performance reasons when retrieving large recordsets
by setting the global variable $ADODB_COUNTRECS = false. This variable is checked
every time a query is executed, so you can selectively choose which recordsets
to count.</p>
<p>If you prefer to set $ADODB_COUNTRECS = false, ADOdb still has the PO_RecordCount(
) function. This will return the number of rows, or if it is not found, it will
return an estimate using SELECT COUNT(*):</p>
<pre>$rs = $db-&gt;Execute(&quot;select * from table where state=$state&quot;);
$numrows = $rs-&gt;PO_RecordCount('table', &quot;state=$state&quot;);</pre>
<p><b>Selects: Locking</b> </p>
<p>SELECT statements are commonly used to implement row-level locking of tables.
Other databases such as Oracle, Interbase, PostgreSQL and MySQL with InnoDB
do not require row-level locking because they use versioning to display data
consistent with a specific point in time.</p>
<p>Currently, I recommend encapsulating the row-level locking in a separate function,
such as RowLock($table, $where):</p>
<pre>$connection-&gt;BeginTrans( );
$connection-&gt;RowLock($table, $where); </pre>
<pre><font color=green># some operation</font></pre>
<pre>if ($ok) $connection-&gt;CommitTrans( );
else $connection-&gt;RollbackTrans( );
</pre>
<p><b>Selects: Outer Joins</b></p>
<p>Not all databases support outer joins. Furthermore the syntax for outer joins
differs dramatically between database vendors. One portable (and possibly slower)
method of implementing outer joins is using UNION.</p>
<p>For example, an ANSI-92 left outer join between two tables t1 and t2 could
look like:</p>
<pre>SELECT t1.col1, t1.col2, t2.cola <br> FROM t1 <i>LEFT JOIN</i> t2 ON t1.col = t2.col</pre>
<p>This can be emulated using:</p>
<pre>SELECT t1.col1, t1.col2, t2.cola FROM t1, t2 <br> WHERE t1.col = t2.col
UNION ALL
SELECT col1, col2, null FROM t1 <br> WHERE t1.col not in (select distinct col from t2)
</pre>
<p>Since ADOdb 2.13, we provide some hints in the connection object as to legal
join variations. This is still incomplete and sometimes depends on the database
version you are using, but is useful as a general guideline:</p>
<p><font face="Courier New, Courier, mono">$conn-&gt;leftOuter</font>: holds the
operator used for left outer joins (eg. '*='), or false if not known or not
available.<br>
<font face="Courier New, Courier, mono">$conn-&gt;rightOuter</font>: holds the
operator used for right outer joins (eg '=*'), or false if not known or not
available.<br>
<font face="Courier New, Courier, mono">$conn-&gt;ansiOuter</font>: boolean
that if true means that ANSI-92 style outer joins are supported, or false if
not known.</p>
<h3><b>Inserts</b> </h3>
<p>When you create records, you need to generate unique id's for each record.
There are two common techniques: (1) auto-incrementing columns and (2) sequences.
</p>
<p>Auto-incrementing columns are supported by MySQL, Sybase and Microsoft Access
and SQL Server. However most other databases do not support this feature. So
for portability, you have little choice but to use sequences. Sequences are
special functions that return a unique incrementing number every time you call
it, suitable to be used as database keys. In ADOdb, we use the GenID( ) function.
It has takes a parameter, the sequence name. Different tables can have different
sequences. </p>
<pre>$id = $connection-&gt;GenID('sequence_name');<br>$connection-&gt;Execute(&quot;insert into table (id, firstname, lastname) <br> values ($id, $firstname, $lastname)&quot;);</pre>
<p>For databases that do not support sequences natively, ADOdb emulates sequences
by creating a table for every sequence.</p>
<h3><b>Binding</b></h3>
<p>Binding variables in an SQL statement is another tricky feature. Binding is
useful because it allows pre-compilation of SQL. When inserting multiple records
into a database in a loop, binding can offer a 50% (or greater) speedup. However
many databases such as Access and MySQL do not support binding natively and
there is some overhead in emulating binding. Furthermore, different databases
(specificly Oracle!) implement binding differently. My recommendation is to
use binding if your database queries are too slow, but make sure you are using
a database that supports it like Oracle. </p>
<p>ADOdb supports portable Prepare/Execute with:</p>
<pre>$stmt = $db-&gt;Prepare('select * from customers where custid=? and state=?');
$rs = $db-&gt;Execute($stmt, array($id,'New York'));</pre>
<p>Oracle uses named bind placeholders, not "?", so to support portable binding, we have Param() that generates
the correct placeholder (available since ADOdb 3.92):
<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>
<a name="native"></a>
<h2>Portable Native SQL</h2>
<p>ADOdb provides the following functions for portably generating SQL functions
as strings to be merged into your SQL statements (some are only available since
ADOdb 3.92): </p>
<table width="75%" border="1" align=center>
<tr>
<td width=30%><b>Function</b></td>
<td><b>Description</b></td>
</tr>
<tr>
<td>DBDate($date)</td>
<td>Pass in a UNIX timestamp or ISO date and it will convert it to a date
string formatted for INSERT/UPDATE</td>
</tr>
<tr>
<td>DBTimeStamp($date)</td>
<td>Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp
string formatted for INSERT/UPDATE</td>
</tr>
<tr>
<td>SQLDate($date, $fmt)</td>
<td>Portably generate a date formatted using $fmt mask, for use in SELECT
statements.</td>
</tr>
<tr>
<td>OffsetDate($date, $ndays)</td>
<td>Portably generate a $date offset by $ndays.</td>
</tr>
<tr>
<td>Concat($s1, $s2, ...)</td>
<td>Portably concatenate strings. Alternatively, for mssql use mssqlpo driver,
which allows || operator.</td>
</tr>
<tr>
<td>IfNull($fld, $replaceNull)</td>
<td>Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL.</td>
</tr>
<tr>
<td>Param($name)</td>
<td>Generates bind placeholders, using ? or named conventions as appropriate.</td>
</tr>
<tr><td>$db->sysDate</td><td>Property that holds the SQL function that returns today's date</td>
</tr>
<tr><td>$db->sysTimeStamp</td><td>Property that holds the SQL function that returns the current
timestamp (date+time).
</td>
</tr>
<tr>
<td>$db->concat_operator</td><td>Property that holds the concatenation operator
</td>
</tr>
<tr><td>$db->length</td><td>Property that holds the name of the SQL strlen function.
</td></tr>
<tr><td>$db->upperCase</td><td>Property that holds the name of the SQL strtoupper function.
</td></tr>
<tr><td>$db->random</td><td>Property that holds the SQL to generate a random number between 0.00 and 1.00.
</td>
</tr>
<tr><td>$db->substr</td><td>Property that holds the name of the SQL substring function.
</td></tr>
</table>
<p>&nbsp; </p>
<h2>DDL and Tuning</h2>
There are database design tools such as ERWin or Dezign that allow you to generate data definition language commands such as ALTER TABLE or CREATE INDEX from Entity-Relationship diagrams.
<p>
However if you prefer to use a PHP-based table creation scheme, adodb provides you with this feature. Here is the code to generate the SQL to create a table with:
<ol>
<li> Auto-increment primary key 'ID', </li>
<li>The person's 'NAME' VARCHAR(32) NOT NULL and defaults to '', </li>
<li>The date and time of record creation 'CREATED', </li>
<li> The person's 'AGE', defaulting to 0, type NUMERIC(16). </li>
</ol>
<p>
Also create a compound index consisting of 'NAME' and 'AGE':
<pre>
$datadict = <strong>NewDataDictionary</strong>($connection);
$flds = "
<font color="#660000"> ID I AUTOINCREMENT PRIMARY,
NAME C(32) DEFAULT '' NOTNULL,
CREATED T DEFTIMESTAMP,
AGE N(16) DEFAULT 0</font>
";
$sql1 = $datadict-><strong>CreateTableSQL</strong>('tabname', $flds);
$sql2 = $datadict-><strong>CreateIndexSQL</strong>('idx_name_age', 'tabname', 'NAME,AGE');
</pre>
<h3>Data Types</h3>
<p>Stick to a few data types that are available in most databases. Char, varchar
and numeric/number are supported by most databases. Most other data types (including
integer, boolean and float) cannot be relied on being available. I recommend
using char(1) or number(1) to hold booleans. </p>
<p>Different databases have different ways of representing dates and timestamps/datetime.
ADOdb attempts to display all dates in ISO (YYYY-MM-DD) format. ADOdb also provides
DBDate( ) and DBTimeStamp( ) to convert dates to formats that are acceptable
to that database. Both functions accept Unix integer timestamps and date strings
in ISO format.</p>
<pre>$date1 = $connection-&gt;DBDate(time( ));<br>$date2 = $connection-&gt;DBTimeStamp('2002-02-23 13:03:33');</pre>
<p>We also provide functions to convert database dates to Unix timestamps:</p>
<pre>$unixts = $recordset-&gt;UnixDate('#2002-02-30#'); <font color="green"># MS Access date =gt; unix timestamp</font></pre>
<p>For date calculations, we have OffsetDate which allows you to calculate dates such as <i>yesterday</i> and <i>next week</i> in a RDBMS independant fashion. For example, if we want to set a field to 6 hour from now, use:
<pre>
$sql = 'update table set dtimefld='.$db-&gt;OffsetDate($db-&gtsysTimeStamp, 6/24).' where ...';
</pre>
<p>The maximum length of a char/varchar field is also database specific. You can
only assume that field lengths of up to 250 characters are supported. This is
normally impractical for web based forum or content management systems. You
will need to be familiar with how databases handle large objects (LOBs). ADOdb
implements two functions, UpdateBlob( ) and UpdateClob( ) that allow you to
update fields holding Binary Large Objects (eg. pictures) and Character Large
Objects (eg. HTML articles):</p>
<pre><font color=green># for oracle </font>
$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1,empty_blob())');
$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
<font color=green># non-oracle databases</font>
$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
</pre>
<p>Null handling is another area where differences can occur. This is a mine-field,
because 3-value logic is tricky.
<p>In general, I avoid using nulls except for dates and default all my numeric
and character fields to 0 or the empty string. This maintains consistency with
PHP, where empty strings and zero are treated as equivalent, and avoids SQL
ambiguities when you use the ANY and EXISTS operators. However if your database
has significant amounts of missing or unknown data, using nulls might be a good
idea.
<p>
ADOdb also supports a portable <a href=http://phplens.com/adodb/reference.functions.concat.html#ifnull>IfNull</a> function, so you can define what to display
if the field contains a null.
<h3><b>Stored Procedures</b></h3>
<p>Stored procedures are another problem area. Some databases allow recordsets
to be returned in a stored procedure (Microsoft SQL Server and Sybase), and
others only allow output parameters to be returned. Stored procedures sometimes
need to be wrapped in special syntax. For example, Oracle requires such code
to be wrapped in an anonymous block with BEGIN and END. Also internal sql operators
and functions such as +, ||, TRIM( ), SUBSTR( ) or INSTR( ) vary between vendors.
</p>
<p>An example of how to call a stored procedure with 2 parameters and 1 return
value follows:</p>
<pre> switch ($db->databaseType) {
case '<font color="#993300">mssql</font>':
$sql = <font color="#000000"><font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font></font>; break;
case '<font color="#993300">oci8</font>':
$sql =
<font color="#993300"> </font><font color="#000000"><font color="#993300">&quot;declare RETVAL integer;begin :RETVAL := </font><font color="#000000"><font color="#993333"><font color="#993300">SP_RUNSOMETHING</font></font></font><font color="#993300">(:myid,:group);end;&quot;;
</font> break;</font>
default:
die('<font color="#993300">Unsupported feature</font>');
}
<font color="#000000"><font color="green"> # @RETVAL = SP_RUNSOMETHING @myid,@group</font>
$stmt = $db-&gt;PrepareSP($sql); <br> $db-&gt;Parameter($stmt,$id,'<font color="#993300">myid</font>');
$db-&gt;Parameter($stmt,$group,'<font color="#993300">group</font>');
<font color="green"># true indicates output parameter<br> </font>$db-&gt;Parameter($stmt,$ret,'<font color="#993300">RETVAL</font>',true);
$db-&gt;Execute($stmt); </font></pre>
<p>As you can see, the ADOdb API is the same for both databases. But the stored
procedure SQL syntax is quite different between databases and is not portable,
so be forewarned! However sometimes you have little choice as some systems only
allow data to be accessed via stored procedures. This is when the ultimate portability
solution might be the only solution: <i>treating portable SQL as a localization
exercise...</i></p>
<h3><b>SQL as a Localization Exercise</b></h3>
<p> In general to provide real portability, you will have to treat SQL coding
as a localization exercise. In PHP, it has become common to define separate
language files for English, Russian, Korean, etc. Similarly, I would suggest
you have separate Sybase, Intebase, MySQL, etc files, and conditionally include
the SQL based on the database. For example, each MySQL SQL statement would be
stored in a separate variable, in a file called 'mysql-lang.inc.php'.</p>
<pre>$sqlGetPassword = '<font color="#993300">select password from users where userid=%s</font>';
$sqlSearchKeyword = quot;<font color="#993300">SELECT * FROM articles WHERE match (title,body) against (%s</font>)&quot;;</pre>
<p>In our main PHP file:</p>
<pre><font color=green># define which database to load...</font>
<b>$database = '<font color="#993300">mysql</font>';
include_once(&quot;<font color="#993300">$database-lang.inc.php</font>&quot;);</b>
$db = NewADOConnection($database);
$db->PConnect(...) or die('<font color="#993300">Failed to connect to database</font>');
<font color=green># search for a keyword $word</font>
$rs = $db-&gt;Execute(sprintf($sqlSearchKeyWord,$db-&gt;qstr($word)));</pre>
<p>Note that we quote the $word variable using the qstr( ) function. This is because
each database quotes strings using different conventions.</p>
<p>
<h3>Final Thoughts</h3>
<p>The best way to ensure that you have portable SQL is to have your data tables designed using
sound principles. Learn the theory of normalization and entity-relationship diagrams and model
your data carefully. Understand how joins and indexes work and how they are used to tune performance.
<p> Visit the following page for more references on database theory and vendors:
<a href="http://php.weblogs.com/sql_tutorial">http://php.weblogs.com/sql_tutorial</a>.
Also read this article on <a href=http://phplens.com/lens/php-book/optimizing-debugging-php.php>Optimizing PHP</a>.
<p>
<font size=1>(c) 2002-2003 John Lim.</font>
</body>
</html>
-290
View File
@@ -1,290 +0,0 @@
<!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 = 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>