2402223a5b59b4777ff6a8e3c841a628f184101b
[Packages/TYPO3.CMS.git] / typo3 / sysext / adodb / adodb / docs / docs-adodb.htm
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html><head><title>ADODB Manual</title>
3
4 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
5
6
7 <style>
8 pre {
9 background-color: #eee;
10 padding: 0.75em 1.5em;
11 font-size: 12px;
12 border: 1px solid #ddd;
13 }
14 </style></head>
15 <body bgcolor="#ffffff" text="black">
16
17 <h2>ADOdb Library for PHP</h2>
18 <p>V4.81 3 May 2006 (c) 2000-2006 John Lim (jlim#natsoft.com)</p>
19 <p><font size="1">This software is dual licensed using BSD-Style and LGPL. This
20 means you can use it in compiled proprietary and commercial products.</font></p>
21
22
23 <p>Useful ADOdb links: <a href="http://adodb.sourceforge.net/#download">Download</a> &nbsp; <a href="http://adodb.sourceforge.net/#docs">Other Docs</a>
24
25 </p><p><a href="#intro"><b>Introduction</b></a><b><br>
26 <a href="#features">Unique Features</a><br>
27 <a href="#users">How People are using ADOdb</a><br>
28 <a href="#bugs">Feature Requests and Bug Reports</a><br>
29 </b><b><a href="#install">Installation</a><br>
30 <a href="#mininstall">Minimum Install</a><br>
31 <a href="#coding">Initializing Code and Connectioning to Databases</a><br>
32 </b><font size="2"> &nbsp; <a href="#dsnsupport">Data Source Name (DSN) Support</a></font> &nbsp; <a href="#connect_ex">Connection Examples</a> <br>
33 <b><a href="#speed">High Speed ADOdb - tuning tips</a></b><br>
34 <b><a href="#hack">Hacking and Modifying ADOdb Safely</a><br>
35 <a href="#php5">PHP5 Features</a></b><br>
36 <font size="2"><a href="#php5iterators">foreach iterators</a> <a href="#php5exceptions">exceptions</a></font><br>
37 <b> <a href="#drivers">Supported Databases</a></b><br>
38 <b> <a href="#quickstart">Tutorials</a></b><br>
39 <a href="#ex1">Example 1: Select</a><br>
40 <a href="#ex2">Example 2: Advanced Select</a><br>
41 <a href="#ex3">Example 3: Insert</a><br>
42 <a href="#ex4">Example 4: Debugging</a> &nbsp;<a href="#exrs2html">rs2html
43 example</a><br>
44 <a href="#ex5">Example 5: MySQL and Menus</a><br>
45 <a href="#ex6">Example 6: Connecting to Multiple Databases at once</a> <br>
46 <a href="#ex7">Example 7: Generating Update and Insert SQL</a> <br>
47 <a href="#ex8">Example 8: Implementing Scrolling with Next and Previous</a><br>
48 <a href="#ex9">Example 9: Exporting in CSV or Tab-Delimited Format</a> <br>
49 <a href="#ex10">Example 10: Custom filters</a><br>
50 <a href="#ex11">Example 11: Smart Transactions</a><br>
51 <br>
52 <b> <a href="#errorhandling">Using Custom Error Handlers and PEAR_Error</a><br>
53 <a href="#DSN">Data Source Names</a><br>
54 <a href="#caching">Caching</a><br>
55 <a href="#pivot">Pivot Tables</a></b>
56 </p><p><a href="#ref"><b>REFERENCE</b></a>
57 </p><p> <font size="2">Variables: <a href="#adodb_countrecs">$ADODB_COUNTRECS</a>
58 <a href="#adodb_ansi_padding_off">$ADODB_ANSI_PADDING_OFF</a>
59 <a href="#adodb_cache_dir">$ADODB_CACHE_DIR</a> <br>
60 &nbsp; &nbsp; &nbsp; &nbsp; <a href="#force_type">$ADODB_FORCE_TYPE</a>
61 <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a>
62 <a href="#adodb_lang">$ADODB_LANG</a> <br>
63 Constants: </font><font size="2"><a href="#adodb_assoc_case">ADODB_ASSOC_CASE</a>
64 </font><br>
65 <a href="#ADOConnection"><b> ADOConnection</b></a><br>
66 <font size="2">Connections: <a href="#connect">Connect</a> <a href="#pconnect">PConnect</a>
67 <a href="#nconnect">NConnect</a> <a href="#isconnected">IsConnected</a><br>
68 Executing SQL: <a href="#execute">Execute</a> <a href="#cacheexecute"><i>CacheExecute</i></a>
69 <a href="#selectlimit">SelectLimit</a> <a href="#cacheSelectLimit"><i>CacheSelectLimit</i></a>
70 <a href="#param">Param</a> <a href="#prepare">Prepare</a> <a href="#preparesp">PrepareSP</a>
71 <a href="#inparameter">InParameter</a> <a href="#outparameter">OutParameter</a> <a href="#autoexecute">AutoExecute</a>
72 <br>
73 &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="#getone">GetOne</a>
74 <a href="#cachegetone"><i>CacheGetOne</i></a> <a href="#getrow">GetRow</a> <a href="#cachegetrow"><i>CacheGetRow</i></a>
75 <a href="#getall">GetAll</a> <a href="#cachegetall"><i>CacheGetAll</i></a> <a href="#getcol">GetCol</a>
76 <a href="#cachegetcol"><i>CacheGetCol</i></a> <a href="#getassoc1">GetAssoc</a> <a href="#cachegetassoc"><i>CacheGetAssoc</i></a> <a href="#replace">Replace</a>
77 <br>
78 &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="#executecursor">ExecuteCursor</a>
79 (oci8 only)<br>
80 Generates SQL strings: <a href="#getupdatesql">GetUpdateSQL</a> <a href="#getinsertsql">GetInsertSQL</a>
81 <a href="#concat">Concat</a> <a href="#ifnull">IfNull</a> <a href="#length">length</a> <a href="#random">random</a> <a href="#substr">substr</a>
82 <a href="#qstr">qstr</a> <a href="#param">Param</a> <a href="#OffsetDate">OffsetDate</a> <a href="#SQLDate">SQLDate</a>
83 <a href="#dbdate">DBDate</a> <a href="#dbtimestamp">DBTimeStamp</a>
84 <br>
85 Blobs: <a href="#updateblob">UpdateBlob</a> <a href="#updateclob">UpdateClob</a>
86 <a href="#updateblobfile">UpdateBlobFile</a> <a href="#blobencode">BlobEncode</a>
87 <a href="#blobdecode">BlobDecode</a><br>
88 Paging/Scrolling: <a href="#pageexecute">PageExecute</a> <a href="#cachepageexecute">CachePageExecute</a><br>
89 Cleanup: <a href="#cacheflush">CacheFlush</a> <a href="#Close">Close</a><br>
90 Transactions: <a href="#starttrans">StartTrans</a> <a href="#completetrans">CompleteTrans</a>
91 <a href="#failtrans">FailTrans</a> <a href="#hasfailedtrans">HasFailedTrans</a>
92 <a href="#begintrans">BeginTrans</a> <a href="#committrans">CommitTrans</a>
93 <a href="#rollbacktrans">RollbackTrans</a> <br>
94 Fetching Data: </font> <font size="2"><a href="#setfetchmode">SetFetchMode</a><br>
95 Strings: <a href="#concat">concat</a> <a href="#length">length</a> <a href="#qstr">qstr</a> <a href="#quote">quote</a> <a href="#substr">substr</a><br>
96 Dates: <a href="#dbdate">DBDate</a> <a href="#dbtimestamp">DBTimeStamp</a> <a href="#unixdate">UnixDate</a>
97 <a href="#unixtimestamp">UnixTimeStamp</a> <a href="#OffsetDate">OffsetDate</a>
98 <a href="#SQLDate">SQLDate</a> <br>
99 Row Management: <a href="#affected_rows">Affected_Rows</a> <a href="#inserted_id">Insert_ID</a> <a href="#rowlock">RowLock</a>
100 <a href="#genid">GenID</a> <a href="#createseq">CreateSequence</a> <a href="#dropseq">DropSequence</a>
101 <br>
102 Error Handling: <a href="#errormsg">ErrorMsg</a> <a href="#errorno">ErrorNo</a>
103 <a href="#metaerror">MetaError</a> <a href="#metaerrormsg">MetaErrorMsg</a><br>
104 Data Dictionary (metadata): <a href="#metadatabases">MetaDatabases</a> <a href="#metatables">MetaTables</a>
105 <a href="#metacolumns">MetaColumns</a> <a href="#metacolumnames">MetaColumnNames</a>
106 <a href="#metaprimarykeys">MetaPrimaryKeys</a> <a href="#metaforeignkeys">MetaForeignKeys</a>
107 <a href="#serverinfo">ServerInfo</a> <br>
108 Statistics and Query-Rewriting: <a href="#logsql">LogSQL</a> <a href="#fnexecute">fnExecute
109 and fnCacheExecute</a><br>
110 </font><font size="2">Deprecated: <a href="#bind">Bind</a> <a href="#blankrecordset">BlankRecordSet</a>
111 <a href="#parameter">Parameter</a></font>
112 <a href="#adorecordSet"><b><br>
113 ADORecordSet</b></a><br>
114 <font size="2">
115 Returns one field: <a href="#fields">Fields</a><br>
116 Returns one row:<a href="#fetchrow">FetchRow</a> <a href="#fetchinto">FetchInto</a>
117 <a href="#fetchobject">FetchObject</a> <a href="#fetchnextobject">FetchNextObject</a>
118 <a href="#fetchobj">FetchObj</a> <a href="#fetchnextobj">FetchNextObj</a>
119 <a href="#getrowassoc">GetRowAssoc</a> <br>
120 Returns all rows:<a href="#getarray">GetArray</a> <a href="#getrows">GetRows</a>
121 <a href="#getassoc">GetAssoc</a><br>
122 Scrolling:<a href="#move">Move</a> <a href="#movenext">MoveNext</a> <a href="#movefirst">MoveFirst</a>
123 <a href="#movelast">MoveLast</a> <a href="#abspos">AbsolutePosition</a> <a href="#currentrow">CurrentRow</a>
124 <a href="#atfirstpage">AtFirstPage</a> <a href="#atlastpage">AtLastPage</a>
125 <a href="#absolutepage">AbsolutePage</a> </font> <font size="2"><br>
126 Menu generation:<a href="#getmenu">GetMenu</a> <a href="#getmenu2">GetMenu2</a><br>
127 Dates:<a href="#userdate">UserDate</a> <a href="#usertimestamp">UserTimeStamp</a>
128 <a href="#unixdate">UnixDate</a> <a href="#unixtimestamp">UnixTimeStamp<br>
129 </a>Recordset Info:<a href="#recordcount">RecordCount</a> <a href="#po_recordcount">PO_RecordSet</a>
130 <a href="#nextrecordset">NextRecordSet</a><br>
131 Field Info:<a href="#fieldcount">FieldCount</a> <a href="#fetchfield">FetchField</a>
132 <a href="#metatype">MetaType</a><br>
133 Cleanup: <a href="#rsclose">Close</a></font>
134 </p>
135 <p><font size="2"><a href="#rs2html"><b>rs2html</b></a>&nbsp; <a href="#exrs2html">example</a></font><br>
136 <a href="#adodiff">Differences between ADOdb and ADO</a><br>
137 <a href="#driverguide"><b>Database Driver Guide<br>
138 </b></a><b><a href="#changes">Change Log</a></b><br>
139 </p>
140 <h2>Introduction<a name="intro"></a></h2>
141 <p>PHP's database access functions are not standardised. This creates a need for
142 a database class library to hide the differences between the different database
143 API's (encapsulate the differences) so we can easily switch databases. PHP 4.0.5 or later
144 is now required (because we use array-based str_replace).</p>
145 <p>We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, Informix,
146 PostgreSQL, FrontBase, SQLite, Interbase (Firebird and Borland variants), Foxpro, Access, ADO, DB2, SAP DB and ODBC.
147 We have had successful reports of connecting to Progress and CacheLite via ODBC. We hope more people
148 will contribute drivers to support other databases.</p>
149 <p>PHP4 supports session variables. You can store your session information using
150 ADOdb for true portability and scalability. See adodb-session.php for more information.</p>
151 <p>Also read <a href="http://phplens.com/lens/adodb/tips_portable_sql.htm">tips_portable_sql.htm</a>
152 for tips on writing
153 portable SQL.</p>
154 <h2>Unique Features of ADOdb<a name="features"></a></h2>
155 <ul>
156 <li><b>Easy for Windows programmers</b> to adapt to because many of the conventions
157 are similar to Microsoft's ADO.</li>
158 <li>Unlike other PHP database classes which focus only on select statements,
159 <b>we provide support code to handle inserts and updates which can be adapted
160 to multiple databases quickly.</b> Methods are provided for date handling,
161 string concatenation and string quoting characters for differing databases.</li>
162 <li>A<b> metatype system </b>is built in so that we can figure out that types
163 such as CHAR, TEXT and STRING are equivalent in different databases.</li>
164 <li><b>Easy to port</b> because all the database dependant code are stored in
165 stub functions. You do not need to port the core logic of the classes.</li>
166 <li><b>Portable table and index creation</b> with the <a href="docs-datadict.htm">datadict</a> classes.
167 </li><li><b>Database performance monitoring and SQL tuning</b> with the <a href="docs-perf.htm">performance monitoring</a> classes.
168 </li><li><b>Database-backed sessions</b> with the <a href="docs-session.htm">session management</a> classes. Supports session expiry notification.
169 <li><b>Object-Relational Mapping</b> using <a href="docs-active-record.htm">ADOdb_Active_Record</a> classes.
170 </li></ul>
171 <h2>How People are using ADOdb<a name="users"></a></h2>
172 Here are some examples of how people are using ADOdb (for a much longer list,
173 visit <a href="http://phplens.com/phpeverywhere/adodb-cool-apps">adodb-cool-apps</a>):
174 <ul>
175 <li><a href="http://phplens.com/">PhpLens</a> is a commercial data grid
176 component that allows both cool Web designers and serious unshaved
177 programmers to develop and maintain databases on the Web easily.
178 Developed by the author of ADOdb.<p>
179
180 </p></li><li><a href="http://www.interakt.ro/phakt/">PHAkt: PHP Extension for DreamWeaver Ultradev</a> allows you to script PHP in the popular Web page editor. Database handling provided by ADOdb.<p>
181
182 </p></li><li><a href="http://www.andrew.cmu.edu/%7Erdanyliw/snort/snortacid.html">Analysis Console for Intrusion Databases</a>
183 (ACID): PHP-based analysis engine to search and process a database of
184 security incidents generated by security-related software such as IDSes
185 and firewalls (e.g. Snort, ipchains). By Roman Danyliw.<p>
186
187 </p></li><li><a href="http://www.postnuke.com/">PostNuke</a> is a very
188 popular free content management system and weblog system. It offers
189 full CSS support, HTML 4.01 transitional compliance throughout, an
190 advanced blocks system, and is fully multi-lingual enabled. <p>
191
192 </p></li><li><a href="http://www.auto-net.no/easypublish.php?page=index&amp;lang_id=2">EasyPublish CMS</a>
193 is another free content management system for managing information and
194 integrated modules on your internet, intranet- and extranet-sites. From
195 Norway.<p>
196
197 </p></li><li><a href="http://nola.noguska.com/">NOLA</a> is a full featured accounting, inventory, and job tracking application. It is licensed under the GPL, and developed by Noguska.
198 </li></ul><p>
199
200 </p><h2>Feature Requests and Bug Reports<a name="bugs"></a></h2>
201 <p>Feature requests and bug reports can be emailed to <a href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a>
202 or posted to the ADOdb Help forums at <a href="http://phplens.com/lens/lensforum/topics.php?id=4">http://phplens.com/lens/lensforum/topics.php?id=4</a>.</p>
203 <h2>Installation Guide<a name="install"></a></h2>
204 <p>Make sure you are running PHP 4.0.5 or later.
205 Unpack all the files into a directory accessible by your webserver.</p>
206 <p>To test, try modifying some of the tutorial examples. Make sure you customize
207 the connection settings correctly. You can debug using <i>$db-&gt;debug = true</i> as shown below:</p>
208 <pre>&lt;?php<br> include('adodb/adodb.inc.php');<br> $db = <a href="#adonewconnection">ADONewConnection</a>($dbdriver); # eg 'mysql' or 'postgres'<br> $db-&gt;debug = true;<br> $db-&gt;<a href="#connect">Connect</a>($server, $user, $password, $database);<br> $rs = $db-&gt;<a href="#execute">Execute</a>('select * from some_small_table');<br> print "&lt;pre&gt;";<br> print_r($rs-&gt;<a href="#getrows">GetRows</a>());<br> print "&lt;/pre&gt;";<br>?&gt;</pre>
209
210 <h3>Minimum Install<a name="mininstall"></a></h3>
211 <p>For developers who want to release a minimal install of ADOdb, you will need:
212 </p><ul>
213 <li>adodb.inc.php
214 </li><li>adodb-lib.inc.php
215 </li><li>adodb-time.inc.php
216 </li><li>drivers/adodb-$database.inc.php
217 </li><li>license.txt (for legal reasons)
218 </li><li>adodb-php4.inc.php
219 </li><li>adodb-iterator.inc.php (php5 functionality)
220 </li></ul>
221 Optional:
222 <ul>
223 <li>adodb-error.inc.php and lang/adodb-$lang.inc.php (if you use MetaError())
224 </li><li>adodb-csvlib.inc.php (if you use cached recordsets - CacheExecute(), etc)
225 </li><li>adodb-exceptions.inc.php and adodb-errorhandler.inc.php (if you use adodb error handler or php5 exceptions).
226 <li>adodb-active-record.inc.php if you use <a href=docs-active-record.htm>Active Records</a>.
227 </li></ul>
228
229 <h3>Code Initialization Examples<a name="coding"></a></h3>
230 <p>When running ADOdb, at least two files are loaded. First is adodb/adodb.inc.php,
231 which contains all functions used by all database classes. The code specific
232 to a particular database is in the adodb/driver/adodb-????.inc.php file.</p>
233 <a name="adonewconnection"></a>
234 <p>For example, to connect to a mysql database:</p>
235 <pre>include('/path/to/set/here/adodb.inc.php');<br>$conn = &amp;ADONewConnection('mysql');<br></pre>
236 <p>Whenever you need to connect to a database, you create a Connection object
237 using the <b>ADONewConnection</b>($driver) function.
238 <b>NewADOConnection</b>($driver) is an alternative name for the same function.</p>
239
240 <p>At this point, you are not connected to the database (no longer true if you pass in a <a href="#dsnsupport">dsn</a>). You will first need to decide
241 whether to use <i>persistent</i> or <i>non-persistent</i> connections. The advantage of <i>persistent</i>
242 connections is that they are faster, as the database connection is never closed (even
243 when you call Close()). <i>Non-persistent </i>connections take up much fewer resources though,
244 reducing the risk of your database and your web-server becoming overloaded.
245 </p><p>For persistent connections,
246 use $conn-&gt;<a href="#pconnect">PConnect()</a>,
247 or $conn-&gt;<a href="#connect">Connect()</a> for non-persistent connections.
248 Some database drivers also support <a href="#nconnect">NConnect()</a>, which forces
249 the creation of a new connection.
250
251 <a name="connection_gotcha"></a>
252 </p><p><b>Connection Gotcha</b>: If you create two connections, but both use the same userid and password,
253 PHP will share the same connection. This can cause problems if the connections are meant to
254 different databases. The solution is to always use different userid's for different databases,
255 or use NConnect().
256
257 <a name="dsnsupport"></a>
258 </p><h3>Data Source Name (DSN) Support</h3>
259 <p> Since ADOdb 4.51, you can connect to a database by passing a dsn to NewADOConnection() (or ADONewConnection, which is
260 the same function). The dsn format is:
261 </p><pre> $driver://$username:$password@hostname/$database?options[=value]<br></pre><p>
262 NewADOConnection() calls Connect() or PConnect() internally for you. If the connection fails, false is returned.
263 </p><pre> <font color="#008000"># non-persistent connection</font>
264 $dsn = 'mysql://root:pwd@localhost/mydb';
265 $db = NewADOConnection($dsn);
266 if (!$db) die("Connection failed");
267
268 <font color="#008000"># no need to call connect/pconnect!</font>
269 $arr = $db-&gt;GetArray("select * from table");
270
271 <font color="#008000"># persistent connection</font>
272 $dsn2 = 'mysql://root:pwd@localhost/mydb?persist';
273 </pre>
274 <p>
275 If you have special characters such as /:? in your dsn, then you need to rawurlencode them first:
276 </p><pre> $pwd = rawurlencode($pwd);<br> $dsn = "mysql://root:$pwd@localhost/mydb";<br></pre>
277 <p>
278 Legal options are:
279 </p><p>
280 <table align="center" border="1"><tbody><tr><td>For all drivers</td><td>
281 'persist', 'persistent', 'debug', 'fetchmode', 'new'
282 </td></tr><tr><td>Interbase/Firebird
283 </td><td>
284 'dialect','charset','buffers','role'
285 </td></tr><tr><td>M'soft ADO</td><td>
286 'charpage'
287
288 </td></tr><tr><td>MySQL</td><td>
289 'clientflags'
290 </td></tr><tr><td>MySQLi</td><td>
291 'port', 'socket', 'clientflags'
292 </td></tr><tr><td>Oci8</td><td>
293 'nls_date_format','charset'
294 </td></tr></tbody></table>
295 </p><p>
296 For all drivers, when the options <i>persist</i> or <i>persistent</i> are set, a persistent connection is forced; similarly, when <i>new</i> is set, then
297 a new connection will be created using NConnect if the underlying driver supports it.
298 The <i>debug</i> option enables debugging. The <i>fetchmode</i> calls <a href="#setfetchmode">SetFetchMode()</a>.
299 If no value is defined for an option, then the value is set to 1.
300 </p><p>
301 ADOdb DSN's are compatible with version 1.0 of PEAR DB's DSN format.
302 <a name="connect_ex">
303 </a></p><h3><a name="connect_ex">Examples of Connecting to Databases</a></h3>
304 <h4><a name="connect_ex">MySQL and Most Other Database Drivers</a></h4>
305 <p><a name="connect_ex">MySQL connections are very straightforward, and the parameters are identical
306 to mysql_connect:</a></p>
307 <pre><a name="connect_ex"> $conn = &amp;ADONewConnection('mysql'); <br> $conn-&gt;PConnect('localhost','userid','password','database');<br> <br> <font color="#008000"># or dsn </font>
308 $dsn = 'mysql://user:pwd@localhost/mydb';
309 $conn = ADONewConnection($dsn); # no need for Connect()
310
311 <font color="#008000"># or persistent dsn</font>
312 $dsn = 'mysql://user:pwd@localhost/mydb?persist';
313 $conn = ADONewConnection($dsn); # no need for PConnect()
314
315 <font color="#008000"># a more complex example:</font>
316 $pwd = urlencode($pwd);
317 $flags = MYSQL_CLIENT_COMPRESS;
318 $dsn = "mysql://user:$pwd@localhost/mydb?persist&amp;clientflags=$flags";
319 $conn = ADONewConnection($dsn); # no need for PConnect()
320 </a></pre>
321 <p><a name="connect_ex"> For most drivers, you can use the standard function: Connect($server, $user, $password, $database), or
322 a </a><a href="dsnsupport">DSN</a> since ADOdb 4.51. Exceptions to this are listed below.
323 </p>
324 <a name=pdo>
325 <h4>PDO</h4>
326 <p>PDO, which only works with PHP5, accepts a driver specific connection string:
327 <pre>
328 $conn =& NewADConnection('pdo');
329 $conn->Connect('mysql:host=localhost',$user,$pwd,$mydb);
330 $conn->Connect('mysql:host=localhost;dbname=mydb',$user,$pwd);
331 $conn->Connect("mysql:host=localhost;dbname=mydb;username=$user;password=$pwd");
332 </pre>
333 <p>The DSN mechanism is also supported:
334 <pre>
335 $conn =& NewADConnection("pdo_mysql://user:pwd@localhost/mydb?persist"); # persist is optional
336 </pre>
337 <h4>PostgreSQL</h4>
338 <p>PostgreSQL 7 and 8 accepts connections using: </p>
339 <p>a. the standard connection string:</p>
340 <pre> $conn = &amp;ADONewConnection('postgres'); <br> $conn-&gt;PConnect('host=localhost port=5432 dbname=mary');</pre>
341 <p> b. the classical 4 parameters:</p>
342 <pre> $conn-&gt;PConnect('localhost','userid','password','database');<br> </pre>
343 <p>c. dsn:
344 </p><pre> $dsn = 'postgres://user:pwd@localhost/mydb?persist'; # persist is optional
345 $conn = ADONewConnection($dsn); # no need for Connect/PConnect<br></pre>
346 <a name="ldap"></a>
347
348 <h4>LDAP</h4>
349 <p>Here is an example of querying a LDAP server. Thanks to Josh Eldridge for the driver and this example:
350 </p><pre>
351 require('/path/to/adodb.inc.php');
352
353 /* Make sure to set this BEFORE calling Connect() */
354 $LDAP_CONNECT_OPTIONS = Array(
355 Array ("OPTION_NAME"=>LDAP_OPT_DEREF, "OPTION_VALUE"=>2),
356 Array ("OPTION_NAME"=>LDAP_OPT_SIZELIMIT,"OPTION_VALUE"=>100),
357 Array ("OPTION_NAME"=>LDAP_OPT_TIMELIMIT,"OPTION_VALUE"=>30),
358 Array ("OPTION_NAME"=>LDAP_OPT_PROTOCOL_VERSION,"OPTION_VALUE"=>3),
359 Array ("OPTION_NAME"=>LDAP_OPT_ERROR_NUMBER,"OPTION_VALUE"=>13),
360 Array ("OPTION_NAME"=>LDAP_OPT_REFERRALS,"OPTION_VALUE"=>FALSE),
361 Array ("OPTION_NAME"=>LDAP_OPT_RESTART,"OPTION_VALUE"=>FALSE)
362 );
363 $host = 'ldap.baylor.edu';
364 $ldapbase = 'ou=People,o=Baylor University,c=US';
365
366 $ldap = NewADOConnection( 'ldap' );
367 $ldap->Connect( $host, $user_name='', $password='', $ldapbase );
368
369 echo "&lt;pre>";
370
371 print_r( $ldap->ServerInfo() );
372 $ldap->SetFetchMode(ADODB_FETCH_ASSOC);
373 $userName = 'eldridge';
374 $filter="(|(CN=$userName*)(sn=$userName*)(givenname=$userName*)(uid=$userName*))";
375
376 $rs = $ldap->Execute( $filter );
377 if ($rs)
378 while ($arr = $rs->FetchRow()) {
379 print_r($arr);
380 }
381
382 $rs = $ldap->Execute( $filter );
383 if ($rs)
384 while (!$rs->EOF) {
385 print_r($rs->fields);
386 $rs->MoveNext();
387 }
388
389 print_r( $ldap->GetArray( $filter ) );
390 print_r( $ldap->GetRow( $filter ) );
391
392 $ldap->Close();
393 echo "&lt;/pre>";
394 </pre>
395 <p>Using DSN:
396 <pre>
397 $dsn = "ldap://ldap.baylor.edu/ou=People,o=Baylor University,c=US";
398 $db = NewADOConnection($dsn);
399 </pre>
400 <h4>Interbase/Firebird</h4>
401 You define the database in the $host parameter:
402 <pre> $conn = &amp;ADONewConnection('ibase'); <br> $conn-&gt;PConnect('localhost:c:\ibase\employee.gdb','sysdba','masterkey');<br></pre>
403 <p>Or dsn:
404 </p><pre> $dsn = 'firebird://user:pwd@localhost/mydb?persist&amp;dialect=3'; # persist is optional<br> $conn = ADONewConnection($dsn); # no need for Connect/PConnect<br></pre>
405 <h4>SQLite</h4>
406 Sqlite will create the database file if it does not exist.
407 <pre> $conn = &amp;ADONewConnection('sqlite');
408 $conn-&gt;PConnect('c:\path\to\sqlite.db'); # sqlite will create if does not exist<br></pre>
409 <p>Or dsn:
410 </p><pre> $path = urlencode('c:\path\to\sqlite.db');
411 $dsn = "sqlite://$path/?persist"; # persist is optional
412 $conn = ADONewConnection($dsn); # no need for Connect/PConnect<br></pre>
413 <h4>Oracle (oci8)</h4>
414 <p>With oci8, you can connect in multiple ways. Note that oci8 works fine with
415 newer versions of the Oracle, eg. 9i and 10g.</p>
416 <p>a. PHP and Oracle reside on the same machine, use default SID.</p>
417 <pre> $conn-&gt;Connect(false, 'scott', 'tiger');</pre>
418 <p>b. TNS Name defined in tnsnames.ora (or ONAMES or HOSTNAMES), eg. 'myTNS'</p>
419 <pre> $conn-&gt;PConnect(false, 'scott', 'tiger', 'myTNS');</pre>
420 <p>or</p>
421 <pre> $conn-&gt;PConnect('myTNS', 'scott', 'tiger');</pre>
422 <p>c. Host Address and SID</p>
423 <pre>
424 $conn->connectSID = true;
425 $conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'SID');</pre>
426 <p>d. Host Address and Service Name</p>
427 <pre> $conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'servicename');</pre>
428 <p>e. Oracle connection string:
429 </p><pre> $cstr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$host)(PORT=$port))<br> (CONNECT_DATA=(SID=$sid)))";<br> $conn-&gt;Connect($cstr, 'scott', 'tiger');<br></pre>
430 <p>f. ADOdb dsn:
431 </p><pre> $dsn = 'oci8://user:pwd@tnsname/?persist'; # persist is optional<br> $conn = ADONewConnection($dsn); # no need for Connect/PConnect<br> <br> $dsn = 'oci8://user:pwd@host/sid';<br> $conn = ADONewConnection($dsn);<br> <br> $dsn = 'oci8://user:pwd@/'; # oracle on local machine<br> $conn = ADONewConnection($dsn);<br></pre>
432 <p>You can also set the charSet for Oracle 9.2 and later, supported since PHP 4.3.2, ADOdb 4.54:
433 </p><pre> $conn-&gt;charSet = 'we8iso8859p1';<br> $conn-&gt;Connect(...);<br> <br> # or<br> $dsn = 'oci8://user:pwd@tnsname/?charset=WE8MSWIN1252';<br> $db = ADONewConnection($dsn);<br></pre>
434 <a name="dsnless"></a>
435 <h4>DSN-less ODBC ( Access, MSSQL and DB2 examples)</h4>
436 <p>ODBC DSN's can be created in the ODBC control panel, or you can use a DSN-less
437 connection.To use DSN-less connections with ODBC you need PHP 4.3 or later.
438 </p>
439 <p>For Microsoft Access:</p>
440 <pre> $db =&amp; ADONewConnection('access');<br> $dsn = <strong>"Driver={Microsoft Access Driver (*.mdb)};Dbq=d:\\northwind.mdb;Uid=Admin;Pwd=;";</strong>
441 $db-&gt;Connect($dsn);
442 </pre>
443 For Microsoft SQL Server:
444 <pre> $db =&amp; ADONewConnection('odbc_mssql');<br> $dsn = <strong>"Driver={SQL Server};Server=localhost;Database=northwind;"</strong>;<br> $db-&gt;Connect($dsn,'userid','password');<br></pre>
445 or if you prefer to use the mssql extension (which is limited to mssql 6.5 functionality):
446 <pre> $db =&amp; ADONewConnection('mssql');<br> $db-&gt;Execute('localhost', 'userid', 'password', 'northwind');<br></pre>
447 For DB2:
448 <pre>
449 $dbms = 'db2'; # or 'odbc_db2' if db2 extension not available
450 $db =&amp; ADONewConnection($dbms);
451 $dsn = "driver={IBM db2 odbc DRIVER};Database=sample;hostname=localhost;port=50000;protocol=TCPIP;".
452 "uid=root; pwd=secret";<br> $db-&gt;Connect($dsn);
453 </pre>
454 <b>DSN-less Connections with ADO</b><br>
455 If you are using versions of PHP earlier than PHP 4.3.0, DSN-less connections
456 only work with Microsoft's ADO, which is Microsoft's COM based API. An example
457 using the ADOdb library and Microsoft's ADO:
458 <pre>&lt;?php<br> include('adodb.inc.php'); <br> $db = &amp;ADONewConnection("ado_mssql");<br> print "&lt;h1&gt;Connecting DSN-less $db-&gt;databaseType...&lt;/h1&gt;";<br> <br> <b>$myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"<br> . "SERVER=flipper;DATABASE=ai;UID=sa;PWD=;" ;</b>
459 $db-&gt;Connect($myDSN);
460
461 $rs = $db-&gt;Execute("select * from table");
462 $arr = $rs-&gt;GetArray();
463 print_r($arr);
464 ?&gt;
465 </pre><a name="speed"></a>
466 <h2>High Speed ADOdb - tuning tips</h2>
467 <p>ADOdb is a big class library, yet it <a href="http://phplens.com/lens/adodb/">consistently beats</a> all other PHP class
468 libraries in performance. This is because it is designed in a layered fashion,
469 like an onion, with the fastest functions in the innermost layer. Stick to the
470 following functions for best performance:</p>
471 <table align="center" border="1" width="40%">
472 <tbody><tr>
473 <td><div align="center"><b>Innermost Layer</b></div></td>
474 </tr>
475 <tr>
476 <td><p align="center">Connect, PConnect, NConnect<br>
477 Execute, CacheExecute<br>
478 SelectLimit, CacheSelectLimit<br>
479 MoveNext, Close <br>
480 qstr, Affected_Rows, Insert_ID</p></td>
481 </tr>
482 </tbody></table>
483 <p>The fastest way to access the field data is by accessing the array $recordset-&gt;fields
484 directly. Also set the global variables <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a>
485 = ADODB_FETCH_NUM, and (for oci8, ibase/firebird and odbc) <a href="#adodb_countrecs">$ADODB_COUNTRECS</a> = false
486 before you connect to your database.</p>
487 <p>Consider using bind parameters if your database supports it, as it improves
488 query plan reuse. Use ADOdb's performance tuning system to identify bottlenecks
489 quickly. At the time of writing (Dec 2003), this means oci8 and odbc drivers.</p>
490 <p>Lastly make sure you have a PHP accelerator cache installed such as APC, Turck
491 MMCache, Zend Accelerator or ionCube.</p>
492 <p>Some examples:</p>
493 <table align="center" border="1"><tbody><tr><td><b>Fastest data retrieval using PHP</b></td><td><b>Fastest data retrieval using ADOdb extension</b></td></tr>
494 <tr><td>
495 <pre>$rs =&amp; $rs-&gt;Execute($sql);<br>while (!$rs-&gt;EOF) {<br> var_dump($rs-&gt;fields);<br> $rs-&gt;MoveNext();<br>}</pre></td><td>
496 <pre>$rs =&amp; $rs-&gt;Execute($sql);<br>$array = adodb_getall($rs);<br>var_dump($array);<br><br><br></pre></td></tr></tbody></table>
497 <p><b>Advanced Tips</b>
498 </p><p>If you have the <a href="http://adodb.sourceforge.net/#extension">ADOdb C extension</a> installed,
499 you can replace your calls to $rs-&gt;MoveNext() with adodb_movenext($rs).
500 This doubles the speed of this operation. For retrieving entire recordsets at once,
501 use GetArray(), which uses the high speed extension function adodb_getall($rs) internally.
502 </p><p>Execute() is the default way to run queries. You can use the low-level functions _Execute() and _query()
503 to reduce query overhead. Both these functions share the same parameters as Execute().
504 </p><p>If you do not have any bind parameters or your database supports
505 binding (without emulation),
506 then you can call _Execute() directly. Calling this function bypasses
507 bind emulation. Debugging is still supported in _Execute().
508 </p><p>If you do not require debugging facilities nor emulated
509 binding, and do not require a recordset to be returned, then you can
510 call _query. This is great for inserts, updates and deletes. Calling
511 this function
512 bypasses emulated binding, debugging, and recordset handling. Either
513 the resultid, true or false are returned by _query(). </p><p>For Informix, you can disable scrollable cursors with $db-&gt;cursorType = 0.
514 </p><p><a name="hack"></a> </p>
515 <h2>Hacking ADOdb Safely</h2>
516 <p>You might want to modify ADOdb for your own purposes. Luckily you can
517 still maintain backward compatibility by sub-classing ADOdb and using the $ADODB_NEWCONNECTION
518 variable. $ADODB_NEWCONNECTION allows you to override the behaviour of ADONewConnection().
519 ADOConnection() checks for this variable and will call
520 the function-name stored in this variable if it is defined.
521 </p><p>In the following example, new functionality for the connection object
522 is placed in the <i>hack_mysql</i> and <i>hack_postgres7</i> classes. The recordset class naming convention
523 can be controlled using $rsPrefix. Here we set it to 'hack_rs_', which will make ADOdb use
524 <i>hack_rs_mysql</i> and <i>hack_rs_postgres7</i> as the recordset classes.
525
526
527 </p><pre>class hack_mysql extends adodb_mysql {<br>var $rsPrefix = 'hack_rs_';<br> /* Your mods here */<br>}<br><br>class hack_rs_mysql extends ADORecordSet_mysql {<br> /* Your mods here */<br>}<br><br>class hack_postgres7 extends adodb_postgres7 {<br>var $rsPrefix = 'hack_rs_';<br> /* Your mods here */<br>}<br><br>class hack_rs_postgres7 extends ADORecordSet_postgres7 {<br> /* Your mods here */<br>}<br><br>$ADODB_NEWCONNECTION = 'hack_factory';<br><br>function&amp; hack_factory($driver)<br>{<br> if ($driver !== 'mysql' &amp;&amp; $driver !== 'postgres7') return false;<br> <br> $driver = 'hack_'.$driver;<br> $obj = new $driver();<br> return $obj;<br>}<br><br>include_once('adodb.inc.php');<br></pre>
528 <p></p><p>Don't forget to call the constructor of the parent class in
529 your constructor. If you want to use the default ADOdb drivers return
530 false in the above hack_factory() function.
531 <a name="php5"></a>
532 </p><h2>PHP5 Features</h2>
533 ADOdb 4.02 or later will transparently determine which version of PHP you are using.
534 If PHP5 is detected, the following features become available:
535 <ul>
536
537 <li><b>PDO</b>: PDO drivers are available. See the <a href=#pdo>connection examples</a>. Currently PDO drivers are
538 not as powerful as native drivers, and should be treated as experimental.<br><br>
539 <a name="php5iterators"></a>
540 <li><b>Foreach iterators</b>: This is a very natural way of going through a recordset:
541 <pre> $ADODB_FETCH_MODE = ADODB_FETCH_NUM;<br> $rs = $db-&gt;Execute($sql);<br> foreach($rs as $k =&gt; $row) {<br> echo "r1=".$row[0]." r2=".$row[1]."&lt;br&gt;";<br> }<br></pre>
542 <p>
543 <a name="php5exceptions"></a>
544 </p></li><li><b>Exceptions</b>: Just include <i>adodb-exceptions.inc.php</i> and you can now
545 catch exceptions on errors as they occur.
546 <pre> <b>include("../adodb-exceptions.inc.php");</b> <br> include("../adodb.inc.php"); <br> try { <br> $db = NewADOConnection("oci8"); <br> $db-&gt;Connect('','scott','bad-password'); <br> } catch (exception $e) { <br> var_dump($e); <br> adodb_backtrace($e-&gt;gettrace());<br> } <br></pre>
547 <p>Note that reaching EOF is <b>not</b> considered an error nor an exception.
548 </p></li></ul>
549 <h3><a name="drivers"></a>Databases Supported</h3>
550 The <i>name</i> below is the value you pass to NewADOConnection($name) to create a connection object for that database.
551 <p>
552 </p><p>
553 </p><table border="1" width="100%">
554 <tbody><tr valign="top">
555 <td><b>Name</b></td>
556 <td><b>Tested</b></td>
557 <td><b>Database</b></td>
558 <td><b><font size="2">RecordCount() usable</font></b></td>
559 <td><b>Prerequisites</b></td>
560 <td><b>Operating Systems</b></td>
561 </tr>
562 <tr valign="top">
563 <td><b><font size="2">access</font></b></td>
564 <td><font size="2">B</font></td>
565 <td><font size="2">Microsoft Access/Jet. You need to create an ODBC DSN.</font></td>
566 <td><font size="2">Y/N</font></td>
567 <td><font size="2">ODBC </font></td>
568 <td><font size="2">Windows only</font></td>
569 </tr>
570 <tr valign="top">
571 <td><b><font size="2">ado</font></b></td>
572 <td><font size="2">B</font></td>
573 <td><p><font size="2">Generic ADO, not tuned for specific databases. Allows
574 DSN-less connections. For best performance, use an OLEDB provider. This
575 is the base class for all ado drivers.</font></p>
576 <p><font size="2">You can set $db-&gt;codePage before connecting.</font></p></td>
577 <td><font size="2">? depends on database</font></td>
578 <td><font size="2">ADO or OLEDB provider</font></td>
579 <td><font size="2">Windows only</font></td>
580 </tr>
581 <tr valign="top">
582 <td><b><font size="2">ado_access</font></b></td>
583 <td><font size="2">B</font></td>
584 <td><font size="2">Microsoft Access/Jet using ADO. Allows DSN-less connections.
585 For best performance, use an OLEDB provider.</font></td>
586 <td><font size="2">Y/N</font></td>
587 <td><font size="2">ADO or OLEDB provider</font></td>
588 <td><font size="2">Windows only</font></td>
589 </tr>
590 <tr valign="top">
591 <td><b><font size="2">ado_mssql</font></b></td>
592 <td><font size="2">B</font></td>
593 <td><font size="2">Microsoft SQL Server using ADO. Allows DSN-less connections.
594 For best performance, use an OLEDB provider.</font></td>
595 <td><font size="2">Y/N</font></td>
596 <td><font size="2">ADO or OLEDB provider</font></td>
597 <td><font size="2">Windows only</font></td>
598 </tr>
599 <tr valign="top">
600 <td height="54"><b><font size="2">db2</font></b></td>
601 <td height="54"><font size="2">C</font></td>
602 <td height="54"><font size="2">Uses PHP's db2-specific extension for better performance.</font></td>
603 <td height="54"><font size="2">Y/N</font></td>
604 <td height="54"><font size="2">DB2 CLI/ODBC interface</font></td>
605 <td height="54"> <p><font size="2">Unix and Windows. Requires IBM DB2 Universal Database client.</font></p></td>
606 </tr>
607 <tr valign="top">
608 <td height="54"><b><font size="2">odbc_db2</font></b></td>
609 <td height="54"><font size="2">C</font></td>
610 <td height="54"><font size="2">Connects to DB2 using generic ODBC extension.</font></td>
611 <td height="54"><font size="2">Y/N</font></td>
612 <td height="54"><font size="2">DB2 CLI/ODBC interface</font></td>
613 <td height="54"> <p><font size="2">Unix and Windows. <a href="http://www.faqts.com/knowledge_base/view.phtml/aid/6283/fid/14">Unix
614 install hints</a>. I have had reports that the $host and $database params have to be reversed in Connect() when using the CLI interface.</font></p></td>
615 </tr>
616 <tr valign="top">
617 <td><b><font size="2">vfp</font></b></td>
618 <td><font size="2">A</font></td>
619 <td><font size="2">Microsoft Visual FoxPro. You need to create an ODBC DSN.</font></td>
620 <td><font size="2">Y/N</font></td>
621 <td><font size="2">ODBC</font></td>
622 <td><font size="2">Windows only</font></td>
623 </tr>
624 <tr valign="top">
625 <td><b><font size="2">fbsql</font></b></td>
626 <td><font size="2">C</font></td>
627 <td><font size="2">FrontBase. </font></td>
628 <td><font size="2">Y</font></td>
629 <td><font size="2">?</font></td>
630 <td> <p><font size="2">Unix and Windows</font></p></td>
631 </tr>
632 <tr valign="top">
633 <td><b><font size="2">ibase</font></b></td>
634 <td><font size="2">B</font></td>
635 <td><font size="2">Interbase 6 or earlier. Some users report you might need
636 to use this<br>
637 $db-&gt;PConnect('localhost:c:/ibase/employee.gdb', "sysdba", "masterkey")
638 to connect. Lacks Affected_Rows currently.<br>
639 <br>
640 You can set $db-&gt;role, $db-&gt;dialect, $db-&gt;buffers and $db-&gt;charSet before connecting.</font></td>
641 <td><font size="2">Y/N</font></td>
642 <td><font size="2">Interbase client</font></td>
643 <td><font size="2">Unix and Windows</font></td>
644 </tr>
645 <tr valign="top">
646 <td><b><i><font size="2">firebird</font></i></b></td>
647 <td><font size="2">C</font></td>
648 <td><font size="2">Firebird version of interbase.</font></td>
649 <td><font size="2">Y/N</font></td>
650 <td><font size="2">Interbase client</font></td>
651 <td><font size="2">Unix and Windows</font></td>
652 </tr>
653 <tr valign="top">
654 <td><b><i><font size="2">borland_ibase</font></i></b></td>
655 <td><font size="2">C</font></td>
656 <td><font size="2">Borland version of Interbase 6.5 or later. Very sad that
657 the forks differ.</font></td>
658 <td><font size="2">Y/N</font></td>
659 <td><font size="2">Interbase client</font></td>
660 <td><font size="2">Unix and Windows</font></td>
661 </tr>
662
663 <tr valign="top">
664 <td><b><font size="2">informix</font></b></td>
665 <td><font size="2">C</font></td>
666 <td><font size="2">Generic informix driver. Use this if you are using Informix 7.3 or later.</font></td>
667 <td><font size="2">Y/N</font></td>
668 <td><font size="2">Informix client</font></td>
669 <td><font size="2">Unix and Windows</font></td>
670 </tr>
671 <tr valign="top">
672 <td><b><font size="2">informix72</font></b></td>
673 <td><font size="2">C</font></td>
674 <td><font size="2"> Informix databases before Informix 7.3 that do no support
675 SELECT FIRST.</font></td>
676 <td><font size="2">Y/N</font></td>
677 <td><font size="2">Informix client</font></td>
678 <td><font size="2">Unix and Windows</font></td>
679 </tr>
680 <tr valign="top">
681 <td><b><font size="2">ldap</font></b></td>
682 <td><font size="2">C</font></td>
683 <td><font size="2">LDAP driver. See this example for usage information.</font></td>
684 <td>&nbsp;</td>
685 <td><font size="2">LDAP extension</font></td>
686 <td><font size="2">?</font></td>
687 </tr>
688 <tr valign="top">
689 <td height="73"><b><font size="2">mssql</font></b></td>
690 <td height="73"><font size="2">A</font></td>
691 <td height="73"> <p><font size="2">Microsoft SQL Server 7 and later. Works
692 with Microsoft SQL Server 2000 also. Note that date formating is problematic
693 with this driver. For example, the PHP mssql extension does not return
694 the seconds for datetime!</font></p></td>
695 <td height="73"><font size="2">Y/N</font></td>
696 <td height="73"><font size="2">Mssql client</font></td>
697 <td height="73"> <p><font size="2">Unix and Windows. <br>
698 <a href="http://phpbuilder.com/columns/alberto20000919.php3">Unix install
699 howto</a> and <a href="http://linuxjournal.com/article.php?sid=6636&amp;mode=thread&amp;order=0">another
700 one</a>. </font></p></td>
701 </tr>
702 <tr valign="top">
703 <td height="73"><b><font size="2">mssqlpo</font></b></td>
704 <td height="73"><font size="2">A</font></td>
705 <td height="73"> <p><font size="2">Portable mssql driver. Identical to above
706 mssql driver, except that '||', the concatenation operator, is converted
707 to '+'. Useful for porting scripts from most other sql variants that use
708 ||.</font></p></td>
709 <td height="73"><font size="2">Y/N</font></td>
710 <td height="73"><font size="2">Mssql client</font></td>
711 <td height="73"> <p><font size="2">Unix and Windows. <a href="http://phpbuilder.com/columns/alberto20000919.php3"><br>
712 Unix install howto</a>.</font></p></td>
713 </tr>
714 <tr valign="top">
715 <td><b><font size="2">mysql</font></b></td>
716 <td><font size="2">A</font></td>
717 <td><font size="2">MySQL without transaction support. You can also set $db-&gt;clientFlags
718 before connecting.</font></td>
719 <td><font size="2">Y</font></td>
720 <td><font size="2">MySQL client</font></td>
721 <td><font size="2">Unix and Windows</font></td>
722 </tr>
723 <tr valign="top">
724 <td><font size="2"><b>mysqlt</b> or <b>maxsql</b></font></td>
725 <td><font size="2">A</font></td>
726 <td> <p><font size="2">MySQL with transaction support. We recommend using
727 || as the concat operator for best portability. This can be done by running
728 MySQL using: <br>
729 <i>mysqld --ansi</i> or <i>mysqld --sql-mode=PIPES_AS_CONCAT</i></font></p></td>
730 <td><font size="2">Y/N</font></td>
731 <td><font size="2">MySQL client</font></td>
732 <td><font size="2">Unix and Windows</font></td>
733 </tr>
734 <tr valign="top">
735 <td><b><font size="2">oci8</font></b></td>
736 <td><font size="2">A</font></td>
737 <td><font size="2">Oracle 8/9. Has more functionality than <i>oracle</i> driver
738 (eg. Affected_Rows). You might have to putenv('ORACLE_HOME=...') before
739 Connect/PConnect. </font> <p><font size="2"> There are 2 ways of connecting
740 - with server IP and service name: <br>
741 <i>PConnect('serverip:1521','scott','tiger','service'</i>)<br>
742 or using an entry in TNSNAMES.ORA or ONAMES or HOSTNAMES: <br>
743 <i>PConnect(false, 'scott', 'tiger', $oraname)</i>. </font>
744 </p><p><font size="2">Since 2.31, we support Oracle REF cursor variables directly
745 (see <a href="#executecursor">ExecuteCursor</a>).</font> </p></td>
746 <td><font size="2">Y/N</font></td>
747 <td><font size="2">Oracle client</font></td>
748 <td><font size="2">Unix and Windows</font></td>
749 </tr>
750 <tr valign="top">
751 <td><b><font size="2">oci805</font></b></td>
752 <td><font size="2">C</font></td>
753 <td><font size="2">Supports reduced Oracle functionality for Oracle 8.0.5.
754 SelectLimit is not as efficient as in the oci8 or oci8po drivers.</font></td>
755 <td><font size="2">Y/N</font></td>
756 <td><font size="2">Oracle client</font></td>
757 <td><font size="2">Unix and Windows</font></td>
758 </tr>
759 <tr valign="top">
760 <td><b><font size="2">oci8po</font></b></td>
761 <td><font size="2">A</font></td>
762 <td><font size="2">Oracle 8/9 portable driver. This is nearly identical with
763 the oci8 driver except (a) bind variables in Prepare() use the ? convention,
764 instead of :bindvar, (b) field names use the more common PHP convention
765 of lowercase names. </font> <p><font size="2">Use this driver if porting
766 from other databases is important. Otherwise the oci8 driver offers better
767 performance. </font> </p></td>
768 <td><font size="2">Y/N</font></td>
769 <td><font size="2">Oracle client</font></td>
770 <td><font size="2">Unix and Windows</font></td>
771 </tr>
772 <tr valign="top">
773 <td><b><font size="2">odbc</font></b></td>
774 <td><font size="2">A</font></td>
775 <td><font size="2">Generic ODBC, not tuned for specific databases. To connect,
776 use <br>
777 PConnect('DSN','user','pwd'). This is the base class for all odbc derived
778 drivers.</font></td>
779 <td><font size="2">? depends on database</font></td>
780 <td><font size="2">ODBC</font></td>
781 <td><font size="2">Unix and Windows. <a href="http://phpbuilder.com/columns/alberto20000919.php3?page=4">Unix
782 hints.</a></font></td>
783 </tr>
784 <tr valign="top">
785 <td><b><font size="2">odbc_mssql</font></b></td>
786 <td><font size="2">C</font></td>
787 <td><font size="2">Uses ODBC to connect to MSSQL</font></td>
788 <td><font size="2">Y/N</font></td>
789 <td><font size="2">ODBC</font></td>
790 <td><font size="2">Unix and Windows. </font></td>
791 </tr>
792 <tr valign="top">
793 <td><b><font size="2">odbc_oracle</font></b></td>
794 <td><font size="2">C</font></td>
795 <td><font size="2">Uses ODBC to connect to Oracle</font></td>
796 <td><font size="2">Y/N</font></td>
797 <td><font size="2">ODBC</font></td>
798 <td><font size="2">Unix and Windows. </font></td>
799 </tr>
800
801 <tr valign="top">
802 <td><b><font size="2">odbtp</font></b></td>
803 <td><font size="2">C</font></td>
804 <td><font size="2">Generic odbtp driver. <a href="http://odbtp.sourceforge.net/">Odbtp</a> is a software for
805 accessing Windows ODBC data sources from other operating systems.</font></td>
806 <td><font size="2">Y/N</font></td>
807 <td><font size="2">odbtp</font></td>
808 <td><font size="2">Unix and Windows</font></td>
809 </tr>
810 <tr valign="top">
811 <td><b><font size="2">odbtp_unicode</font></b></td>
812 <td><font size="2">C</font></td>
813 <td><font size="2">Odtbp with unicode support</font></td>
814 <td><font size="2">Y/N</font></td>
815 <td><font size="2">odbtp</font></td>
816 <td><font size="2">Unix and Windows</font></td>
817 </tr>
818 <tr valign="top">
819 <td height="34"><b><font size="2">oracle</font></b></td>
820 <td height="34"><font size="2">C</font></td>
821 <td height="34"><font size="2">Implements old Oracle 7 client API. Use oci8
822 driver if possible for better performance.</font></td>
823 <td height="34"><font size="2">Y/N</font></td>
824 <td height="34"><font size="2">Oracle client</font></td>
825 <td height="34"><font size="2">Unix and Windows</font></td>
826 </tr>
827 <tr valign="top">
828 <td height="34"><b><font size="2">netezza</font></b></td>
829 <td height="34"><font size="2">C</font></td>
830 <td height="34"><font size="2">Netezza driver. Netezza is based on postgres code-base.</font></td>
831 <td height="34"><font size="2">Y</font></td>
832 <td height="34"><font size="2">?</font></td>
833 <td height="34"><font size="2">?</font></td>
834 </tr>
835 <tr valign="top">
836 <td><b><font size="2">pdo</font></b></td>
837 <td><font size="2">C</font></td>
838 <td><font size="2">Generic PDO driver for PHP5. </font></td>
839 <td><font size="2">Y</font></td>
840 <td><font size="2">PDO extension and database specific drivers</font></td>
841 <td><font size="2">Unix and Windows. </font></td>
842 </tr>
843 <tr valign="top">
844 <td><b><font size="2">postgres</font></b></td>
845 <td><font size="2">A</font></td>
846 <td><font size="2">Generic PostgreSQL driver. Currently identical to postgres7
847 driver.</font></td>
848 <td><font size="2">Y</font></td>
849 <td><font size="2">PostgreSQL client</font></td>
850 <td><font size="2">Unix and Windows. </font></td>
851 </tr>
852 <tr valign="top">
853 <td><b><font size="2">postgres64</font></b></td>
854 <td><font size="2">A</font></td>
855 <td><font size="2">For PostgreSQL 6.4 and earlier which does not support LIMIT
856 internally.</font></td>
857 <td><font size="2">Y</font></td>
858 <td><font size="2">PostgreSQL client</font></td>
859 <td><font size="2">Unix and Windows. </font></td>
860 </tr>
861 <tr valign="top">
862 <td><b><font size="2">postgres7</font></b></td>
863 <td><font size="2">A</font></td>
864 <td><font size="2">PostgreSQL which supports LIMIT and other version 7 functionality.</font></td>
865 <td><font size="2">Y</font></td>
866 <td><font size="2">PostgreSQL client</font></td>
867 <td><font size="2">Unix and Windows. </font></td>
868 </tr>
869 <tr valign="top">
870 <td><b><font size="2">postgres8</font></b></td>
871 <td><font size="2">A</font></td>
872 <td><font size="2">PostgreSQL which supports version 8 functionality.</font></td>
873 <td><font size="2">Y</font></td>
874 <td><font size="2">PostgreSQL client</font></td>
875 <td><font size="2">Unix and Windows. </font></td>
876 </tr>
877 <tr valign="top">
878 <td><b><font size="2">sapdb</font></b></td>
879 <td><font size="2">C</font></td>
880 <td><font size="2">SAP DB. Should work reliably as based on ODBC driver.</font></td>
881 <td><font size="2">Y/N</font></td>
882 <td><font size="2">SAP ODBC client</font></td>
883 <td> <p><font size="2">?</font></p></td>
884 </tr>
885 <tr valign="top">
886 <td><b><font size="2">sqlanywhere</font></b></td>
887 <td><font size="2">C</font></td>
888 <td><font size="2">Sybase SQL Anywhere. Should work reliably as based on ODBC
889 driver.</font></td>
890 <td><font size="2">Y/N</font></td>
891 <td><font size="2">SQL Anywhere ODBC client</font></td>
892 <td> <p><font size="2">?</font></p></td>
893 </tr>
894 <tr valign="top">
895 <td height="54"><b><font size="2">sqlite</font></b></td>
896 <td height="54"><font size="2">B</font></td>
897 <td height="54"><font size="2">SQLite.</font></td>
898 <td height="54"><font size="2">Y</font></td>
899 <td height="54"><font size="2">-</font></td>
900 <td height="54"> <p><font size="2">Unix and Windows.</font></p></td>
901 </tr>
902 <tr valign="top">
903 <td height="54"><b><font size="2">sqlitepo</font></b></td>
904 <td height="54"><font size="2">B</font></td>
905 <td height="54"><font size="2">Portable SQLite driver. This is because assoc mode does not work like other drivers in sqlite.
906 Namely, when selecting (joining) multiple tables, the table
907 names are included in the assoc keys in the "sqlite" driver.</font><p>
908 <font size="2"> In "sqlitepo" driver, the table names are stripped from the returned column names.
909 When this results in a conflict, the first field get preference.
910 </font></p></td>
911 <td height="54"><font size="2">Y</font></td>
912 <td height="54"><font size="2">-</font></td>
913 <td height="54"> <p><font size="2">Unix and Windows.</font></p></td>
914 </tr>
915
916
917 <tr valign="top">
918 <td><b><font size="2">sybase</font></b></td>
919 <td><font size="2">C</font></td>
920 <td><font size="2">Sybase. </font></td>
921 <td><font size="2">Y/N</font></td>
922 <td><font size="2">Sybase client</font></td>
923 <td> <p><font size="2">Unix and Windows.</font></p></td>
924 </tr>
925
926 <tr valign="top">
927 <td><b><font size="2">sybase_ase</font></b></td>
928 <td><font size="2">C</font></td>
929 <td><font size="2">Sybase ASE. </font></td>
930 <td><font size="2">Y/N</font></td>
931 <td><font size="2">Sybase client</font></td>
932 <td> <p><font size="2">Unix and Windows.</font></p></td>
933 </tr>
934 </tbody></table>
935
936 <p></p><p>The "Tested" column indicates how extensively the code has been tested
937 and used. <br>
938 A = well tested and used by many people<br>
939 B = tested and usable, but some features might not be implemented<br>
940 C = user contributed or experimental driver. Might not fully support all of
941 the latest features of ADOdb. </p>
942 <p>The column "RecordCount() usable" indicates whether RecordCount()
943 return the number of rows, or returns -1 when a SELECT statement is executed.
944 If this column displays Y/N then the RecordCount() is emulated when the global
945 variable $ADODB_COUNTRECS=true (this is the default). Note that for large recordsets,
946 it might be better to disable RecordCount() emulation because substantial amounts
947 of memory are required to cache the recordset for counting. Also there is a
948 speed penalty of 40-50% if emulation is required. This is emulated in most databases
949 except for PostgreSQL and MySQL. This variable is checked every time a query
950 is executed, so you can selectively choose which recordsets to count.</p>
951 <p>
952 </p><hr />
953 <h1>Tutorials<a name="quickstart"></a></h1>
954 <h3>Example 1: Select Statement<a name="ex1"></a></h3>
955 <p>Task: Connect to the Access Northwind DSN, display the first 2 columns of each
956 row.</p>
957 <p>In this example, we create a ADOConnection object, which represents the connection
958 to the database. The connection is initiated with <a href="#pconnect"><font face="Courier New, Courier, mono">PConnect</font></a>,
959 which is a persistent connection. Whenever we want to query the database, we
960 call the <font face="Courier New, Courier, mono">ADOConnection.<a href="#execute">Execute</a>()</font>
961 function. This returns an ADORecordSet object which is actually a cursor that
962 holds the current row in the array <font face="Courier New, Courier, mono">fields[]</font>.
963 We use <font face="Courier New, Courier, mono"><a href="#movenext">MoveNext</a>()</font>
964 to move from row to row.</p>
965 <p>NB: A useful function that is not used in this example is <font face="Courier New, Courier, mono"><a href="#selectlimit">SelectLimit</a></font>,
966 which allows us to limit the number of rows shown.
967 </p><pre>&lt;?<br><font face="Courier New, Courier, mono"><b>include</b>('adodb.inc.php'); # load code common to ADOdb<br>$<font color="#660000">conn</font> = &amp;ADONewConnection('access'); # create a connection<br>$<font color="#660000">conn</font>-&gt;PConnect('northwind'); # connect to MS-Access, northwind DSN<br>$<font color="#660000">recordSet</font> = &amp;$<font color="#660000">conn</font>-&gt;Execute('select * from products');<br>if (!$<font color="#660000">recordSet</font>) <br> print $<font color="#660000">conn</font>-&gt;ErrorMsg();<br>else<br><b>while</b> (!$<font color="#660000">recordSet</font>-&gt;EOF) {<br> <b>print</b> $<font color="#660000">recordSet</font>-&gt;fields[0].' '.$<font color="#660000">recordSet</font>-&gt;fields[1].'&lt;BR&gt;';<br> $<font color="#660000">recordSet</font>-&gt;MoveNext();<br>}</font><font face="Courier New, Courier, mono">
968
969 $<font color="#660000">recordSet</font>-&gt;Close(); # optional<br>$<font color="#660000">conn</font>-&gt;Close(); # optional<br></font>
970 ?&gt;
971 </pre>
972 <p>The $<font face="Courier New, Courier, mono">recordSet</font> returned stores
973 the current row in the <font face="Courier New, Courier, mono">$recordSet-&gt;fields</font>
974 array, indexed by column number (starting from zero). We use the <font face="Courier New, Courier, mono"><a href="#movenext">MoveNext</a>()</font>
975 function to move to the next row. The <font face="Courier New, Courier, mono">EOF</font>
976 property is set to true when end-of-file is reached. If an error occurs in Execute(),
977 we return false instead of a recordset.</p>
978 <p>The <code>$recordSet-&gt;fields[]</code> array is generated by the PHP database
979 extension. Some database extensions only index by number and do not index the
980 array by field name. To force indexing by name - that is associative arrays
981 - use the SetFetchMode function. Each recordset saves and uses whatever fetch
982 mode was set when the recordset was created in Execute() or SelectLimit().
983 </p><pre> $db-&gt;SetFetchMode(ADODB_FETCH_NUM);<br> $rs1 = $db-&gt;Execute('select * from table');<br> $db-&gt;SetFetchMode(ADODB_FETCH_ASSOC);<br> $rs2 = $db-&gt;Execute('select * from table');<br> print_r($rs1-&gt;fields); # shows <i>array([0]=&gt;'v0',[1] =&gt;'v1')</i>
984 print_r($rs2-&gt;fields); # shows <i>array(['col1']=&gt;'v0',['col2'] =&gt;'v1')</i>
985 </pre>
986 <p> </p>
987 <p>To get the number of rows in the select statement, you can use <font face="Courier New, Courier, mono">$recordSet-&gt;<a href="#recordcount">RecordCount</a>()</font>.
988 Note that it can return -1 if the number of rows returned cannot be determined.</p>
989 <h3>Example 2: Advanced Select with Field Objects<a name="ex2"></a></h3>
990 <p>Select a table, display the first two columns. If the second column is a date
991 or timestamp, reformat the date to US format.</p>
992 <pre>&lt;?<br><font face="Courier New, Courier, mono"><b>include</b>('adodb.inc.php'); # load code common to ADOdb<br>$<font color="#660000">conn</font> = &amp;ADONewConnection('access'); # create a connection<br>$<font color="#660000">conn</font>-&gt;PConnect('northwind'); # connect to MS-Access, northwind dsn<br>$<font color="#660000">recordSet</font> = &amp;$<font color="#660000">conn</font>-&gt;Execute('select CustomerID,OrderDate from Orders');<br>if (!$<font color="#660000">recordSet</font>) <br> print $<font color="#660000">conn</font>-&gt;ErrorMsg();<br>else<br><b>while</b> (!$<font color="#660000">recordSet</font>-&gt;EOF) {<br> $<font color="#660000">fld</font> = <font color="#336600"><b>$</b><font color="#660000">recordSet</font><b>-&gt;FetchField</b></font><font color="#006600">(</font>1<font color="#006600">);</font>
993 $<font color="#660000">type</font> = <font color="#336600"><b>$</b><font color="#660000">recordSet</font><b>-&gt;MetaType</b></font>($fld-&gt;type);<br><br> <b>if</b> ( $<font color="#660000">type</font> == 'D' || $<font color="#660000">type</font> == 'T') <br> <b>print</b> $<font color="#660000">recordSet</font>-&gt;fields[0].' '.<br> <b><font color="#336600">$</font></b><font color="#660000">recordSet</font><b><font color="#336600">-&gt;UserDate</font></b>($<font color="#660000">recordSet</font>-&gt;fields[1],'<b>m/d/Y</b>').'&lt;BR&gt;';<br> <b>else </b>
994 <b>print</b> $<font color="#660000">recordSet</font>-&gt;fields[0].' '.$<font color="#660000">recordSet</font>-&gt;fields[1].'&lt;BR&gt;';<br><br> $<font color="#660000">recordSet</font>-&gt;MoveNext();<br>}</font><font face="Courier New, Courier, mono">
995 $<font color="#660000">recordSet</font>-&gt;Close(); # optional<br>$<font color="#660000">conn</font>-&gt;Close(); # optional<br></font>
996 ?&gt;
997 </pre>
998 <p>In this example, we check the field type of the second column using <font face="Courier New, Courier, mono"><a href="#fetchfield">FetchField</a>().</font>
999 This returns an object with at least 3 fields.</p>
1000 <ul>
1001 <li><b>name</b>: name of column</li>
1002 <li> <b>type</b>: native field type of column</li>
1003 <li> <b>max_length</b>: maximum length of field. Some databases such as MySQL
1004 do not return the maximum length of the field correctly. In these cases max_length
1005 will be set to -1.</li>
1006 </ul>
1007 <p>We then use <font face="Courier New, Courier, mono"><a href="#metatype">MetaType</a>()</font>
1008 to translate the native type to a <i>generic</i> type. Currently the following
1009 <i>generic</i> types are defined:</p>
1010 <ul>
1011 <li><b>C</b>: character fields that should be shown in a &lt;input type="text"&gt;
1012 tag.</li>
1013 <li><b>X</b>: TeXt, large text fields that should be shown in a &lt;textarea&gt;</li>
1014 <li><b>B</b>: Blobs, or Binary Large Objects. Typically images.
1015 </li><li><b>D</b>: Date field</li>
1016 <li><b>T</b>: Timestamp field</li>
1017 <li><b>L</b>: Logical field (boolean or bit-field)</li>
1018 <li><b>I</b>:&nbsp; Integer field</li>
1019 <li><b>N</b>: Numeric field. Includes autoincrement, numeric, floating point,
1020 real and integer. </li>
1021 <li><b>R</b>: Serial field. Includes serial, autoincrement integers. This works
1022 for selected databases. </li>
1023 </ul>
1024 <p>If the metatype is of type date or timestamp, then we print it using the user
1025 defined date format with <font face="Courier New, Courier, mono"><a href="#userdate">UserDate</a>(),</font>
1026 which converts the PHP SQL date string format to a user defined one. Another
1027 use for <font face="Courier New, Courier, mono"><a href="#metatype">MetaType</a>()</font>
1028 is data validation before doing an SQL insert or update.</p>
1029 <h3>Example 3: Inserting<a name="ex3"></a></h3>
1030 <p>Insert a row to the Orders table containing dates and strings that need to
1031 be quoted before they can be accepted by the database, eg: the single-quote
1032 in the word <i>John's</i>.</p>
1033 <pre>&lt;?<br><b>include</b>('adodb.inc.php'); # load code common to ADOdb<br>$<font color="#660000">conn</font> = &amp;ADONewConnection('access'); # create a connection<br><br>$<font color="#660000">conn</font>-&gt;PConnect('northwind'); # connect to MS-Access, northwind dsn<br>$<font color="#660000">shipto</font> = <font color="#006600"><b>$conn-&gt;qstr</b></font>("<i>John's Old Shoppe</i>");<br><br>$<font color="#660000">sql</font> = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";<br>$<font color="#660000">sql</font> .= "values ('ANATR',2,".<b><font color="#006600">$conn-&gt;DBDate(</font>time()<font color="#006600">)</font></b><font color="#006600">.</font>",$<font color="#660000">shipto</font>)";<br><br><b>if</b> ($<font color="#660000">conn</font>-&gt;Execute($<font color="#660000">sql</font>) <font color="#336600"><b>=== false</b></font>) {<br> <b>print</b> 'error inserting: '.<font color="#336600"><b>$conn-&gt;ErrorMsg()</b></font>.'&lt;BR&gt;';<br>}<br>?&gt;<br></pre>
1034 <p>In this example, we see the advanced date and quote handling facilities of
1035 ADOdb. The unix timestamp (which is a long integer) is appropriately formated
1036 for Access with <font face="Courier New, Courier, mono"><a href="#dbdate">DBDate</a>()</font>,
1037 and the right escape character is used for quoting the <i>John's Old Shoppe</i>,
1038 which is<b> </b><i>John'<b>'</b>s Old Shoppe</i> and not PHP's default <i>John<b>'</b>s
1039 Old Shoppe</i> with <font face="Courier New, Courier, mono"><a href="#qstr">qstr</a>()</font>.
1040 </p>
1041 <p>Observe the error-handling of the Execute statement. False is returned by<font face="Courier New, Courier, mono">
1042 <a href="#execute">Execute</a>() </font>if an error occured. The error message
1043 for the last error that occurred is displayed in <font face="Courier New, Courier, mono"><a href="#errormsg">ErrorMsg</a>()</font>.
1044 Note: <i>php_track_errors</i> might have to be enabled for error messages to
1045 be saved.</p>
1046 <h3> Example 4: Debugging<a name="ex4"></a></h3>
1047 <pre>&lt;?<br><b>include</b>('adodb.inc.php'); # load code common to ADOdb<br>$<font color="#663300">conn</font> = &amp;ADONewConnection('access'); # create a connection<br>$<font color="#663300">conn</font>-&gt;PConnect('northwind'); # connect to MS-Access, northwind dsn<br><font>$<font color="#663300">shipto</font> = <b>$conn-&gt;qstr</b>("John's Old Shoppe");<br>$<font color="#663300">sql</font> = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";<br>$<font color="#663300">sql</font> .= "values ('ANATR',2,".$<font color="#663300">conn</font>-&gt;FormatDate(time()).",$shipto)";<br><b><font color="#336600">$<font color="#663300">conn</font>-&gt;debug = true;</font></b>
1048 <b>if</b> ($<font color="#663300">conn</font>-&gt;Execute($sql) <b>=== false</b>) <b>print</b> 'error inserting';</font>
1049 ?&gt;
1050 </pre>
1051 <p>In the above example, we have turned on debugging by setting <b>debug = true</b>.
1052 This will display the SQL statement before execution, and also show any error
1053 messages. There is no need to call <font face="Courier New, Courier, mono"><a href="#errormsg">ErrorMsg</a>()</font>
1054 in this case. For displaying the recordset, see the <font face="Courier New, Courier, mono"><a href="#exrs2html">rs2html</a>()
1055 </font>example.</p>
1056 <p>Also see the section on <a href="#errorhandling">Custom Error Handlers</a>.</p>
1057 <h3>Example 5: MySQL and Menus<a name="ex5"></a></h3>
1058 <p>Connect to MySQL database <i>agora</i>, and generate a &lt;select&gt; menu
1059 from an SQL statement where the &lt;option&gt; captions are in the 1st column,
1060 and the value to send back to the server is in the 2nd column.</p>
1061 <pre>&lt;?<br><b>include</b>('adodb.inc.php'); # load code common to ADOdb<br>$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql'); # create a connection<br>$<font color="#663300">conn</font>-&gt;PConnect('localhost','userid','','agora');# connect to MySQL, agora db<br><font>$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers';<br>$<font color="#663300">rs</font> = $<font color="#663300">conn</font>-&gt;Execute($sql);<br><b>print</b> <b><font color="#336600">$<font color="#663300">rs</font>-&gt;GetMenu('GetCust','Mary Rosli');<br>?&gt;</font></b></font></pre>
1062 <p>Here we define a menu named GetCust, with the menu option 'Mary Rosli' selected.
1063 See <a href="#getmenu"><font face="Courier New, Courier, mono">GetMenu</font></a><font face="Courier New, Courier, mono">()</font>.
1064 We also have functions that return the recordset as an array: <font face="Courier New, Courier, mono"><a href="#getarray">GetArray</a>()</font>,
1065 and as an associative array with the key being the first column: <a href="#getassoc1">GetAssoc</a>().</p>
1066 <h3>Example 6: Connecting to 2 Databases At Once<a name="ex6"></a></h3>
1067 <pre>&lt;?<br><b>include</b>('adodb.inc.php'); # load code common to ADOdb<br>$<font color="#663300">conn1</font> = &amp;ADONewConnection('mysql'); # create a mysql connection<br>$<font color="#663300">conn2</font> = &amp;ADONewConnection('oracle'); # create a oracle connection<br><br>$conn1-&gt;PConnect($server, $userid, $password, $database);<br>$conn2-&gt;PConnect(false, $ora_userid, $ora_pwd, $oraname);<br><br>$conn1-&gt;Execute('insert ...');<br>$conn2-&gt;Execute('update ...');<br>?&gt;</pre>
1068 <p>
1069 </p><h3>Example 7: Generating Update and Insert SQL<a name="ex7"></a></h3>
1070 <p>Since ADOdb 4.56, we support <a href="reference.functions.getupdatesql.html#autoexecute">AutoExecute()</a>,
1071 which simplifies things by providing an advanced wrapper for GetInsertSQL() and GetUpdateSQL(). For example,
1072 an INSERT can be carried out with:
1073
1074 <pre>
1075 $record["firstname"] = "Bob";
1076 $record["lastname"] = "Smith";
1077 $record["created"] = time();
1078 $insertSQL = $conn->AutoExecute($rs, $record, 'INSERT');
1079 </pre>
1080
1081 and an UPDATE with:
1082 <pre>
1083 $record["firstname"] = "Caroline";
1084 $record["lastname"] = "Smith"; # Update Caroline's lastname from Miranda to Smith
1085 $insertSQL = $conn->AutoExecute($rs, $record, 'UPDATE', 'id = 1');
1086 </pre>
1087 <p>
1088 The rest of this section is out-of-date:
1089 <p>ADOdb 1.31 and later supports two new recordset functions: GetUpdateSQL( ) and
1090 GetInsertSQL( ). This allow you to perform a "SELECT * FROM table query WHERE...",
1091 make a copy of the $rs-&gt;fields, modify the fields, and then generate the SQL to
1092 update or insert into the table automatically.
1093 <p> We show how the functions can be used when accessing a table with the following
1094 fields: (ID, FirstName, LastName, Created).
1095 </p><p> Before these functions can be called, you need to initialize the recordset
1096 by performing a select on the table. Idea and code by Jonathan Younger jyounger#unilab.com.
1097 Since ADOdb 2.42, you can pass a table name instead of a recordset into
1098 GetInsertSQL (in $rs), and it will generate an insert statement for that table.
1099 </p><p>
1100 </p><pre>&lt;?<br>#==============================================<br># SAMPLE GetUpdateSQL() and GetInsertSQL() code<br>#==============================================<br>include('adodb.inc.php');<br>include('tohtml.inc.php');<br><br>#==========================<br># This code tests an insert<br><br>$sql = "SELECT * FROM ADOXYZ WHERE id = -1"; <br># Select an empty record from the database<br><br>$conn = &amp;ADONewConnection("mysql"); # create a connection<br>$conn-&gt;debug=1;<br>$conn-&gt;PConnect("localhost", "admin", "", "test"); # connect to MySQL, testdb<br>$rs = $conn-&gt;Execute($sql); # Execute the query and get the empty recordset<br><br>$record = array(); # Initialize an array to hold the record data to insert<br><br># Set the values for the fields in the record<br># Note that field names are case-insensitive<br>$record["firstname"] = "Bob";<br>$record["lastNamE"] = "Smith";<br>$record["creaTed"] = time();<br><br># Pass the empty recordset and the array containing the data to insert<br># into the GetInsertSQL function. The function will process the data and return<br># a fully formatted insert sql statement.<br>$insertSQL = $conn-&gt;GetInsertSQL($rs, $record);<br><br>$conn-&gt;Execute($insertSQL); # Insert the record into the database<br><br>#==========================<br># This code tests an update<br><br>$sql = "SELECT * FROM ADOXYZ WHERE id = 1"; <br># Select a record to update<br><br>$rs = $conn-&gt;Execute($sql); # Execute the query and get the existing record to update<br><br>$record = array(); # Initialize an array to hold the record data to update<br><br># Set the values for the fields in the record<br># Note that field names are case-insensitive<br>$record["firstname"] = "Caroline";<br>$record["LasTnAme"] = "Smith"; # Update Caroline's lastname from Miranda to Smith<br><br># Pass the single record recordset and the array containing the data to update<br># into the GetUpdateSQL function. The function will process the data and return<br># a fully formatted update sql statement with the correct WHERE clause.<br># If the data has not changed, no recordset is returned<br>$updateSQL = $conn-&gt;GetUpdateSQL($rs, $record);<br><br>$conn-&gt;Execute($updateSQL); # Update the record in the database<br>$conn-&gt;Close();<br>?&gt;<br></pre>
1101 <a name="ADODB_FORCE_TYPE"></a>
1102 <b>$ADODB_FORCE_TYPE</b><p>
1103 The behaviour of AutoExecute(), GetUpdateSQL() and GetInsertSQL()
1104 when converting empty or null PHP variables to SQL is controlled by the
1105 global $ADODB_FORCE_TYPE variable. Set it to one of the values below. Default
1106 is ADODB_FORCE_VALUE (3):
1107 </p><pre>0 = ignore empty fields. All empty fields in array are ignored.<br>1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.<br>2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.<br>3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and <br> empty fields '' are set to empty '' sql values.<br><br>define('ADODB_FORCE_IGNORE',0);<br>define('ADODB_FORCE_NULL',1);<br>define('ADODB_FORCE_EMPTY',2);<br>define('ADODB_FORCE_VALUE',3);<br></pre>
1108 <p>
1109 Thanks to Niko (nuko#mbnet.fi) for the $ADODB_FORCE_TYPE code.
1110 </p><p>
1111 Note: the constant ADODB_FORCE_NULLS is obsolete since 4.52 and is ignored. Set $ADODB_FORCE_TYPE = ADODB_FORCE_NULL
1112 for equivalent behaviour.
1113 <p>Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called.
1114 </p><h3>Example 8: Implementing Scrolling with Next and Previous<a name="ex8"></a></h3>
1115 <p> The following code creates a very simple recordset pager, where you can scroll
1116 from page to page of a recordset.</p>
1117 <pre>include_once('../adodb.inc.php');<br>include_once('../adodb-pager.inc.php');<br>session_start();<br><br>$db = NewADOConnection('mysql');<br><br>$db-&gt;Connect('localhost','root','','xphplens');<br><br>$sql = "select * from adoxyz ";<br><br>$pager = new ADODB_Pager($db,$sql);<br>$pager-&gt;Render($rows_per_page=5);</pre>
1118 <p>This will create a basic record pager that looks like this: <a name="scr"></a>
1119 </p><p>
1120 <table bgcolor="beige" border="1">
1121 <tbody><tr>
1122 <td> <a href="#scr"><code>|&lt;</code></a> &nbsp; <a href="#scr"><code>&lt;&lt;</code></a>
1123 &nbsp; <a href="#scr"><code>&gt;&gt;</code></a> &nbsp; <a href="#scr"><code>&gt;|</code></a>
1124 &nbsp; </td>
1125 </tr>
1126 <tr>
1127 <td><table bgcolor="white" border="1" cols="4" width="100%">
1128 <tbody><tr><th>ID</th>
1129 <th>First Name</th>
1130 <th>Last Name</th>
1131 <th>Date Created</th>
1132 </tr><tr>
1133 <td align="right">36&nbsp;</td>
1134 <td>Alan&nbsp;</td>
1135 <td>Turing&nbsp;</td>
1136 <td>Sat 06, Oct 2001&nbsp;</td>
1137 </tr>
1138 <tr>
1139 <td align="right">37&nbsp;</td>
1140 <td>Serena&nbsp;</td>
1141 <td>Williams&nbsp;</td>
1142 <td>Sat 06, Oct 2001&nbsp;</td>
1143 </tr>
1144 <tr>
1145 <td align="right">38&nbsp;</td>
1146 <td>Yat Sun&nbsp;</td>
1147 <td>Sun&nbsp;</td>
1148 <td>Sat 06, Oct 2001&nbsp;</td>
1149 </tr>
1150 <tr>
1151 <td align="right">39&nbsp;</td>
1152 <td>Wai Hun&nbsp;</td>
1153 <td>See&nbsp;</td>
1154 <td>Sat 06, Oct 2001&nbsp;</td>
1155 </tr>
1156 <tr>
1157 <td align="right">40&nbsp;</td>
1158 <td>Steven&nbsp;</td>
1159 <td>Oey&nbsp;</td>
1160 <td>Sat 06, Oct 2001&nbsp;</td>
1161 </tr>
1162 </tbody></table></td>
1163 </tr>
1164 <tr>
1165 <td><font size="-1">Page 8/10</font></td>
1166 </tr>
1167 </tbody></table>
1168 </p><p>The number of rows to display at one time is controled by the Render($rows)
1169 method. If you do not pass any value to Render(), ADODB_Pager will default to
1170 10 records per page.
1171 </p><p>You can control the column titles by modifying your SQL (supported by most
1172 databases):
1173 </p><pre>$sql = 'select id as "ID", firstname as "First Name", <br> lastname as "Last Name", created as "Date Created" <br> from adoxyz';</pre>
1174 <p>The above code can be found in the <i>adodb/tests/testpaging.php</i> example
1175 included with this release, and the class ADODB_Pager in <i>adodb/adodb-pager.inc.php</i>.
1176 The ADODB_Pager code can be adapted by a programmer so that the text links can
1177 be replaced by images, and the dull white background be replaced with more interesting
1178 colors.
1179 </p><p>You can also allow display of html by setting $pager-&gt;htmlSpecialChars = false.
1180 </p><p>Some of the code used here was contributed by Iv&aacute;n Oliva and Cornel
1181 G. </p>
1182 <h3><a name="ex9"></a>Example 9: Exporting in CSV or Tab-Delimited Format</h3>
1183 <p>We provide some helper functions to export in comma-separated-value (CSV) and
1184 tab-delimited formats:</p>
1185 <pre><b>include_once('/path/to/adodb/toexport.inc.php');</b><br>include_once('/path/to/adodb/adodb.inc.php');<br>
1186 $db = &amp;NewADOConnection('mysql');<br>$db-&gt;Connect($server, $userid, $password, $database);<br><br>$rs = $db-&gt;Execute('select fname as "First Name", surname as "Surname" from table');<br><br>print "&lt;pre&gt;";<br>print <b>rs2csv</b>($rs); # return a string, CSV format<p>print '&lt;hr&gt;';<br><br>$rs-&gt;MoveFirst(); # note, some databases do not support MoveFirst<br>print <b>rs2tab</b>($rs,<i>false</i>); # return a string, tab-delimited<br> # false == suppress field names in first line</p>print '&lt;hr&gt;';<br>$rs-&gt;MoveFirst();<br><b>rs2tabout</b>($rs); # send to stdout directly (there is also an rs2csvout function)<br>print "&lt;/pre&gt;";<br><br>$rs-&gt;MoveFirst();<br>$fp = fopen($path, "w");<br>if ($fp) {<br> <b>rs2csvfile</b>($rs, $fp); # write to file (there is also an rs2tabfile function)<br> fclose($fp);<br>}<br></pre>
1187 <p> Carriage-returns or newlines are converted to spaces. Field names are returned
1188 in the first line of text. Strings containing the delimiter character are quoted
1189 with double-quotes. Double-quotes are double-quoted again. This conforms to
1190 Excel import and export guide-lines.
1191 </p><p>All the above functions take as an optional last parameter, $addtitles which
1192 defaults to <i>true</i>. When set to <i>false</i> field names in the first line
1193 are suppressed. <br>
1194 </p><h3>Example 10: Recordset Filters<a name="ex10"></a></h3>
1195 <p>Sometimes we want to pre-process all rows in a recordset before we use it.
1196 For example, we want to ucwords all text in recordset.
1197 </p><pre>include_once('adodb/rsfilter.inc.php');<br>include_once('adodb/adodb.inc.php');<br><br>// ucwords() every element in the recordset<br>function do_ucwords(&amp;$arr,$rs)<br>{<br> foreach($arr as $k =&gt; $v) {<br> $arr[$k] = ucwords($v);<br> }<br>}<br><br>$db = NewADOConnection('mysql');<br>$db-&gt;PConnect('server','user','pwd','db');<br><br>$rs = $db-&gt;Execute('select ... from table');<br>$rs = <b>RSFilter</b>($rs,'do_ucwords');<br></pre>
1198 <p>The <i>RSFilter</i> function takes 2 parameters, the recordset, and the name
1199 of the <i>filter</i> function. It returns the processed recordset scrolled to
1200 the first record. The <i>filter</i> function takes two parameters, the current
1201 row as an array, and the recordset object. For future compatibility, you should
1202 not use the original recordset object. </p>
1203 <h3>Example 11:<a name="ex11"></a> Smart Transactions</h3>
1204 The old way of doing transactions required you to use
1205 <pre>$conn-&gt;<b>BeginTrans</b>();<br>$ok = $conn-&gt;Execute($sql);<br>if ($ok) $ok = $conn-&gt;Execute($sql2);<br>if (!$ok) $conn-&gt;<b>RollbackTrans</b>();<br>else $conn-&gt;<b>CommitTrans</b>();<br></pre>
1206 This is very complicated for large projects because you have to track the error
1207 status. Smart Transactions is much simpler. You start a smart transaction by calling
1208 StartTrans():
1209 <pre>$conn-&gt;<b>StartTrans</b>();<br>$conn-&gt;Execute($sql);<br>$conn-&gt;Execute($Sql2);<br>$conn-&gt;<b>CompleteTrans</b>();<br></pre>
1210 CompleteTrans() detects when an SQL error occurs, and will Rollback/Commit as
1211 appropriate. To specificly force a rollback even if no error occured, use FailTrans().
1212 Note that the rollback is done in CompleteTrans(), and not in FailTrans().
1213 <pre>$conn-&gt;<b>StartTrans</b>();<br>$conn-&gt;Execute($sql);<br>if (!CheckRecords()) $conn-&gt;<strong>FailTrans</strong>();<br>$conn-&gt;Execute($Sql2);<br>$conn-&gt;<b>CompleteTrans</b>();<br></pre>
1214 <p>You can also check if a transaction has failed, using HasFailedTrans(), which
1215 returns true if FailTrans() was called, or there was an error in the SQL execution.
1216 Make sure you call HasFailedTrans() before you call CompleteTrans(), as it is
1217 only works between StartTrans/CompleteTrans.
1218 </p><p>Lastly, StartTrans/CompleteTrans is nestable, and only the outermost block
1219 is executed. In contrast, BeginTrans/CommitTrans/RollbackTrans is NOT nestable.
1220 </p><pre>$conn-&gt;<strong>StartTrans</strong>();<br>$conn-&gt;Execute($sql);<br> $conn-&gt;<strong>StartTrans</strong>(); <font color="#006600"># ignored</font>
1221 if (!CheckRecords()) $conn-&gt;FailTrans();
1222 $conn-&gt;<strong>CompleteTrans</strong>(); <font color="#006600"># ignored</font>
1223 $conn-&gt;Execute($Sql2);
1224 $conn-&gt;<strong>CompleteTrans</strong>();<br></pre>
1225 <p>Note: Savepoints are currently not supported.
1226 </p><h2><a name="errorhandling"></a>Using Custom Error Handlers and PEAR_Error</h2>
1227 <p>ADOdb supports PHP5 exceptions. Just include <i>adodb-exceptions.inc.php</i> and you can now
1228 catch exceptions on errors as they occur.
1229 </p><pre> <b>include("../adodb-exceptions.inc.php");</b> <br> include("../adodb.inc.php"); <br> try { <br> $db = NewADOConnection("oci8://scott:bad-password@mytns/"); <br> } catch (exception $e) { <br> var_dump($e); <br> adodb_backtrace($e-&gt;gettrace());<br> } <br></pre>
1230 <p> ADOdb also provides two custom handlers which you can modify for your needs. The
1231 first one is in the <b>adodb-errorhandler.inc.php</b> file. This makes use of
1232 the standard PHP functions <a href="http://php.net/error_reporting">error_reporting</a>
1233 to control what error messages types to display, and <a href="http://php.net/trigger_error">trigger_error</a>
1234 which invokes the default PHP error handler.
1235 </p><p> Including the above file will cause <i>trigger_error($errorstring,E_USER_ERROR)</i>
1236 to be called when<br>
1237 (a) Connect() or PConnect() fails, or <br>
1238 (b) a function that executes SQL statements such as Execute() or SelectLimit()
1239 has an error.<br>
1240 (c) GenID() appears to go into an infinite loop.
1241 </p><p> The $errorstring is generated by ADOdb and will contain useful debugging information
1242 similar to the error.log data generated below. This file adodb-errorhandler.inc.php
1243 should be included before you create any ADOConnection objects.
1244 </p><p> If you define error_reporting(0), no errors will be passed to the error handler.
1245 If you set error_reporting(E_ALL), all errors will be passed to the error handler.
1246 You still need to use <b>ini_set("display_errors", "0" or "1")</b> to control
1247 the display of errors.
1248 </p><pre>&lt;?php<br><b>error_reporting(E_ALL); # pass any error messages triggered to error handler<br>include('adodb-errorhandler.inc.php');</b>
1249 include('adodb.inc.php');
1250 include('tohtml.inc.php');
1251 $c = NewADOConnection('mysql');
1252 $c-&gt;PConnect('localhost','root','','northwind');
1253 $rs=$c-&gt;Execute('select * from productsz'); #invalid table productsz');
1254 if ($rs) rs2html($rs);
1255 ?&gt;
1256 </pre>
1257 <p> If you want to log the error message, you can do so by defining the following
1258 optional constants ADODB_ERROR_LOG_TYPE and ADODB_ERROR_LOG_DEST. ADODB_ERROR_LOG_TYPE
1259 is the error log message type (see <a href="http://php.net/error_log">error_log</a>
1260 in the PHP manual). In this case we set it to 3, which means log to the file
1261 defined by the constant ADODB_ERROR_LOG_DEST.
1262 </p><pre>&lt;?php<br><b>error_reporting(E_ALL); # report all errors<br>ini_set("display_errors", "0"); # but do not echo the errors<br>define('ADODB_ERROR_LOG_TYPE',3);<br>define('ADODB_ERROR_LOG_DEST','C:/errors.log');<br>include('adodb-errorhandler.inc.php');</b>
1263 include('adodb.inc.php');
1264 include('tohtml.inc.php');
1265
1266 $c = NewADOConnection('mysql');
1267 $c-&gt;PConnect('localhost','root','','northwind');
1268 $rs=$c-&gt;Execute('select * from productsz'); ## invalid table productsz
1269 if ($rs) rs2html($rs);
1270 ?&gt;
1271 </pre>
1272 The following message will be logged in the error.log file:
1273 <pre>(2001-10-28 14:20:38) mysql error: [1146: Table 'northwind.productsz' doesn't exist] in<br> EXECUTE("select * from productsz")<br></pre>
1274 <h3>PEAR_ERROR</h3>
1275 The second error handler is <b>adodb-errorpear.inc.php</b>. This will create a
1276 PEAR_Error derived object whenever an error occurs. The last PEAR_Error object
1277 created can be retrieved using ADODB_Pear_Error().
1278 <pre>&lt;?php<br><b>include('adodb-errorpear.inc.php');</b>
1279 include('adodb.inc.php');
1280 include('tohtml.inc.php');
1281 $c = NewADOConnection('mysql');
1282 $c-&gt;PConnect('localhost','root','','northwind');
1283 $rs=$c-&gt;Execute('select * from productsz'); #invalid table productsz');
1284 if ($rs) rs2html($rs);
1285 else {
1286 <b>$e = ADODB_Pear_Error();<br> echo '&lt;p&gt;',$e-&gt;message,'&lt;/p&gt;';</b>
1287 }
1288 ?&gt;
1289 </pre>
1290 <p> You can use a PEAR_Error derived class by defining the constant ADODB_PEAR_ERROR_CLASS
1291 before the adodb-errorpear.inc.php file is included. For easy debugging, you
1292 can set the default error handler in the beginning of the PHP script to PEAR_ERROR_DIE,
1293 which will cause an error message to be printed, then halt script execution:
1294 </p><pre>include('PEAR.php');<br>PEAR::setErrorHandling('PEAR_ERROR_DIE');<br></pre>
1295 <p> Note that we do not explicitly return a PEAR_Error object to you when an error
1296 occurs. We return false instead. You have to call ADODB_Pear_Error() to get
1297 the last error or use the PEAR_ERROR_DIE technique.
1298 </p>
1299 <h3>MetaError and MetaErrMsg</h3>
1300 <p>If you need error messages that work across multiple databases, then use <a href="#metaerror">MetaError()</a>, which returns a virtualized error number, based on PEAR DB's error number system, and <a href=<a href="#metaerrmsg">MetaErrMsg()</a>.
1301
1302 <h4>Error Messages</h4>
1303 <p>Error messages are outputted using the static method ADOConnnection::outp($msg,$newline=true).
1304 By default, it sends the messages to the client. You can override this to perform
1305 error-logging.
1306 </p><h2><a name="dsn"></a> Data Source Names</h2>
1307 <p>We now support connecting using PEAR style DSN's. A DSN is a connection string
1308 of the form:</p>
1309 <p>$dsn = <i>"$driver://$username:$password@$hostname/$databasename"</i>;</p>
1310 <p>An example:</p>
1311 <pre> $username = 'root';<br> $password = '';<br> $hostname = 'localhost';<br> $databasename = 'xphplens';<br> $driver = 'mysql';<br> $dsn = "$driver://$username:$password@$hostname/$databasename"<br> $db = NewADOConnection(); <br> # DB::Connect($dsn) also works if you include 'adodb/adodb-pear.inc.php' at the top<br> $rs = $db-&gt;query('select firstname,lastname from adoxyz');<br> $cnt = 0;<br> while ($arr = $rs-&gt;fetchRow()) {<br> print_r($arr); print "&lt;br&gt;";<br> }</pre>
1312 <p></p>
1313 <p> <a href="#dsnsupport">More info and connection examples</a> on the DSN format.
1314
1315 </p><h2><a name="pear"></a>PEAR Compatibility</h2>
1316 We support DSN's (see above), and the following functions:
1317 <pre><b> DB_Common</b>
1318 query - returns PEAR_Error on error
1319 limitQuery - return PEAR_Error on error
1320 prepare - does not return PEAR_Error on error
1321 execute - does not return PEAR_Error on error
1322 setFetchMode - supports ASSOC and ORDERED
1323 errorNative
1324 quote
1325 nextID
1326 disconnect
1327
1328 getOne
1329 getAssoc
1330 getRow
1331 getCol
1332
1333 <b> DB_Result</b>
1334 numRows - returns -1 if not supported
1335 numCols
1336 fetchInto - does not support passing of fetchmode
1337 fetchRows - does not support passing of fetchmode
1338 free
1339 </pre>
1340 <h2><a name="caching"></a>Caching of Recordsets</h2>
1341 <p>ADOdb now supports caching of recordsets using the CacheExecute( ), CachePageExecute(
1342 ) and CacheSelectLimit( ) functions. There are similar to the non-cache functions,
1343 except that they take a new first parameter, $secs2cache.
1344 </p><p> An example:
1345 </p><pre><b>include</b>('adodb.inc.php'); # load code common to ADOdb<br>$ADODB_CACHE_DIR = '/usr/ADODB_cache';<br>$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql'); # create a connection<br>$<font color="#663300">conn</font>-&gt;PConnect('localhost','userid','','agora');# connect to MySQL, agora db<br><font>$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers';<br>$<font color="#663300">rs</font> = $<font color="#663300">conn</font>-&gt;CacheExecute(15,$sql);</font></pre>
1346 <p><font> The first parameter is the number of seconds to cache
1347 the query. Subsequent calls to that query will used the cached version stored
1348 in $ADODB_CACHE_DIR. To force a query to execute and flush the cache, call CacheExecute()
1349 with the first parameter set to zero. Alternatively, use the CacheFlush($sql)
1350 call. </font></p>
1351 <p><font>For the sake of security, we recommend you set <i>register_globals=off</i>
1352 in php.ini if you are using $ADODB_CACHE_DIR.</font></p>
1353 <p>In ADOdb 1.80 onwards, the secs2cache parameter is optional in CacheSelectLimit()
1354 and CacheExecute(). If you leave it out, it will use the $connection-&gt;cacheSecs
1355 parameter, which defaults to 60 minutes.
1356 </p><pre> $conn-&gt;Connect(...);<br> $conn-&gt;cacheSecs = 3600*24; # cache 24 hours<br> $rs = $conn-&gt;CacheExecute('select * from table');<br></pre>
1357 <p>Please note that magic_quotes_runtime should be turned off. <a href="http://phplens.com/lens/lensforum/msgs.php?LeNs#LensBM_forummsg">More
1358 info</a>, and do not change $ADODB_FETCH_MODE (or SetFetchMode)
1359 as the cached recordset will use the $ADODB_FETCH_MODE set when the query was executed. <font>
1360 <h2><a name="pivot"></a>Pivot Tables</h2>
1361 </font> </p><p><font>Since ADOdb 2.30, we support the generation of
1362 SQL to create pivot tables, also known as cross-tabulations. For further explanation
1363 read this DevShed <a href="http://www.devshed.com/Server_Side/MySQL/MySQLWiz/">Cross-Tabulation
1364 tutorial</a>. We assume that your database supports the SQL case-when expression. </font></p>
1365 <font>
1366 <p>In this example, we will use the Northwind database from Microsoft. In the
1367 database, we have a products table, and we want to analyze this table by <i>suppliers
1368 versus product categories</i>. We will place the suppliers on each row, and
1369 pivot on categories. So from the table on the left, we generate the pivot-table
1370 on the right:</p>
1371 </font>
1372 <table align="center" border="0" cellpadding="2" cellspacing="2">
1373 <tbody><tr>
1374 <td>
1375 <table align="center" border="1" cellpadding="2" cellspacing="2" width="142">
1376 <tbody><tr>
1377 <td><i>Supplier</i></td>
1378 <td><i>Category</i></td>
1379 </tr>
1380 <tr>
1381 <td>supplier1</td>
1382 <td>category1</td>
1383 </tr>
1384 <tr>
1385 <td>supplier2</td>
1386 <td>category1</td>
1387 </tr>
1388 <tr>
1389 <td>supplier2</td>
1390 <td>category2</td>
1391 </tr>
1392 </tbody></table>
1393 </td>
1394 <td> <font face="Courier New, Courier, mono">--&gt;</font></td>
1395 <td>
1396 <table align="center" border="1" cellpadding="2" cellspacing="2">
1397 <tbody><tr>
1398 <td>&nbsp;</td>
1399 <td><i>category1</i></td>
1400 <td><i>category2</i></td>
1401 <td><i>total</i></td>
1402 </tr>
1403 <tr>
1404 <td><i>supplier1</i></td>
1405 <td align="right">1</td>
1406 <td align="right">0</td>
1407 <td align="right">1</td>
1408 </tr>
1409 <tr>
1410 <td><i>supplier2</i></td>
1411 <td align="right">1</td>
1412 <td align="right">1</td>
1413 <td align="right">2</td>
1414 </tr>
1415 </tbody></table>
1416 </td>
1417 </tr>
1418 </tbody></table>
1419 <font>
1420 </font><p><font>The following code will generate the SQL for a cross-tabulation:
1421 </font></p><pre><font># Query the main "product" table<br># Set the rows to SupplierName<br># and the columns to the values of Categories<br># and define the joins to link to lookup tables <br># "categories" and "suppliers"<br>#<br> include "adodb/pivottable.inc.php";<br> $sql = PivotTableSQL(<br> $gDB, # adodb connection<br> 'products p ,categories c ,suppliers s', # tables<br> 'SupplierName', # rows (multiple fields allowed)<br> 'CategoryName', # column to pivot on <br> 'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where<br>);<br></font></pre>
1422
1423 <p><font> This will generate the following SQL:</font></p>
1424 <p><code><font size="2">SELECT SupplierName, <br>
1425 SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages",
1426 <br>
1427 SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments",
1428 <br>
1429 SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections",
1430 <br>
1431 SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy
1432 Products", <br>
1433 SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals",
1434 <br>
1435 SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry",
1436 <br>
1437 SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce",
1438 <br>
1439 SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood",
1440 <br>
1441 SUM(1) as Total <br>
1442 FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID
1443 and s.SupplierID= p.SupplierID <br>
1444 GROUP BY SupplierName</font></code></p>
1445 <p> You can also pivot on <i>numerical columns</i> and <i>generate totals</i>
1446 by using ranges. <font>This code was revised in ADODB 2.41
1447 and is not backward compatible.</font> The second example shows this:</p>
1448 <pre> $sql = PivotTableSQL(<br> $gDB, # adodb connection<br> 'products p ,categories c ,suppliers s', # tables<br> 'SupplierName', #<font> rows (multiple fields allowed)</font>
1449 array( # column ranges
1450 ' 0 ' =&gt; 'UnitsInStock &lt;= 0',
1451 "1 to 5" =&gt; '0 &lt; UnitsInStock and UnitsInStock &lt;= 5',
1452 "6 to 10" =&gt; '5 &lt; UnitsInStock and UnitsInStock &lt;= 10',
1453 "11 to 15" =&gt; '10 &lt; UnitsInStock and UnitsInStock &lt;= 15',
1454 "16+" =&gt; '15 &lt; UnitsInStock'
1455 ),
1456 ' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where
1457 'UnitsInStock', # sum this field
1458 'Sum ' # sum label prefix
1459 );
1460 </pre>
1461 <p>Which generates: </p>
1462 <p> <code> <font size="2">SELECT SupplierName, <br>
1463 SUM(CASE WHEN UnitsInStock &lt;= 0 THEN UnitsInStock ELSE 0 END) AS "Sum
1464 0 ", <br>
1465 SUM(CASE WHEN 0 &lt; UnitsInStock and UnitsInStock &lt;= 5 THEN UnitsInStock
1466 ELSE 0 END) AS "Sum 1 to 5",<br>
1467 SUM(CASE WHEN 5 &lt; UnitsInStock and UnitsInStock &lt;= 10 THEN UnitsInStock
1468 ELSE 0 END) AS "Sum 6 to 10",<br>
1469 SUM(CASE WHEN 10 &lt; UnitsInStock and UnitsInStock &lt;= 15 THEN UnitsInStock
1470 ELSE 0 END) AS "Sum 11 to 15", <br>
1471 SUM(CASE WHEN 15 &lt; UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum
1472 16+", <br>
1473 SUM(UnitsInStock) AS "Sum UnitsInStock", <br>
1474 SUM(1) as Total,<br>
1475 FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID
1476 and s.SupplierID= p.SupplierID <br>
1477 GROUP BY SupplierName</font></code><font size="2"><br>
1478 </font> </p>
1479 <font><hr />
1480 <h1>Class Reference<a name="ref"></a></h1>
1481 <p>Function parameters with [ ] around them are optional.</p>
1482 </font>
1483 <h2>Global Variables</h2>
1484 <h3><font><a name="adodb_countrecs"></a></font>$ADODB_COUNTRECS</h3>
1485 <p>If the database driver API does not support counting the number of records
1486 returned in a SELECT statement, the function RecordCount() is emulated when
1487 the global variable $ADODB_COUNTRECS is set to true, which is the default.
1488 We emulate this by buffering the records, which can take up large amounts
1489 of memory for big recordsets. Set this variable to false for the best performance.
1490 This variable is checked every time a query is executed, so you can selectively
1491 choose which recordsets to count.</p>
1492 <h3><font><a name="adodb_cache_dir"></a>$ADODB_CACHE_DIR</font></h3>
1493 <font>
1494 <p>If you are using recordset caching, this is the directory to save your recordsets
1495 in. Define this before you call any caching functions such as CacheExecute(
1496 ). We recommend setting <i>register_globals=off</i> in php.ini if you use this
1497 feature for security reasons.</p>
1498 <p>If you are using Unix and apache, you might need to set your cache directory
1499 permissions to something similar to the following:</p>
1500 </font>
1501 <p>chown -R apache /path/to/adodb/cache<br>
1502 chgrp -R apache /path/to/adodb/cache </p>
1503 <h3><font><a name="adodb_ansi_padding_off"></a>$ADODB_ANSI_PADDING_OFF</font></h3>
1504 <p><font>Determines whether to right trim CHAR fields (and also VARCHAR for ibase/firebird).
1505 Set to true to trim. Default is false. Currently works for oci8po, ibase and firebird
1506 drivers. Added in ADOdb 4.01.
1507 </font></p><h3><font><a name="adodb_lang"></a>$ADODB_LANG</font></h3>
1508 <p><font>Determines the language used in MetaErrorMsg(). The default is 'en', for English.
1509 To find out what languages are supported, see the files
1510 in adodb/lang/adodb-$lang.inc.php, where $lang is the supported langauge.
1511 </font></p><h3><font><a name="adodb_fetch_mode"></a>$ADODB_FETCH_MODE</font></h3>
1512 <p><font>This is a global variable that determines how arrays are retrieved by recordsets.
1513 The recordset saves this value on creation (eg. in Execute( ) or SelectLimit(
1514 )), and any subsequent changes to $ADODB_FETCH_MODE have no affect on existing
1515 recordsets, only on recordsets created in the future.</font></p>
1516 <p><font>The following constants are defined:</font></p>
1517
1518 <p><font>define('ADODB_FETCH_DEFAULT',0);<br>
1519 define('ADODB_FETCH_NUM',1);<br>
1520 define('ADODB_FETCH_ASSOC',2);<br>
1521 define('ADODB_FETCH_BOTH',3); </font></p>
1522 <font>
1523 </font><p><font> An example:
1524 </font></p><pre><font> $ADODB_<b>FETCH_MODE</b> = ADODB_FETCH_NUM;<br> $rs1 = $db-&gt;Execute('select * from table');<br> $ADODB_<b>FETCH_MODE</b> = ADODB_FETCH_ASSOC;<br> $rs2 = $db-&gt;Execute('select * from table');<br> print_r($rs1-&gt;fields); # shows <i>array([0]=&gt;'v0',[1] =&gt;'v1')</i>
1525 print_r($rs2-&gt;fields); # shows <i>array(['col1']=&gt;'v0',['col2'] =&gt;'v1')</i>
1526 </font></pre>
1527 <p><font> As you can see in the above example, both recordsets store and use different
1528 fetch modes based on the $ADODB_FETCH_MODE setting when the recordset was
1529 created by Execute().</font></p>
1530 <p><font>If no fetch mode is predefined, the fetch mode defaults to ADODB_FETCH_DEFAULT.
1531 The behaviour of this default mode varies from driver to driver, so do not
1532 rely on ADODB_FETCH_DEFAULT. For portability, we recommend sticking to ADODB_FETCH_NUM
1533 or ADODB_FETCH_ASSOC. Many drivers do not support ADODB_FETCH_BOTH.</font></p>
1534 <p><font><strong>SetFetchMode Function</strong></font></p>
1535 <p><font>If you have multiple connection objects, and want to have different fetch modes for each
1536 connection, then use <a href="#setfetchmode">SetFetchMode</a>.
1537 Once this function is called for a connection object, that connection object
1538 will ignore the global variable $ADODB_FETCH_MODE and will use the internal
1539 fetchMode property exclusively.</font></p>
1540 <pre><font> $db-&gt;SetFetchMode(ADODB_FETCH_NUM);<br> $rs1 = $db-&gt;Execute('select * from table');<br> $db-&gt;SetFetchMode(ADODB_FETCH_ASSOC);<br> $rs2 = $db-&gt;Execute('select * from table');<br> print_r($rs1-&gt;fields); # shows <i>array([0]=&gt;'v0',[1] =&gt;'v1')</i>
1541 print_r($rs2-&gt;fields); # shows <i>array(['col1']=&gt;'v0',['col2'] =&gt;'v1')</i></font></pre>
1542 <p><font>To retrieve the previous fetch mode, you can use check the $db-&gt;fetchMode
1543 property, or use the return value of SetFetchMode( ).
1544 </font></p><p><font><strong><a name="adodb_assoc_case"></a>ADODB_ASSOC_CASE</strong></font></p>
1545 <p><font>You can control the associative fetch case for certain drivers which behave
1546 differently. For the sybase, oci8po, mssql, odbc and ibase drivers and all
1547 drivers derived from them, ADODB_ASSOC_CASE will by default generate recordsets
1548 where the field name keys are lower-cased. Use the constant ADODB_ASSOC_CASE
1549 to change the case of the keys. There are 3 possible values:</font></p>
1550 <p><font>0 = assoc lowercase field names. $rs-&gt;fields['orderid']<br>
1551 1 = assoc uppercase field names. $rs-&gt;fields['ORDERID']<br>
1552 2 = use native-case field names. $rs-&gt;fields['OrderID'] -- this is the
1553 default since ADOdb 2.90</font></p>
1554 <p><font>To use it, declare it before you incldue adodb.inc.php.</font></p>
1555 <p><font>define('ADODB_ASSOC_CASE', 2); # use native-case for ADODB_FETCH_ASSOC<br>
1556 include('adodb.inc.php'); </font></p>
1557 <h3><font><a name="force_type"></a>$ADODB_FORCE_TYPE</font></h3>
1558 <p><font>See the <a href="#ADODB_FORCE_TYPE">GetUpdateSQL tutorial</a>.
1559 </font></p><hr />
1560 <h2><font>ADOConnection<a name="adoconnection"></a></font></h2>
1561 <p><font>Object that performs the connection to the database, executes SQL statements
1562 and has a set of utility functions for standardising the format of SQL statements
1563 for issues such as concatenation and date formats.</font></p>
1564 <h3><font>ADOConnection Fields</font></h3>
1565 <p><font><b>databaseType</b>: Name of the database system we are connecting to. Eg.
1566 <b>odbc</b> or <b>mssql</b> or <b>mysql</b>.</font></p>
1567 <p><font><b>dataProvider</b>: The underlying mechanism used to connect to the database.
1568 Normally set to <b>native</b>, unless using <b>odbc</b> or <b>ado</b>.</font></p>
1569 <p><font><b>host: </b>Name of server or data source name (DSN) to connect to.</font></p>
1570 <p><font><b>database</b>: Name of the database or to connect to. If ado is used, it
1571 will hold the ado data provider.</font></p>
1572 <p><font><b>user</b>: Login id to connect to database. Password is not saved for security
1573 reasons.</font></p>
1574 <p><font><b>raiseErrorFn</b>: Allows you to define an error handling function. See adodb-errorhandler.inc.php
1575 for an example.</font></p>
1576 <p><font><b>debug</b>: Set to <i>true</i> to make debug statements to appear.</font></p>
1577 <p><font><b>concat_operator</b>: Set to '+' or '||' normally. The operator used to concatenate
1578 strings in SQL. Used by the <b><a href="#concat">Concat</a></b> function.</font></p>
1579 <p><font><b>fmtDate</b>: The format used by the <b><a href="#dbdate">DBDate</a></b>
1580 function to send dates to the database. is '#Y-m-d#' for Microsoft Access,
1581 and ''Y-m-d'' for MySQL.</font></p>
1582 <p><font><b>fmtTimeStamp: </b>The format used by the <b><a href="#dbtimestamp">DBTimeStamp</a></b>
1583 function to send timestamps to the database. </font></p>
1584 <p><font><b>true</b>: The value used to represent true.Eg. '.T.'. for Foxpro, '1' for
1585 Microsoft SQL.</font></p>
1586 <p><font><b>false: </b> The value used to represent false. Eg. '.F.'. for Foxpro, '0'
1587 for Microsoft SQL.</font></p>
1588 <p><font><b>replaceQuote</b>: The string used to escape quotes. Eg. double single-quotes
1589 for Microsoft SQL, and backslash-quote for MySQL. Used by <a href="#qstr">qstr</a>.</font></p>
1590 <p><font><b>autoCommit</b>: indicates whether automatic commit is enabled. Default is
1591 true.</font></p>
1592 <p><font><b>charSet</b>: set the default charset to use. Currently only interbase/firebird supports
1593 this.</font></p>
1594 <p><font><b>dialect</b>: set the default sql dialect to use. Currently only interbase/firebird
1595 supports this.</font></p>
1596 <p><font><b>role</b>: set the role. Currently only interbase/firebird
1597 supports this.</font></p>
1598 <p><font><b>metaTablesSQL</b>: SQL statement to return a list of available tables. Eg.
1599 <i>SHOW TABLES</i> in MySQL.</font></p>
1600 <p><font><b>genID</b>: The latest id generated by GenID() if supported by the database.</font></p>
1601 <p><font><b>cacheSecs</b>: The number of seconds to cache recordsets if CacheExecute()
1602 or CacheSelectLimit() omit the $secs2cache parameter. Defaults to 60 minutes.</font></p>
1603 <p><font><b>sysDate</b>: String that holds the name of the database function to call
1604 to get the current date. Useful for inserts and updates.</font></p>
1605 <p><font><b>sysTimeStamp</b>: String that holds the name of the database function to
1606 call to get the current timestamp/datetime value.</font></p>
1607 <p><font><b>leftOuter</b>: String that holds operator for left outer join, if known.
1608 Otherwise set to false.</font></p>
1609 <p><font><b>rightOuter</b>: String that holds operator for left outer join, if known.
1610 Otherwise set to false.</font></p>
1611 <p><font><b>ansiOuter</b>: Boolean that if true indicates that ANSI style outer joins
1612 are permitted. Eg. <i>select * from table1 left join table2 on p1=p2.</i></font></p>
1613 <p><font><b>connectSID</b>: Boolean that indicates whether to treat the $database parameter
1614 in connects as the SID for the oci8 driver. Defaults to false. Useful for
1615 Oracle 8.0.5 and earlier.</font></p>
1616 <p><font><b>autoRollback</b>: Persistent connections are auto-rollbacked in PConnect(
1617 ) if this is set to true. Default is false.</font></p>
1618 <hr />
1619 <h3><font>ADOConnection Main Functions</font></h3>
1620 <p><font><b>ADOConnection( )</b></font></p>
1621 <p><font>Constructor function. Do not call this directly. Use ADONewConnection( ) instead.</font></p>
1622 <p><font><b>Connect<a name="connect"></a>($host,[$user],[$password],[$database])</b></font></p>
1623 <p><font>Non-persistent connect to data source or server $<b>host</b>, using userid
1624 $<b>user </b>and password $<b>password</b>. If the server supports multiple
1625 databases, connect to database $<b>database</b>. </font></p>
1626 <p><font>Returns true/false depending on connection success. Since 4.23, null is returned if the extension is not loaded.</font></p>
1627 <p><font>ADO Note: If you are using a Microsoft ADO and not OLEDB, you can set the $database
1628 parameter to the OLEDB data provider you are using.</font></p>
1629 <p><font>PostgreSQL: An alternative way of connecting to the database is to pass the
1630 standard PostgreSQL connection string in the first parameter $host, and the
1631 other parameters will be ignored.</font></p>
1632 <p><font>For Oracle and Oci8, there are two ways to connect. First is to use the TNS
1633 name defined in your local tnsnames.ora (or ONAMES or HOSTNAMES). Place the
1634 name in the $database field, and set the $host field to false. Alternatively,
1635 set $host to the server, and $database to the database SID, this bypassed
1636 tnsnames.ora.
1637 </font></p><p><font>Examples:
1638 </font></p><pre><font> # $oraname in tnsnames.ora/ONAMES/HOSTNAMES<br> $conn-&gt;Connect(false, 'scott', 'tiger', $oraname); <br> $conn-&gt;Connect('server:1521', 'scott', 'tiger', 'ServiceName'); # bypass tnsnames.ora</font></pre>
1639 <p><font>There are many examples of connecting to a database.
1640 See <a href="#connect_ex">Connection Examples</a> for many examples.
1641
1642 </font></p><p><font><b>PConnect<a name="pconnect"></a>($host,[$user],[$password],[$database])</b></font></p>
1643 <p><font>Persistent connect to data source or server $<b>host</b>, using userid $<b>user</b>
1644 and password $<b>password</b>. If the server supports multiple databases,
1645 connect to database $<b>database</b>.</font></p>
1646 <p><font>We now perform a rollback on persistent connection for selected databases since
1647 2.21, as advised in the PHP manual. See change log or source code for which
1648 databases are affected.
1649 </font></p><p><font>Returns true/false depending on connection. Since 4.23, 0 is returned if the extension is not loaded.
1650 See Connect( ) above for more info.</font></p>
1651 <p><font>Since ADOdb 2.21, we also support autoRollback. If you set:</font></p>
1652
1653 <pre> $conn = &amp;NewADOConnection('mysql');<br> $conn-&gt;autoRollback = true; # default is false<br> $conn-&gt;PConnect(...); # rollback here</pre>
1654 <p> Then when doing a persistent connection with PConnect( ), ADOdb will
1655 perform a rollback first. This is because it is documented that PHP is
1656 not guaranteed to rollback existing failed transactions when
1657 persistent connections are used. This is implemented in Oracle,
1658 MySQL, PgSQL, MSSQL, ODBC currently.
1659 </p><p>Since ADOdb 3.11, you can force non-persistent
1660 connections even if PConnect is called by defining the constant
1661 ADODB_NEVER_PERSIST before you call PConnect.
1662 </p><p>
1663 Since 4.23, null is returned if the extension is not loaded.
1664 </p><p><b>NConnect<a name="nconnect"></a>($host,[$user],[$password],[$database])</b></p>
1665 <p>Always force a new connection. In contrast, PHP sometimes reuses connections
1666 when you use Connect() or PConnect(). Currently works only on mysql (PHP 4.3.0
1667 or later), postgresql and oci8-derived drivers. For other drivers, NConnect() works like
1668 Connect().</p>
1669 <p><font><b>IsConnected( )<a name="isconnected"></a></b></font></p>
1670 <p>
1671 <font>Returns true if connected to database. Added in 4.53.
1672
1673 </font></p><p><font><b>Execute<a name="execute"></a>($sql,$inputarr=false)</b></font></p>
1674 <p><font>Execute SQL statement $<b>sql</b> and return derived class of ADORecordSet
1675 if successful. Note that a record set is always returned on success, even
1676 if we are executing an insert or update statement. You can also pass in $sql a statement prepared
1677 in <a href="#prepare">Prepare()</a>.</font></p>
1678 <p><font>Returns derived class of ADORecordSet. Eg. if connecting via mysql, then ADORecordSet_mysql
1679 would be returned. False is returned if there was an error in executing the
1680 sql.</font></p>
1681 <p><font>The $inputarr parameter can be used for binding variables to parameters. Below
1682 is an Oracle example:</font></p>
1683 <pre><font> $conn-&gt;Execute("SELECT * FROM TABLE WHERE COND=:val", array('val'=&gt; $val));<br> </font></pre>
1684 <p><font>Another example, using ODBC,which uses the ? convention:</font></p>
1685 <pre><font> $conn-&gt;Execute("SELECT * FROM TABLE WHERE COND=?", array($val));<br></font></pre>
1686 <font><a name="binding"></a>
1687 <i>Binding variables</i></font><p>
1688 <font>Variable binding speeds the compilation and caching of SQL statements, leading
1689 to higher performance. Currently Oracle, Interbase and ODBC supports variable binding.
1690 Interbase/ODBC style ? binding is emulated in databases that do not support binding.
1691 Note that you do not have to quote strings if you use binding.
1692 </font></p><p><font> Variable binding in the odbc, interbase and oci8po drivers.
1693 </font></p><pre><font>$rs = $db-&gt;Execute('select * from table where val=?', array('10'));<br></font></pre>
1694 <font>Variable binding in the oci8 driver:
1695 </font><pre><font>$rs = $db-&gt;Execute('select name from table where val=:key', <br> array('key' =&gt; 10));<br></font></pre>
1696 <font><a name="bulkbind"></a>
1697 <i>Bulk binding</i>
1698 </font><p><font>Since ADOdb 3.80, we support bulk binding in Execute(), in which you pass in a 2-dimensional array to
1699 be bound to an INSERT/UPDATE or DELETE statement.
1700 </font></p><pre><font>$arr = array(<br> array('Ahmad',32),<br> array('Zulkifli', 24),<br> array('Rosnah', 21)<br> );<br>$ok = $db-&gt;Execute('insert into table (name,age) values (?,?)',$arr);<br></font></pre>
1701 <p><font>This provides very high performance as the SQL statement is prepared first.
1702 The prepared statement is executed repeatedly for each array row until all rows are completed,
1703 or until the first error. Very useful for importing data.
1704
1705 </font></p><p><font><b>CacheExecute<a name="cacheexecute"></a>([$secs2cache,]$sql,$inputarr=false)</b></font></p>
1706 <p><font>Similar to Execute, except that the recordset is cached for $secs2cache seconds
1707 in the $ADODB_CACHE_DIR directory, and $inputarr only accepts 1-dimensional arrays.
1708 If CacheExecute() is called again with the same $sql, $inputarr,
1709 and also the same database, same userid, and the cached recordset
1710 has not expired, the cached recordset is returned.
1711 </font></p><pre><font> include('adodb.inc.php'); <br> include('tohtml.inc.php');<br> $ADODB_<b>CACHE_DIR</b> = '/usr/local/ADOdbcache';<br> $conn = &amp;ADONewConnection('mysql'); <br> $conn-&gt;PConnect('localhost','userid','password','database');<br> $rs = $conn-&gt;<b>CacheExecute</b>(15, 'select * from table'); # cache 15 secs<br> rs2html($rs); /* recordset to html table */ <br></font></pre>
1712 <p><font> Alternatively, since ADOdb 1.80, the $secs2cache parameter is optional:</font></p>
1713 <pre><font> $conn-&gt;Connect(...);<br> $conn-&gt;cacheSecs = 3600*24; // cache 24 hours<br> $rs = $conn-&gt;CacheExecute('select * from table');<br></font></pre>
1714 <font>If $secs2cache is omitted, we use the value
1715 in $connection-&gt;cacheSecs (default is 3600 seconds, or 1 hour). Use CacheExecute()
1716 only with SELECT statements.
1717 </font><p><font>Performance note: I have done some benchmarks and found that they vary so greatly
1718 that it's better to talk about when caching is of benefit. When your database
1719 server is <i>much slower </i>than your Web server or the database is <i>very
1720 overloaded </i>then ADOdb's caching is good because it reduces the load on
1721 your database server. If your database server is lightly loaded or much faster
1722 than your Web server, then caching could actually reduce performance. </font></p>
1723 <p><font><b>ExecuteCursor<a name="executecursor"></a>($sql,$cursorName='rs',$parameters=false)</b></font></p>
1724 <p><font>Execute an Oracle stored procedure, and returns an Oracle REF cursor variable as
1725 a regular ADOdb recordset. Does not work with any other database except oci8.
1726 Thanks to Robert Tuttle for the design.
1727 </font></p><pre><font> $db = ADONewConnection("oci8"); <br> $db-&gt;Connect("foo.com:1521", "uid", "pwd", "FOO"); <br> $rs = $db-&gt;ExecuteCursor("begin :cursorvar := getdata(:param1); end;", <br> 'cursorvar',<br> array('param1'=&gt;10)); <br> # $rs is now just like any other ADOdb recordset object<br> rs2html($rs);</font></pre>
1728 <p><font>ExecuteCursor() is a helper function that does the following internally:
1729 </font></p><pre><font> $stmt = $db-&gt;Prepare("begin :cursorvar := getdata(:param1); end;", true); <br> $db-&gt;Parameter($stmt, $cur, 'cursorvar', false, -1, OCI_B_CURSOR);<br> $rs = $db-&gt;Execute($stmt,$bindarr);<br></font></pre>
1730 <p><font>ExecuteCursor only accepts 1 out parameter. So if you have 2 out parameters, use:
1731 </font></p><pre><font> $vv = 'A%';<br> $stmt = $db-&gt;PrepareSP("BEGIN list_tabs(:crsr,:tt); END;");<br> $db-&gt;OutParameter($stmt, $cur, 'crsr', -1, OCI_B_CURSOR);<br> $db-&gt;OutParameter($stmt, $vv, 'tt', 32); # return varchar(32)<br> $arr = $db-&gt;GetArray($stmt);<br> print_r($arr);<br> echo " val = $vv"; ## outputs 'TEST'<br></font></pre>
1732 <font>for the following PL/SQL:
1733 </font><pre><font> TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;<br><br> PROCEDURE list_tabs(tabcursor IN OUT TabType,tablenames IN OUT VARCHAR) IS<br> BEGIN<br> OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;<br> tablenames := 'TEST';<br> END list_tabs;<br></font></pre>
1734 <p><font><b>SelectLimit<a name="selectlimit"></a>($sql,$numrows=-1,$offset=-1,$inputarr=false)</b></font></p>
1735 <p><font>Returns a recordset if successful. Returns false otherwise. Performs a select
1736 statement, simulating PostgreSQL's SELECT statement, LIMIT $numrows OFFSET
1737 $offset clause.</font></p>
1738 <p><font>In PostgreSQL, SELECT * FROM TABLE LIMIT 3 will return the first 3 records
1739 only. The equivalent is <code>$connection-&gt;SelectLimit('SELECT * FROM TABLE',3)</code>.
1740 This functionality is simulated for databases that do not possess this feature.</font></p>
1741 <p><font>And SELECT * FROM TABLE LIMIT 3 OFFSET 2 will return records 3, 4 and 5 (eg.
1742 after record 2, return 3 rows). The equivalent in ADOdb is <code>$connection-&gt;SelectLimit('SELECT
1743 * FROM TABLE',3,2)</code>.</font></p>
1744 <p><font>Note that this is the <i>opposite</i> of MySQL's LIMIT clause. You can also
1745 set <code>$connection-&gt;SelectLimit('SELECT * FROM TABLE',-1,10)</code> to
1746 get rows 11 to the last row.</font></p>
1747 <p><font>The last parameter $inputarr is for databases that support variable binding
1748 such as Oracle oci8. This substantially reduces SQL compilation overhead.
1749 Below is an Oracle example:</font></p>
1750 <pre><font> $conn-&gt;SelectLimit("SELECT * FROM TABLE WHERE COND=:val", 100,-1,array('val'=&gt; $val));<br> </font></pre>
1751 <p><font>The oci8po driver (oracle portable driver) uses the more standard bind variable
1752 of ?:
1753 </font></p><pre><font> $conn-&gt;SelectLimit("SELECT * FROM TABLE WHERE COND=?", 100,-1,array('val'=&gt; $val));<br></font></pre>
1754 <p><font>
1755 </font></p><p><font>Ron Wilson reports that SelectLimit does not work with UNIONs.
1756 </font></p><p><font><b>CacheSelectLimit<a name="cacheselectlimit"></a>([$secs2cache,] $sql, $numrows=-1,$offset=-1,$inputarr=false)</b></font></p>
1757 <p><font>Similar to SelectLimit, except that the recordset returned is cached for $secs2cache
1758 seconds in the $ADODB_CACHE_DIR directory. </font></p>
1759 <p><font>Since 1.80, $secs2cache has been optional, and you can define the caching time
1760 in $connection-&gt;cacheSecs.</font></p>
1761
1762 <pre><font> $conn-&gt;Connect(...);<br> $conn-&gt;cacheSecs = 3600*24; // cache 24 hours<br> $rs = $conn-&gt;CacheSelectLimit('select * from table',10);</font></pre>
1763 <font>
1764 </font><p><font><b>CacheFlush<a name="cacheflush"></a>($sql=false,$inputarr=false)</b></font></p>
1765 <p><font>Flush (delete) any cached recordsets for the SQL statement $sql in $ADODB_CACHE_DIR.
1766 </font></p><p><font>If no parameter is passed in, then all adodb_*.cache files are deleted.
1767 </font></p><p><font> If you want to flush all cached recordsets manually, execute the following
1768 PHP code (works only under Unix): <br>
1769 <code> &nbsp; system("rm -f `find ".$ADODB_CACHE_DIR." -name
1770 adodb_*.cache`");</code></font></p>
1771 <p><font>For general cleanup of all expired files, you should use <a href="http://www.superscripts.com/tutorial/crontab.html">crontab</a>
1772 on Unix, or at.exe on Windows, and a shell script similar to the following:<font face="Courier New, Courier, mono"><br>
1773 #------------------------------------------------------ <br>
1774 # This particular example deletes files in the TMPPATH <br>
1775 # directory with the string ".cache" in their name that <br>
1776 # are more than 7 days old. <br>
1777 #------------------------------------------------------ <br>
1778 AGED=7 <br>
1779 find ${TMPPATH} -mtime +$AGED | grep "\.cache" | xargs rm -f <br>
1780 </font> </font></p>
1781 <p><font><b>MetaError<a name="metaerror"></a>($errno=false)</b></font></p>
1782 <p><font>Returns a virtualized error number, based on PEAR DB's error number system. You might
1783 need to include adodb-error.inc.php before you call this function. The parameter $errno
1784 is the native error number you want to convert. If you do not pass any parameter, MetaError
1785 will call ErrorNo() for you and convert it. If the error number cannot be virtualized, MetaError
1786 will return -1 (DB_ERROR).</font></p>
1787
1788 <p><font><b>MetaErrorMsg<a name="metaerrormsg"></a>($errno)</b></font></p>
1789 <p><font>Pass the error number returned by MetaError() for the equivalent textual error message.</font></p>
1790 <p><font><b>ErrorMsg<a name="errormsg"></a>()</b></font></p>
1791 <p><font>Returns the last status or error message. The error message is reset after every
1792 call to Execute().
1793 </font></p><p>
1794 <font>This can return a string even if
1795 no error occurs. In general you do not need to call this function unless an
1796 ADOdb function returns false on an error. </font></p>
1797 <p><font>Note: If <b>debug</b> is enabled, the SQL error message is always displayed
1798 when the <b>Execute</b> function is called.</font></p>
1799 <p><font><b>ErrorNo<a name="errorno"></a>()</b></font></p>
1800 <p><font>Returns the last error number. The error number is reset after every call to Execute().
1801 If 0 is returned, no error occurred.
1802 </font></p><p>
1803 <font>Note that old versions of PHP (pre 4.0.6) do
1804 not support error number for ODBC. In general you do not need to call this
1805 function unless an ADOdb function returns false on an error.</font></p>
1806
1807 <p><font><b>SetFetchMode<a name="setfetchmode"></a>($mode)</b></font></p>
1808 <p><font>Sets the current fetch mode for the connection and stores
1809 it in $db-&gt;fetchMode. Legal modes are ADODB_FETCH_ASSOC and ADODB_FETCH_NUM.
1810 For more info, see <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a>.</font></p>
1811 <p><font>Returns the previous fetch mode, which could be false
1812 if SetFetchMode( ) has not been called before.</font></p>
1813 <font>
1814 </font><p><font><b>CreateSequence<a name="createseq"></a>($seqName = 'adodbseq',$startID=1)</b></font></p>
1815 <p><font>Create a sequence. The next time GenID( ) is called, the value returned will
1816 be $startID. Added in 2.60.
1817 </font></p><p><font><b>DropSequence<a name="dropseq"></a>($seqName = 'adodbseq')</b></font></p>
1818 <p><font>Delete a sequence. Added in 2.60.
1819 </font></p><p><font><b>GenID<a name="genid"></a>($seqName = 'adodbseq',$startID=1)</b></font></p>
1820 <p><font>Generate a sequence number . Works for interbase,
1821 mysql, postgresql, oci8, oci8po, mssql, ODBC based (access,vfp,db2,etc) drivers
1822 currently. Uses $seqName as the name of the sequence. GenID() will automatically
1823 create the sequence for you if it does not exist (provided the userid has
1824 permission to do so). Otherwise you will have to create the sequence yourself.
1825 </font></p><p><font> If your database driver emulates sequences, the name of the table is the sequence
1826 name. The table has one column, "id" which should be of type integer, or if
1827 you need something larger - numeric(16).
1828 </font></p><p><font> For ODBC and databases that do not support sequences natively (eg mssql, mysql),
1829 we create a table for each sequence. If the sequence has not been defined
1830 earlier, it is created with the starting value set in $startID.</font></p>
1831 <p><font>Note that the mssql driver's GenID() before 1.90 used to generate 16 byte GUID's.</font></p>
1832 <p><font><b>UpdateBlob<a name="updateblob"></a>($table,$column,$val,$where)</b></font></p>
1833 <font>Allows you to store a blob (in $val) into $table into $column in a row at $where.
1834 </font><p><font> Usage:
1835 </font></p><p><font>
1836 </font></p><pre><font> # for oracle<br> $conn-&gt;Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, empty_blob())');<br> $conn-&gt;UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');<br> <br> # non oracle databases<br> $conn-&gt;Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');<br> $conn-&gt;UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');<br></font></pre>
1837 <p><font> Returns true if succesful, false otherwise. Supported by MySQL, PostgreSQL,
1838 Oci8, Oci8po and Interbase drivers. Other drivers might work, depending on
1839 the state of development.</font></p>
1840 <p><font>Note that when an Interbase blob is retrieved using SELECT, it still needs
1841 to be decoded using $connection-&gt;DecodeBlob($blob); to derive the original
1842 value in versions of PHP before 4.1.0.
1843 </font></p><p><font>For PostgreSQL, you can store your blob using blob oid's or as a bytea field.
1844 You can use bytea fields but not blob oid's currently with UpdateBlob( ).
1845 Conversely UpdateBlobFile( ) supports oid's, but not bytea data.<br>
1846 <br>
1847 If you do not pass in an oid, then UpdateBlob() assumes that you are storing
1848 in bytea fields.
1849 <p>If you do not have any blob fields, you can improve you can improve general SQL query performance by disabling blob handling with $connection->disableBlobs = true.
1850 </font></p><p><font><b>UpdateClob<a name="updateclob"></a>($table,$column,$val,$where)</b></font></p>
1851 <font>Allows you to store a clob (in $val) into $table into $column in a row at $where.
1852 Similar to UpdateBlob (see above), but for Character Large OBjects.
1853 </font><p><font> Usage:
1854 </font></p><pre><font> # for oracle<br> $conn-&gt;Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, empty_clob())');<br> $conn-&gt;UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');<br> <br> # non oracle databases<br> $conn-&gt;Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');<br> $conn-&gt;UpdateBlob('clobtable','clobcol',$clobvalue,'id=1');<br></font></pre>
1855 <p><font><b>UpdateBlobFile<a name="updateblobfile"></a>($table,$column,$path,$where,$blobtype='BLOB')</b></font></p>
1856 <p><font>Similar to UpdateBlob, except that we pass in a file path to where the blob
1857 resides.
1858 </font></p><p><font>For PostgreSQL, if you are using blob oid's, use this interface. This interface
1859 does not support bytea fields.
1860 </font></p><p><font>Returns true if successful, false otherwise.
1861 </font></p><p><font><b>BlobEncode<a name="blobencode" id="blobencode"></a>($blob)</b>
1862 </font></p><p><font>Some databases require blob's to be encoded manually before upload. Note if
1863 you use UpdateBlob( ) or UpdateBlobFile( ) the conversion is done automatically
1864 for you and you do not have to call this function. For PostgreSQL, currently,
1865 BlobEncode() can only be used for bytea fields.
1866 </font></p><p><font>Returns the encoded blob value.
1867 </font></p><p><font>Note that there is a connection property called <em>blobEncodeType</em> which
1868 has 3 legal values:
1869 </font></p><p><font>false - no need to perform encoding or decoding.<br>
1870 'I' - blob encoding required, and returned encoded blob is a numeric value
1871 (no need to quote).<br>
1872 'C' - blob encoding required, and returned encoded blob is a character value
1873 (requires quoting).
1874 </font></p><p><font>This is purely for documentation purposes, so that programs that accept multiple
1875 database drivers know what is the right thing to do when processing blobs.
1876 </font></p><p><font><strong>BlobDecode<a name="blobdecode"></a>($blob, $maxblobsize = false)</strong>
1877 </font></p><p><font>Some databases require blob's to be decoded manually after doing a select statement.
1878 If the database does not require decoding, then this function will return
1879 the blob unchanged. Currently BlobDecode is only required for one database,
1880 PostgreSQL, and only if you are using blob oid's (if you are using bytea fields,
1881 we auto-decode for you).</font> The default maxblobsize is set in $connection-&gt;maxblobsize, which
1882 is set to 256K in adodb 4.54. </p><p>
1883 In ADOdb 4.54 and later, the blob is the return value. In earlier versions, the blob data is sent to stdout.</p><font>
1884 </font><p></p><pre><font>$rs = $db-&gt;Execute("select bloboid from postgres_table where id=$key");<br>$blob = $db-&gt;BlobDecode( reset($rs-&gt;fields) );</font></pre>
1885 <p><font><b>Replace<a name="replace"></a>($table, $arrFields, $keyCols,$autoQuote=false)</b></font></p>
1886 <p><font>Try to update a record, and if the record is not found, an insert statement
1887 is generated and executed. Returns 0 on failure, 1 if update statement worked,
1888 2 if no record was found and the insert was executed successfully. This differs
1889 from MySQL's replace which deletes the record and inserts a new record. This
1890 also means you cannot update the primary key. The only exception to this is
1891 Interbase and its derivitives, which uses delete and insert because of some
1892 Interbase API limitations.
1893 </font></p><p><font>The parameters are $table which is the table name, the $arrFields which is an
1894 associative array where the keys are the field names, and $keyCols is the name
1895 of the primary key, or an array of field names if it is a compound key. If
1896 $autoQuote is set to true, then Replace() will quote all values that are non-numeric;
1897 auto-quoting will not quote nulls. Note that auto-quoting will not work if
1898 you use SQL functions or operators.
1899 </font></p><p><font>Examples:
1900 </font></p><pre><font># single field primary key<br>$ret = $db-&gt;Replace('atable', <br> array('id'=&gt;1000,'firstname'=&gt;'Harun','lastname'=&gt;'Al-Rashid'),<br> 'id',$autoquote = true); <br># generates UPDATE atable SET firstname='Harun',lastname='Al-Rashid' WHERE id=1000<br># or INSERT INTO atable (id,firstname,lastname) VALUES (1000,'Harun','Al-Rashid')<br><br># compound key<br>$ret = $db-&gt;Replace('atable2', <br> array('firstname'=&gt;'Harun','lastname'=&gt;'Al-Rashid', 'age' =&gt; 33, 'birthday' =&gt; 'null'),<br> array('lastname','firstname'),<br> $autoquote = true);<br><br># no auto-quoting<br>$ret = $db-&gt;Replace('atable2', <br> array('firstname'=&gt;"'Harun'",'lastname'=&gt;"'Al-Rashid'", 'age' =&gt; 'null'),<br> array('lastname','firstname')); <br></font></pre>
1901 <p><font><b>AutoExecute<a name="autoexecute"></a>($table, $arrFields, $mode, $where=false, $forceUpdate=true,$magicq=false)</b></font></p>
1902 <p>Since ADOdb 4.56, you can automatically generate and execute INSERTs and UPDATEs on a given table with this
1903 function, which is a wrapper for GetInsertSQL() and GetUpdateSQL().
1904 <p>AutoExecute() inserts or updates $table given an array of $arrFields, where the keys are the field names and the array values are the
1905 field values to store. Note that there is some overhead because the table is first queried to extract key information
1906 before the SQL is generated. We generate an INSERT or UPDATE based on $mode (see below).
1907 <p>
1908 Legal values for $mode are
1909 <ul>
1910 <li>'INSERT' or 1 or DB_AUTOQUERY_INSERT
1911 <li>'UPDATE' or 2 or DB_AUTOQUERY_UPDATE
1912 </ul>
1913 <p>You have to define the constants DB_AUTOQUERY_UPDATE and DB_AUTOQUERY_INSERT yourself or include adodb-pear.inc.php.
1914 <p>The $where clause is required if $mode == 'UPDATE'. If $forceUpdate=false then we will query the
1915 database first and check if the field value returned by the query matches the current field value; only if they differ do we update that field.
1916 <p>Returns true on success, false on error.
1917 <p>An example of its use is:
1918 <pre>
1919 $record["firstName"] = "Carol";
1920 $record["lasTname"] = "Smith";
1921 $conn->AutoExecute($table,$record,'INSERT');
1922 # executes <i>"INSERT INTO $table (firstName,lasTname) values ('Carol',Smith')"</i>;
1923
1924 $record["firstName"] = "Carol";
1925 $record["lasTname"] = "Jones";
1926 $conn->AutoExecute($table,$record,'UPDATE', "lastname like 'Sm%'");
1927 # executes <i>"UPDATE $table SET firstName='Carol',lasTname='Jones' WHERE lastname like 'Sm%'"</i>;
1928 </pre>
1929 <p>Note: One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated. If $arrFields
1930 contains keys that are invalid field names for $table, they are ignored. There is some overhead in doing this as we have to
1931 query the database to get the field names, but given that you are not directly coding the SQL yourself, you probably aren't interested in
1932 speed at all, but convenience.
1933 <p>Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called.
1934 <p><font><b>GetUpdateSQL<a name="getupdatesql"></a>(&amp;$rs, $arrFields, $forceUpdate=false,$magicq=false, $force=null)</b></font></p>
1935 <p><font>Generate SQL to update a table given a recordset $rs, and the modified fields
1936 of the array $arrFields (which must be an associative array holding the column
1937 names and the new values) are compared with the current recordset. If $forceUpdate
1938 is true, then we also generate the SQL even if $arrFields is identical to
1939 $rs-&gt;fields. Requires the recordset to be associative. $magicq is used
1940 to indicate whether magic quotes are enabled (see qstr()). The field names in the array
1941 are case-insensitive.</font></p>
1942 <font> </font><p><font>Since 4.52, we allow you to pass the $force type parameter, and this overrides the <a href="#ADODB_FORCE_TYPE">$ADODB_FORCE_TYPE</a>
1943 global variable.
1944 <p>Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called.
1945 </font></p><p><font><b>GetInsertSQL<a name="getinsertsql"></a>(&amp;$rs, $arrFields,$magicq=false,$force_type=false)</b></font></p>
1946 <p><font>Generate SQL to insert into a table given a recordset $rs. Requires the query
1947 to be associative. $magicq is used to indicate whether magic quotes are enabled
1948 (for qstr()). The field names in the array are case-insensitive.</font></p>
1949 <p>
1950 <font> Since 2.42, you can pass a table name instead of a recordset into
1951 GetInsertSQL (in $rs), and it will generate an insert statement for that table.
1952 </font></p><p><font>Since 4.52, we allow you to pass the $force_type parameter, and this overrides the <a href="#ADODB_FORCE_TYPE">$ADODB_FORCE_TYPE</a>
1953 global variable.
1954 <p>Since 4.62, the table name to be used can be overridden by setting $rs->tableName before AutoExecute(), GetInsertSQL() or GetUpdateSQL() is called.
1955 </font></p><p><font><b>PageExecute<a name="pageexecute"></a>($sql, $nrows, $page, $inputarr=false)</b>
1956 </font></p><p><font>Used for pagination of recordset. $page is 1-based. See <a href="#ex8">Example
1957 8</a>.</font></p>
1958
1959 <p><font><b>CachePageExecute<a name="cachepageexecute"></a>($secs2cache,
1960 $sql, $nrows, $page, $inputarr=false)</b> </font></p>
1961 <p><font>Used for pagination of recordset. $page is 1-based. See
1962 <a href="#ex8">Example 8</a>. Caching version of PageExecute.</font></p>
1963 <font>
1964 </font><p></p>
1965 <p><font><b>Close<a name="close"></a>( )</b></font></p>
1966 <p><font>Close the database connection. PHP4 proudly states that we no longer have to
1967 clean up at the end of the connection because the reference counting mechanism
1968 of PHP4 will automatically clean up for us.</font></p>
1969 <font> </font><p><font><b>StartTrans<a name="starttrans"></a>( )</b></font></p>
1970 <font> </font><p><font>Start a monitored transaction. As SQL statements are executed, ADOdb will monitor
1971 for SQL errors, and if any are detected, when CompleteTrans() is called, we auto-rollback.
1972 </font></p><p>
1973 <font> </font></p><p><font> To understand why StartTrans() is superior to BeginTrans(),
1974 let us examine a few ways of using BeginTrans().
1975 The following is the wrong way to use transactions:
1976 </font></p><pre><font>$DB-&gt;BeginTrans();<br>$DB-&gt;Execute("update table1 set val=$val1 where id=$id");<br>$DB-&gt;Execute("update table2 set val=$val2 where id=$id");<br>$DB-&gt;CommitTrans();<br></font></pre>
1977 <p><font>because you perform no error checking. It is possible to update table1 and
1978 for the update on table2 to fail. Here is a better way:
1979 </font></p><pre><font>$DB-&gt;BeginTrans();<br>$ok = $DB-&gt;Execute("update table1 set val=$val1 where id=$id");<br>if ($ok) $ok = $DB-&gt;Execute("update table2 set val=$val2 where id=$id");<br>if ($ok) $DB-&gt;CommitTrans();<br>else $DB-&gt;RollbackTrans();<br></font></pre>
1980 <p><font>Another way is (since ADOdb 2.0):
1981 </font></p><pre><font>$DB-&gt;BeginTrans();<br>$ok = $DB-&gt;Execute("update table1 set val=$val1 where id=$id");<br>if ($ok) $ok = $DB-&gt;Execute("update table2 set val=$val2 where id=$id");<br>$DB-&gt;CommitTrans($ok);<br></font></pre>
1982 <p><font> Now it is a headache monitoring $ok all over the place. StartTrans() is an
1983 improvement because it monitors all SQL errors for you. This is particularly
1984 useful if you are calling black-box functions in which SQL queries might be executed.
1985 Also all BeginTrans, CommitTrans and RollbackTrans calls inside a StartTrans block
1986 will be disabled, so even if the black box function does a commit, it will be ignored.
1987 </font></p><pre><font>$DB-&gt;StartTrans();<br>CallBlackBox();<br>$DB-&gt;Execute("update table1 set val=$val1 where id=$id");<br>$DB-&gt;Execute("update table2 set val=$val2 where id=$id");<br>$DB-&gt;CompleteTrans();<br></font></pre>
1988 <p><font>Note that a StartTrans blocks are nestable, the inner blocks are ignored.
1989 </font></p><p><font><b>CompleteTrans<a name="completetrans"></a>($autoComplete=true)</b></font></p>
1990 <font> </font><p><font>Complete a transaction called with StartTrans(). This function monitors
1991 for SQL errors, and will commit if no errors have occured, otherwise it will rollback.
1992 Returns true on commit, false on rollback. If the parameter $autoComplete is true
1993 monitor sql errors and commit and rollback as appropriate. Set $autoComplete to false
1994 to force rollback even if no SQL error detected.
1995 </font></p><p><font><b>FailTrans<a name="failtrans"></a>( )</b></font></p>
1996 <font> </font><p><font>Fail a transaction started with StartTrans(). The rollback will only occur when
1997 CompleteTrans() is called.
1998 </font></p><p><font><b>HasFailedTrans<a name="hasfailedtrans"></a>( )</b></font></p>
1999 <font> </font><p><font>Check whether smart transaction has failed,
2000 eg. returns true if there was an error in SQL execution or FailTrans() was called.
2001 If not within smart transaction, returns false.
2002 </font></p><p><font><b>BeginTrans<a name="begintrans"></a>( )</b></font></p>
2003 <p><font>Begin a transaction. Turns off autoCommit. Returns true if successful. Some
2004 databases will always return false if transaction support is not available.
2005 Any open transactions will be rolled back when the connection is closed. Among the
2006 databases that support transactions are Oracle, PostgreSQL, Interbase, MSSQL, certain
2007 versions of MySQL, DB2, Informix, Sybase, etc.</font></p>
2008 <font> </font><p><font>Note that <a href="#starttrans">StartTrans()</a> and CompleteTrans() is a superior method of
2009 handling transactions, available since ADOdb 3.40. For a explanation, see the <a href="#starttrans">StartTrans()</a> documentation.
2010
2011 </font></p><p><font>You can also use the ADOdb <a href="#errorhandling">error handler</a> to die
2012 and rollback your transactions for you transparently. Some buggy database extensions
2013 are known to commit all outstanding tranasactions, so you might want to explicitly
2014 do a $DB-&gt;RollbackTrans() in your error handler for safety.
2015 </font></p><h4><font>Detecting Transactions</font></h4>
2016 <font> </font><p><font>Since ADOdb 2.50, you are able to detect when you are inside a transaction. Check
2017 that $connection-&gt;transCnt &gt; 0. This variable is incremented whenever BeginTrans() is called,
2018 and decremented whenever RollbackTrans() or CommitTrans() is called.
2019 </font></p><p><font><b>CommitTrans<a name="committrans"></a>($ok=true)</b></font></p>
2020 <p><font>End a transaction successfully. Returns true if successful. If the database
2021 does not support transactions, will return true also as data is always committed.
2022 </font></p>
2023 <p><font>If you pass the parameter $ok=false, the data is rolled back. See example in
2024 BeginTrans().</font></p>
2025 <p><font><b>RollbackTrans<a name="rollbacktrans"></a>( )</b></font></p>
2026 <p><font>End a transaction, rollback all changes. Returns true if successful. If the
2027 database does not support transactions, will return false as data is never rollbacked.
2028 </font></p>
2029 <font>
2030 </font><p><font><b>GetAssoc<a name="getassoc1"></a>($sql,$inputarr=false,$force_array=false,$first2cols=false)</b></font></p>
2031 <p><font>Returns an associative array for the given query $sql with optional bind parameters
2032 in $inputarr. If the number of columns returned is greater to two, a 2-dimensional
2033 array is returned, with the first column of the recordset becomes the keys
2034 to the rest of the rows. If the columns is equal to two, a 1-dimensional array
2035 is created, where the the keys directly map to the values (unless $force_array
2036 is set to true, when an array is created for each value).
2037 </font></p><p><font> Examples:<a name="getassocex"></a></font></p>
2038
2039 <p><font>We have the following data in a recordset:</font></p>
2040 <p><font>row1: Apple, Fruit, Edible<br>
2041 row2: Cactus, Plant, Inedible<br>
2042 row3: Rose, Flower, Edible</font></p>
2043 <p><font>GetAssoc will generate the following 2-dimensional associative
2044 array:</font></p>
2045 <p><font>Apple =&gt; array[Fruit, Edible]<br>
2046 Cactus =&gt; array[Plant, Inedible]<br>
2047 Rose =&gt; array[Flower,Edible]</font></p>
2048 <p><font>If the dataset is:</font></p>
2049 <p><font>row1: Apple, Fruit<br>
2050 row2: Cactus, Plant<br>
2051 row3: Rose, Flower </font></p>
2052 <p><font>GetAssoc will generate the following 1-dimensional associative
2053 array (with $force_array==false):</font></p>
2054 <p><font>Apple =&gt; Fruit</font><br>
2055 Cactus=&gt;Plant<br>
2056 Rose=&gt;Flower </p>
2057 <p><font>The function returns:</font></p>
2058 <p><font>The associative array, or false if an error occurs.</font></p>
2059 <font>
2060 <p><b>CacheGetAssoc<a name="cachegetassoc"></a>([$secs2cache,] $sql,$inputarr=false,$force_array=false,$first2cols=false)</b></p>
2061 </font>
2062 <p><font>Caching version of <a href="#getassoc1">GetAssoc</a> function above.
2063 </font></p><p><font><b>GetOne<a name="getone"></a>($sql,$inputarr=false)</b></font></p>
2064 <p><font>Executes the SQL and returns the first field of the first row. The recordset
2065 and remaining rows are discarded for you automatically. If an error occur, false
2066 is returned.</font></p>
2067 <p><font><b>GetRow<a name="getrow"></a>($sql,$inputarr=false)</b></font></p>
2068 <p><font>Executes the SQL and returns the first row as an array. The recordset and remaining
2069 rows are discarded for you automatically. If an error occurs, false is returned.</font></p>
2070 <p><font><b>GetAll<a name="getall"></a>($sql,$inputarr=false)</b></font></p>
2071
2072 <p>Executes the SQL and returns the all the rows as a 2-dimensional
2073 array. The recordset is discarded for you automatically. If an error occurs,
2074 false is returned. <i>GetArray</i> is a synonym for <i>GetAll</i>.</p>
2075 <p><b>GetCol<a name="getcol"></a>($sql,$inputarr=false,$trim=false)</b></p>
2076
2077 <p><font>Executes the SQL and returns all elements of the first column as a
2078 1-dimensional array. The recordset is discarded for you automatically. If an error occurs,
2079 false is returned.</font></p>
2080 <p><font><b>CacheGetOne<a name="cachegetone"></a>([$secs2cache,]
2081 $sql,$inputarr=false), CacheGetRow<a name="cachegetrow"></a>([$secs2cache,] $sql,$inputarr=false), CacheGetAll<a name="cachegetall"></a>([$secs2cache,]
2082 $sql,$inputarr=false), CacheGetCol<a name="cachegetcol"></a>([$secs2cache,]
2083 $sql,$inputarr=false,$trim=false)</b></font></p>
2084 <font>
2085 </font><p><font>Similar to above Get* functions, except that the recordset is serialized and
2086 cached in the $ADODB_CACHE_DIR directory for $secs2cache seconds. Good for speeding
2087 up queries on rarely changing data. Note that the $secs2cache parameter is optional.
2088 If omitted, we use the value in $connection-&gt;cacheSecs (default is 3600 seconds,
2089 or 1 hour).</font></p>
2090 <p><font><b>Prepare<a name="prepare"></a>($sql )</b></font></p>
2091
2092 <p><font>Prepares (compiles) an SQL query for repeated execution. Bind parameters
2093 are denoted by ?, except for the oci8 driver, which uses the traditional Oracle :varname
2094 convention.
2095 </font></p>
2096 <p><font>Returns an array containing the original sql statement
2097 in the first array element; the remaining elements of the array are driver dependent.
2098 If there is an error, or we are emulating Prepare( ), we return the original
2099 $sql string. This is because all error-handling has been centralized in Execute(
2100 ).</font></p>
2101 <p><font>Prepare( ) cannot be used with functions that use SQL
2102 query rewriting techniques, e.g. PageExecute( ) and SelectLimit( ).</font></p>
2103 <p>Example:</p>
2104 <pre><font>$stmt = $DB-&gt;Prepare('insert into table (col1,col2) values (?,?)');<br>for ($i=0; $i &lt; $max; $i++)<br></font> $DB-&gt;<font>Execute($stmt,array((string) rand(), $i));<br></font></pre>
2105 <font>
2106 </font><p><font>Also see InParameter(), OutParameter() and PrepareSP() below. Only supported internally by interbase,
2107 oci8 and selected ODBC-based drivers, otherwise it is emulated. There is no
2108 performance advantage to using Prepare() with emulation.
2109 </font></p><p><font> Important: Due to limitations or bugs in PHP, if you are getting errors when
2110 you using prepared queries, try setting $ADODB_COUNTRECS = false before preparing.
2111 This behaviour has been observed with ODBC.
2112 </font></p><p><font><b>IfNull<a name="ifnull"></a>($field, $nullReplacementValue)</b></font></p>
2113 <p><font>Portable IFNULL function (NVL in Oracle). Returns a string that represents
2114 the function that checks whether a $field is null for the given database, and
2115 if null, change the value returned to $nullReplacementValue. Eg.</font></p>
2116 <pre><font>$sql = <font color="#993300">'SELECT '</font>.$db-&gt;IfNull('name', <font color="#993300">"'- unknown -'"</font>).<font color="#993300"> ' FROM table'</font>;</font></pre>
2117
2118 <p><font><b>length<a name="length"></a></b></font></p>
2119 <p><font>This is not a function, but a property. Some databases have "length" and others "len"
2120 as the function to measure the length of a string. To use this property:
2121 </font></p><pre><font> $sql = <font color="#993300">"SELECT "</font>.$db-&gt;length.<font color="#993300">"(field) from table"</font>;<br> $rs = $db-&gt;Execute($sql);<br></font></pre>
2122
2123 <p><font><b>random<a name="random"></a></b></font></p>
2124 <p><font>This is not a function, but a property. This is a string that holds the sql to
2125 generate a random number between 0.0 and 1.0 inclusive.
2126
2127 </font></p><p><font><b>substr<a name="substr"></a></b></font></p>
2128 <p><font>This is not a function, but a property. Some databases have "substr" and others "substring"
2129 as the function to retrieve a sub-string. To use this property:
2130 </font></p><pre><font> $sql = <font color="#993300">"SELECT "</font>.$db-&gt;substr.<font color="#993300">"(field, $offset, $length) from table"</font>;<br> $rs = $db-&gt;Execute($sql);<br></font></pre>
2131 <p><font>For all databases, the 1st parameter of <i>substr</i> is the field, the 2nd is the
2132 offset (1-based) to the beginning of the sub-string, and the 3rd is the length of the sub-string.
2133
2134
2135 </font></p><p><font><b>Param<a name="param"></a>($name)</b></font></p>
2136 <p><font>Generates a bind placeholder portably. For most databases, the bind placeholder
2137 is "?". However some databases use named bind parameters such as Oracle, eg
2138 ":somevar". This allows us to portably define an SQL statement with bind parameters:
2139 </font></p><pre><font>$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>;<br><font color="#006600"># generates 'insert into table (col1,col2) values (?,?)'<br># or 'insert into table (col1,col2) values (:a,:b)</font>'<br>$stmt = $DB-&gt;Prepare($sql);<br>$stmt = $DB-&gt;Execute($stmt,array('one','two'));<br></font></pre>
2140 <font> </font>
2141 <p></p>
2142 <p><font><b>PrepareSP</b><b><a name="preparesp"></a></b><b>($sql,
2143 $cursor=false )</b></font></p>
2144 <p><font>When calling stored procedures in mssql and oci8 (oracle),
2145 and you might want to directly bind to parameters that return values, or
2146 for special LOB handling. PrepareSP() allows you to do so. </font></p>
2147 <p><font>Returns the same array or $sql string as Prepare( )
2148 above. If you do not need to bind to return values, you should use Prepare(
2149 ) instead.</font></p>
2150 <p><font>The 2nd parameter, $cursor is not used except with oci8.
2151 Setting it to true will force OCINewCursor to be called; this is to support
2152 output REF CURSORs. </font></p>
2153 <p><font>For examples of usage of PrepareSP( ), see InParameter(
2154 ) below. </font></p>
2155 <p><font>Note: in the mssql driver, preparing stored procedures
2156 requires a special function call, mssql_init( ), which is called by this
2157 function. PrepareSP( ) is available in all other drivers, and is emulated
2158 by calling Prepare( ). </font></p>
2159 <p><font><b> InParameter<a name="inparameter"></a>($stmt, $var,
2160 $name, $maxLen = 4000, $type = false )</b></font></p>
2161 <font>Binds a PHP variable as input to a stored procedure variable.
2162 The parameter <i>$stmt</i> is the value returned by PrepareSP(), <i>$var</i> is
2163 the PHP variable you want to bind, $name is the name of the stored procedure
2164 variable. Optional is <i>$maxLen</i>, the maximum length of the data to bind,
2165 and $type which is database dependant. Consult <a href="http://php.net/mssql_bind">mssql_bind</a> and <a href="http://php.net/ocibindbyname">ocibindbyname</a> docs
2166 at php.net for more info on legal values for $type. </font>
2167 <p>
2168 <font>InParameter() is a wrapper function that calls Parameter()
2169 with $isOutput=false. The advantage of this function is that it is self-documenting,
2170 because the $isOutput parameter is no longer needed. Only for mssql and oci8
2171 currently. </font></p>
2172 <p><font>Here is an example using oci8: </font></p>
2173 <pre><font><font color="green"># For oracle, Prepare and PrepareSP are identical</font>
2174 $stmt = $db-&gt;PrepareSP(
2175 <font color="#993300">"declare RETVAL integer; <br> begin<br> :RETVAL := </font><font color="#993300">SP_RUNSOMETHING</font><font color="#993300">(:myid,:group);<br> end;"</font>);<br>$db-&gt;InParameter($stmt,$id,'myid');<br>$db-&gt;InParameter($stmt,$group,'group',64);<br>$db-&gt;OutParameter($stmt,$ret,'RETVAL');<br>$db-&gt;Execute($stmt);<br></font></pre>
2176 <p><font> The same example using mssql:</font></p>
2177 <font>
2178 </font><pre><font><font color="green"># @RETVAL = SP_RUNSOMETHING @myid,@group</font>
2179 $stmt = $db-&gt;PrepareSP(<font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font>); <br><font color="green"># note that the parameter name does not have @ in front!</font>
2180 $db-&gt;InParameter($stmt,$id,'myid');
2181 $db-&gt;InParameter($stmt,$group,'group',64);
2182 <font color="green"># return value in mssql - RETVAL is hard-coded name</font> <br>$db-&gt;OutParameter($stmt,$ret,'RETVAL');<br>$db-&gt;Execute($stmt); </font></pre>
2183
2184 <p><font>Note that the only difference between the oci8 and mssql implementations is $sql.</font></p>
2185 <p>
2186 <font> If $type parameter is set to false, in mssql, $type will be dynamicly determined
2187 based on the type of the PHP variable passed <font face="Courier New, Courier, mono">(string
2188 =&gt; SQLCHAR, boolean =&gt;SQLINT1, integer =&gt;SQLINT4 or float/double=&gt;SQLFLT8)</font>.
2189 </font></p><p><font>
2190 In oci8, $type can be set to OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File),
2191 OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID). To
2192 pass in a null, use<font face="Courier New, Courier, mono"> $db-&gt;Parameter($stmt,
2193 $null=null, 'param')</font>.
2194 </font></p><p><font><b> OutParameter<a name="outparameter"></a>($stmt, $var, $name,
2195 $maxLen = 4000, $type = false )</b></font></p>
2196 <font> Binds a PHP variable as output from a stored procedure variable. The parameter <i>$stmt</i>
2197 is the value returned by PrepareSP(), <i>$var</i> is the PHP variable you want to bind, <i>$name</i>
2198 is the name of the stored procedure variable. Optional is <i>$maxLen</i>, the maximum length of the
2199 data to bind, and <i>$type</i> which is database dependant.
2200 </font><p>
2201 <font> OutParameter() is a wrapper function that calls Parameter() with $isOutput=true.
2202 The advantage of this function is that it is self-documenting, because
2203 the $isOutput parameter is no longer needed. Only for mssql
2204 and oci8 currently.
2205 </font></p><p>
2206 <font>For an example, see <a href="#inparameter">InParameter</a>.
2207
2208 </font></p><p><font><b> Parameter<a name="parameter"></a>($stmt, $var, $name, $isOutput=false,
2209 $maxLen = 4000, $type = false )</b></font></p>
2210 <p><font>Note: This function is deprecated, because of the new InParameter() and OutParameter() functions.
2211 These are superior because they are self-documenting, unlike Parameter().
2212 </font></p><p><font>Adds a bind parameter suitable for return values or special data handling (eg.
2213 LOBs) after a statement has been prepared using PrepareSP(). Only for mssql
2214 and oci8 currently. The parameters are:<br>
2215 <br>
2216 $<i><b>stmt</b></i> Statement returned by Prepare() or PrepareSP().<br>
2217 $<i><b>var</b></i> PHP variable to bind to. Make sure you pre-initialize it!<br>
2218 $<i><b>name</b></i> Name of stored procedure variable name to bind to.<br>
2219 [$<i><b>isOutput</b></i>] Indicates direction of parameter 0/false=IN 1=OUT
2220 2= IN/OUT. This is ignored in oci8 as this driver auto-detects the direction.<br>
2221 [$<b>maxLen</b>] Maximum length of the parameter variable.<br>
2222 [$<b>type</b>] Consult <a href="http://php.net/mssql_bind">mssql_bind</a> and
2223 <a href="http://php.net/ocibindbyname">ocibindbyname</a> docs at php.net for
2224 more info on legal values for type.</font></p>
2225 <p><font>Lastly, in oci8, bind parameters can be reused without calling PrepareSP( )
2226 or Parameters again. This is not possible with mssql. An oci8 example:</font></p>
2227 <pre><font>$id = 0; $i = 0;<br>$stmt = $db-&gt;PrepareSP( <font color="#993300">"update table set val=:i where id=:id"</font>);<br>$db-&gt;Parameter($stmt,$id,'id');<br>$db-&gt;Parameter($stmt,$i, 'i');<br>for ($cnt=0; $cnt &lt; 1000; $cnt++) {<br> $id = $cnt; <br> $i = $cnt * $cnt; <font color="green"># works with oci8!</font>
2228 $db-&gt;Execute($stmt); <br>}</font></pre>
2229 <p><font><b>Bind<a name="bind"></a>($stmt, $var, $size=4001, $type=false, $name=false)</b></font></p>
2230
2231 <p><font>This is a low-level function supported only by the oci8
2232 driver. <b>Avoid using</b> unless you only want to support Oracle. The Parameter(
2233 ) function is the recommended way to go with bind variables.</font></p>
2234 <p><font>Bind( ) allows you to use bind variables in your sql
2235 statement. This binds a PHP variable to a name defined in an Oracle sql statement
2236 that was previously prepared using Prepare(). Oracle named variables begin with
2237 a colon, and ADOdb requires the named variables be called :0, :1, :2, :3, etc.
2238 The first invocation of Bind() will match :0, the second invocation will match
2239 :1, etc. Binding can provide 100% speedups for insert, select and update statements.
2240 </font></p>
2241 <p>The other variables, $size sets the buffer size for data storage, $type is
2242 the optional descriptor type OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File),
2243 OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID).
2244 Lastly, instead of using the default :0, :1, etc names, you can define your
2245 own bind-name using $name.
2246 </p><p><font>The following example shows 3 bind variables being used:
2247 p1, p2 and p3. These variables are bound to :0, :1 and :2.</font></p>
2248 <pre>$stmt = $DB-&gt;Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)");<br>$DB-&gt;Bind($stmt, $p1);<br>$DB-&gt;Bind($stmt, $p2);<br>$DB-&gt;Bind($stmt, $p3);<br>for ($i = 0; $i &lt; $max; $i++) { <br> $p1 = ?; $p2 = ?; $p3 = ?;<br> $DB-&gt;Execute($stmt);<br>}</pre>
2249 <p>You can also use named variables:</p>
2250 <pre>$stmt = $DB-&gt;Prepare("insert into table (col0, col1, col2) values (:name0, :name1, :name2)");<br>$DB-&gt;Bind($stmt, $p1, "name0");<br>$DB-&gt;Bind($stmt, $p2, "name1");<br>$DB-&gt;Bind($stmt, $p3, "name2");<br>for ($i = 0; $i &lt; $max; $i++) { <br> $p1 = ?; $p2 = ?; $p3 = ?;<br> $DB-&gt;Execute($stmt);<br>}</pre>
2251 <p><b>LogSQL($enable=true)<a name="logsql"></a></b></p>
2252 Call this method to install a SQL logging and timing function (using fnExecute).
2253 Then all SQL statements are logged into an adodb_logsql table in a database. If
2254 the adodb_logsql table does not exist, ADOdb will create the table if you have
2255 the appropriate permissions. Returns the previous logging value (true for enabled,
2256 false for disabled). Here are samples of the DDL for selected databases:
2257 <p>
2258 </p><pre> <b>mysql:</b>
2259 CREATE TABLE adodb_logsql (
2260 created datetime NOT NULL,
2261 sql0 varchar(250) NOT NULL,
2262 sql1 text NOT NULL,
2263 params text NOT NULL,
2264 tracer text NOT NULL,
2265 timer decimal(16,6) NOT NULL
2266 )
2267
2268 <b>postgres:</b>
2269 CREATE TABLE adodb_logsql (
2270 created timestamp NOT NULL,
2271 sql0 varchar(250) NOT NULL,
2272 sql1 text NOT NULL,
2273 params text NOT NULL,
2274 tracer text NOT NULL,
2275 timer decimal(16,6) NOT NULL
2276 )
2277
2278 <b>mssql:</b>
2279 CREATE TABLE adodb_logsql (
2280 created datetime NOT NULL,
2281 sql0 varchar(250) NOT NULL,
2282 sql1 varchar(4000) NOT NULL,
2283 params varchar(3000) NOT NULL,
2284 tracer varchar(500) NOT NULL,
2285 timer decimal(16,6) NOT NULL
2286 )
2287
2288 <b>oci8:</b>
2289 CREATE TABLE adodb_logsql (
2290 created date NOT NULL,
2291 sql0 varchar(250) NOT NULL,
2292 sql1 varchar(4000) NOT NULL,
2293 params varchar(4000),
2294 tracer varchar(4000),
2295 timer decimal(16,6) NOT NULL
2296 )
2297 </pre>
2298 Usage:
2299 <pre> $conn-&gt;LogSQL(); // turn on logging<br> :<br> $conn-&gt;Execute(...);<br> :<br> $conn-&gt;LogSQL(false); // turn off logging<br> <br> # output summary of SQL logging results<br> $perf = NewPerfMonitor($conn);<br> echo $perf-&gt;SuspiciousSQL();<br> echo $perf-&gt;ExpensiveSQL();<br></pre>
2300 <p>One limitation of logging is that rollback also prevents SQL from being logged.
2301 </p><p>
2302 If you prefer to use another name for the table used to store the SQL, you can override it by calling
2303 adodb_perf::table($tablename), where $tablename is the new table name (you will still need to manually
2304 create the table yourself). An example:
2305 </p><pre> include('adodb.inc.php');<br> include('adodb-perf.inc.php');<br> adodb_perf::table('my_logsql_table');<br></pre>
2306 Also see <a href="docs-perf.htm">Performance Monitor</a>.
2307 <p><font><b>fnExecute and fnCacheExecute properties<a name="fnexecute" id="fnexecute"></a></b></font></p>
2308 <p>These two properties allow you to define bottleneck functions for all sql statements
2309 processed by ADOdb. This allows you to perform statistical analysis and query-rewriting
2310 of your sql.
2311 </p><p><b>Examples of fnExecute</b></p>
2312 <p>Here is an example of using fnExecute, to count all cached queries and non-cached
2313 queries, you can do this:</p>
2314 <pre><font color="#006600"># $db is the connection object</font>
2315 function CountExecs($db, $sql, $inputarray)
2316 {
2317 global $EXECS;
2318
2319 if (!is_array(inputarray)) $EXECS++;
2320 <font color="#006600"># handle 2-dimensional input arrays</font>
2321 else if (is_array(reset($inputarray))) $EXECS += sizeof($inputarray);
2322 else $EXECS++;
2323 }
2324
2325 <font color="#006600"># $db is the connection object</font>
2326 function CountCachedExecs($db, $secs2cache, $sql, $inputarray)
2327 {<br>global $CACHED; $CACHED++;<br>}<br><br>$db = NewADOConnection('mysql');<br>$db-&gt;Connect(...);<br>$db-&gt;<strong>fnExecute</strong> = 'CountExecs';<br>$db-&gt;<strong>fnCacheExecute</strong> = 'CountCachedExecs';<br> :<br> :<br><font color="#006600"># After many sql statements:</font>`<br>printf("&lt;p&gt;Total queries=%d; total cached=%d&lt;/p&gt;",$EXECS+$CACHED, $CACHED);<br></pre>
2328 <p>The fnExecute function is called before the sql is parsed and executed, so
2329 you can perform a query rewrite. If you are passing in a prepared statement,
2330 then $sql is an array (see <a href="#prepare">Prepare</a>). The fnCacheExecute
2331 function is only called if the recordset returned was cached.<font>
2332 The function parameters match the Execute and CacheExecute functions respectively,
2333 except that $this (the connection object) is passed as the first parameter.</font></p>
2334 <p>Since ADOdb 3.91, the behaviour of fnExecute varies depending on whether the
2335 defined function returns a value. If it does not return a value, then the $sql
2336 is executed as before. This is useful for query rewriting or counting sql queries.
2337 </p><p> On the other hand, you might want to replace the Execute function with one
2338 of your own design. If this is the case, then have your function return a value.
2339 If a value is returned, that value is returned immediately, without any further
2340 processing. This is used internally by ADOdb to implement LogSQL() functionality.
2341 </p>
2342 <p>
2343 </p><hr />
2344 <h3><font>ADOConnection Utility Functions</font></h3>
2345 <p><font><b>BlankRecordSet<a name="blankrecordset"></a>([$queryid])</b></font></p>
2346 <p><font>No longer available - removed since 1.99.</font></p>
2347 <p><font><b>Concat<a name="concat"></a>($s1,$s2,....)</b></font></p>
2348 <p><font>Generates the sql string used to concatenate $s1, $s2, etc together. Uses the
2349 string in the concat_operator field to generate the concatenation. Override
2350 this function if a concatenation operator is not used, eg. MySQL.</font></p>
2351 <p><font>Returns the concatenated string.</font></p>
2352 <p><font><b>DBDate<a name="dbdate"></a>($date)</b></font></p>
2353 <p><font>Format the $<b>date</b> in the format the database accepts. This is used in
2354 INSERT/UPDATE statements; for SELECT statements, use <a href="#sqldate">SQLDate</a>.
2355 The $<b>date</b> parameter can be a Unix integer timestamp or an ISO format
2356 Y-m-d. Uses the fmtDate field, which holds the format to use. If null or false
2357 or '' is passed in, it will be converted to an SQL null.</font></p>
2358 <p><font>Returns the date as a quoted string.</font></p>
2359 <p><font><b>DBTimeStamp<a name="dbtimestamp"></a>($ts)</b></font></p>
2360 <p><font>Format the timestamp $<b>ts</b> in the format the database accepts; this can
2361 be a Unix integer timestamp or an ISO format Y-m-d H:i:s. Uses the fmtTimeStamp
2362 field, which holds the format to use. If null or false or '' is passed in, it
2363 will be converted to an SQL null.</font></p>
2364 <p><font>Returns the timestamp as a quoted string.</font></p>
2365 <p><font><b>qstr<a name="qstr"></a>($s,[$magic_quotes_enabled</b>=false]<b>)</b></font></p>
2366 <p><font>Quotes a string to be sent to the database. The $<b>magic_quotes_enabled</b>
2367 parameter may look funny, but the idea is if you are quoting a string extracted
2368 from a POST/GET variable, then pass get_magic_quotes_gpc() as the second parameter.
2369 This will ensure that the variable is not quoted twice, once by <i>qstr</i>
2370 and once by the <i>magic_quotes_gpc</i>.</font></p>
2371 <p><font>Eg.<font face="Courier New, Courier, mono"> $s = $db-&gt;qstr(HTTP_GET_VARS['name'],get_magic_quotes_gpc());</font></font></p>
2372 <p><font>Returns the quoted string.</font></p>
2373 <p><font><b>Quote<a name="quote"></a>($s)</b></font></p>
2374 <p><font>Quotes the string $s, escaping the database specific quote character as appropriate.
2375 Formerly checked magic quotes setting, but this was disabled since 3.31 for
2376 compatibility with PEAR DB.
2377 </font></p><p><font><b>Affected_Rows<a name="affected_rows"></a>( )</b></font></p>
2378 <p><font>Returns the number of rows affected by a update or delete statement. Returns
2379 false if function not supported.</font></p>
2380 <p><font>Not supported by interbase/firebird currently. </font></p>
2381 <p><font><b>Insert_ID<a name="inserted_id"></a>( )</b></font></p>
2382 <p><font>Returns the last autonumbering ID inserted. Returns false if function not supported.
2383 </font></p>
2384 <p><font>Only supported by databases that support auto-increment or object id's, such
2385 as PostgreSQL, MySQL and MS SQL Server currently. PostgreSQL returns the OID, which
2386 can change on a database reload.</font></p>
2387 <p><font><b>RowLock<a name="rowlock"></a>($table,$where)</b></font></p>
2388 <p><font>Lock a table row for the duration of a transaction. For example to lock record $id in table1:
2389 </font></p><pre><font> $DB-&gt;StartTrans();<br> $DB-&gt;RowLock("table1","rowid=$id");<br> $DB-&gt;Execute($sql1);<br> $DB-&gt;Execute($sql2);<br> $DB-&gt;CompleteTrans();<br></font></pre>
2390 <p><font>Supported in db2, interbase, informix, mssql, oci8, postgres, sybase.
2391 </font></p><p><font><b>MetaDatabases<a name="metadatabases"></a>()</b></font></p>
2392 <p><font>Returns a list of databases available on the server as an array. You have to
2393 connect to the server first. Only available for ODBC, MySQL and ADO.</font></p>
2394 <p><font><b>MetaTables<a name="metatables"></a>($ttype = false, $showSchema = false,
2395 $mask=false)</b></font></p>
2396 <p><font>Returns an array of tables and views for the current database as an array.
2397 The array should exclude system catalog tables if possible. To only show tables,
2398 use $db-&gt;MetaTables('TABLES'). To show only views, use $db-&gt;MetaTables('VIEWS').
2399 The $showSchema parameter currently works only for DB2, and when set to true,
2400 will add the schema name to the table, eg. "SCHEMA.TABLE". </font></p>
2401 <p><font>You can define a mask for matching. For example, setting $mask = 'TMP%' will
2402 match all tables that begin with 'TMP'. Currently only mssql, oci8, odbc_mssql
2403 and postgres* support $mask.
2404 </font></p><p><font><b>MetaColumns<a name="metacolumns"></a>($table,$notcasesensitive=true)</b></font></p>
2405 <p><font>Returns an array of ADOFieldObject's, one field object for every column of
2406 $table. A field object is a class instance with (name, type, max_length) defined.
2407 Currently Sybase does not recognise date types, and ADO cannot identify
2408 the correct data type (so we default to varchar).
2409 </font></p><p><font> The $notcasesensitive parameter determines whether we uppercase or lowercase the table name to normalize it
2410 (required for some databases). Does not work with MySQL ISAM tables.
2411 </font></p><p><font>For schema support, pass in the $table parameter, "$schema.$tablename". This is only
2412 supported for selected databases.
2413 </font></p><p><font><b>MetaColumnNames<a name="metacolumnames"></a>($table,$numericIndex=false)</b></font></p>
2414 <p><font>Returns an array of column names for $table. Since ADOdb 4.22, this is an associative array, with the
2415 keys in uppercase. Set $numericIndex=true if you want the old behaviour of numeric indexes (since 4.23).
2416 </font></p><p>
2417 <font>e.g. array('FIELD1' =&gt; 'Field1', 'FIELD2'=&gt;'Field2')
2418 </font></p><p>
2419 </p><p><font><b>MetaPrimaryKeys<a name="metaprimarykeys"></a>($table,
2420 $owner=false)</b></font>
2421 </p>
2422 <p><font>Returns an array containing column names that are the
2423 primary keys of $table. Supported by mysql, odbc (including db2, odbc_mssql,
2424 etc), mssql, postgres, interbase/firebird, oci8 currently. </font></p>
2425 <p><font>Views (and some tables) have primary keys, but sometimes this information is not available from the
2426 database. You can define a function ADODB_View_PrimaryKeys($databaseType, $database, $view, $owner) that
2427 should return an array containing the fields that make up the primary key. If that function exists,
2428 it will be called when MetaPrimaryKeys() cannot find a primary key for a table or view.
2429 </font></p><pre><font>// In this example: dbtype = 'oci8', $db = 'mydb', $view = 'dataView', $owner = false <br>function ADODB_View_PrimaryKeys($dbtype,$db,$view,$owner)<br>{<br> switch(strtoupper($view)) {<br> case 'DATAVIEW': return array('DATAID');<br> default: return false;<br> }<br>}<br><br>$db = NewADOConnection('oci8');<br>$db-&gt;Connect('localhost','root','','mydb'); <br>$db-&gt;MetaPrimaryKeys('dataView');<br></font></pre>
2430 <p><font><b>ServerInfo<a name="serverinfo" id="serverinfo"></a>()</b></font>
2431 </p>
2432 <p><font>Returns an array of containing two elements 'description'
2433 and 'version'. The 'description' element contains the string description of
2434 the database. The 'version' naturally holds the version number (which is also
2435 a string).</font></p>
2436 <p><font><b>MetaForeignKeys<a name="metaforeignkeys"></a>($table, $owner=false, $upper=false)</b>
2437 </font></p><p><font>Returns an associate array of foreign keys, or false if not supported. For
2438 example, if table employee has a foreign key where employee.deptkey points to
2439 dept_table.deptid, and employee.posn=posn_table.postionid and employee.poscategory=posn_table.category,
2440 then $conn-&gt;MetaForeignKeys('employee') will return
2441 </font></p><pre><font> array(<br> 'dept_table' =&gt; array('deptkey=deptid'),<br> 'posn_table' =&gt; array('posn=positionid','poscategory=category')<br> )<br></font></pre>
2442 <p><font>The optional schema or owner can be defined in $owner. If $upper is true, then
2443 the table names (array keys) are upper-cased.
2444 </font></p><hr />
2445 <h2><font>ADORecordSet<a name="adorecordset"></a></font></h2>
2446 <p><font>When an SQL statement successfully is executed by <font face="Courier New, Courier, mono">ADOConnection-&gt;Execute($sql),</font>an
2447 ADORecordSet object is returned. This object contains a virtual cursor so we
2448 can move from row to row, functions to obtain information about the columns
2449 and column types, and helper functions to deal with formating the results to
2450 show to the user.</font></p>
2451 <h3><font>ADORecordSet Fields</font></h3>
2452 <p><font><b>fields: </b>Array containing the current row. This is not associative, but
2453 is an indexed array from 0 to columns-1. See also the function <b><a href="#fields">Fields</a></b>,
2454 which behaves like an associative array.</font></p>
2455 <p><font><b>dataProvider</b>: The underlying mechanism used to connect to the database.
2456 Normally set to <b>native</b>, unless using <b>odbc</b> or <b>ado</b>.</font></p>
2457 <p><font><b>blobSize</b>: Maximum size of a char, string or varchar object before it
2458 is treated as a Blob (Blob's should be shown with textarea's). See the <a href="#metatype">MetaType</a>
2459 function.</font></p>
2460 <p><font><b>sql</b>: Holds the sql statement used to generate this record set.</font></p>
2461 <p><font><b>canSeek</b>: Set to true if Move( ) function works.</font></p>
2462 <p><font><b>EOF</b>: True if we have scrolled the cursor past the last record.</font></p>
2463 <h3><font>ADORecordSet Functions</font></h3>
2464 <p><font><b>ADORecordSet( )</b></font></p>
2465 <p><font>Constructer. Normally you never call this function yourself.</font></p>
2466 <p><font><b>GetAssoc<a name="getassoc"></a>([$force_array])</b></font></p>
2467 <p><font>Generates an associative array from the recordset. Note that is this function
2468 is also <a href="#getassoc1">available</a> in the connection object. More details
2469 can be found there.</font></p>
2470 <font> </font>
2471 <p><font><b>GetArray<a name="getarray"></a>([$number_of_rows])</b></font></p>
2472 <p><font>Generate a 2-dimensional array of records from the current
2473 cursor position, indexed from 0 to $number_of_rows - 1. If $number_of_rows
2474 is undefined, till EOF.</font></p>
2475 <p><font><b>GetRows<a name="getrows"></a>([$number_of_rows])</b></font></p>
2476 <font>Generate a 2-dimensional array of records from the current
2477 cursor position. Synonym for GetArray() for compatibility with Microsoft ADO. </font>
2478 <p><font> <b>GetMenu<a name="getmenu"></a>($name, [$default_str=''],
2479 [$blank1stItem=true], [$multiple_select=false], [$size=0], [$moreAttr=''])</b></font></p>
2480 <p><font>Generate a HTML menu (&lt;select&gt;&lt;option&gt;&lt;option&gt;&lt;/select&gt;).
2481 The first column of the recordset (fields[0]) will hold the string to display
2482 in the option tags. If the recordset has more than 1 column, the second column
2483 (fields[1]) is the value to send back to the web server.. The menu will be
2484 given the name $<i>name</i>. </font></p>
2485 <p><font> If $<i>default_str</i> is defined, then if $<i>default_str</i> ==
2486 fields[0], that field is selected. If $<i>blank1stItem</i> is true, the first
2487 option is empty. You can also set the first option strings by setting $blank1stItem
2488 = "$value:$text".</font></p>
2489 <p><font>$<i>Default_str</i> can be array for a multiple select
2490 listbox.</font></p>
2491 <p><font>To get a listbox, set the $<i>size</i> to a non-zero
2492 value (or pass $default_str as an array). If $<i>multiple_select</i> is true
2493 then a listbox will be generated with $<i>size</i> items (or if $size==0,
2494 then 5 items) visible, and we will return an array to a server. Lastly use
2495 $<i>moreAttr </i> to add additional attributes such as javascript or styles. </font></p>
2496 <p><font>Menu Example 1: <code>GetMenu('menu1','A',true)</code> will
2497 generate a menu:
2498 <select name="menu1"><option> </option><option value="1" selected="selected">A </option><option value="2">B </option><option value="3">C </option></select>
2499 for the data (A,1), (B,2), (C,3). Also see <a href="#ex5">example 5</a>.</font></p>
2500 <p><font>Menu Example 2: For the same data, <code>GetMenu('menu1',array('A','B'),false)</code> will
2501 generate a menu with both A and B selected: <br>
2502 <select name="menu1" multiple="multiple" size="3"><option value="1" selected="selected">A </option><option value="2" selected="selected">B </option><option value="3">C </option></select>
2503 </font></p>
2504 <p><font> <b>GetMenu2<a name="getmenu2"></a>($name, [$default_str=''],
2505 [$blank1stItem=true], [$multiple_select=false], [$size=0], [$moreAttr=''])</b></font></p>
2506 <p><font>This is nearly identical to GetMenu, except that the
2507 $<i>default_str</i> is matched to fields[1] (the option values).</font></p>
2508 <p><font>Menu Example 3: Given the data in menu example 2, <code>GetMenu2('menu1',array('1','2'),false)</code> will
2509 generate a menu with both A and B selected in menu example 2, but this time
2510 the selection is based on the 2nd column, which holds the values to return
2511 to the Web server. </font></p>
2512 <p><font><b>UserDate<a name="userdate"></a>($str, [$fmt])</b></font></p>
2513 <p><font>Converts the date string $<i>str</i> to another format.
2514 The date format is Y-m-d, or Unix timestamp format. The default $<i>fmt</i> is
2515 Y-m-d.</font></p>
2516 <p><font><b>UserTimeStamp<a name="usertimestamp"></a>($str, [$fmt])</b></font></p>
2517 <p><font>Converts the timestamp string $<b>str</b> to another
2518 format. The timestamp format is Y-m-d H:i:s, as in '2002-02-28 23:00:12',
2519 or Unix timestamp format. UserTimeStamp calls UnixTimeStamp to parse $<i>str</i>,
2520 and $<i>fmt</i> defaults to Y-m-d H:i:s if not defined. </font></p>
2521 <p><font><b>UnixDate<a name="unixdate"></a>($str)</b></font></p>
2522 <p><font>Parses the date string $<b>str</b> and returns it in
2523 unix mktime format (eg. a number indicating the seconds after January 1st,
2524 1970). Expects the date to be in Y-m-d H:i:s format, except for Sybase and
2525 Microsoft SQL Server, where M d Y is also accepted (the 3 letter month strings
2526 are controlled by a global array, which might need localisation).</font></p>
2527 <p><font>This function is available in both ADORecordSet and
2528 ADOConnection since 1.91.</font></p>
2529 <p><font><b>UnixTimeStamp<a name="unixtimestamp"></a>($str)</b></font></p>
2530 <p><font>Parses the timestamp string $<b>str</b> and returns
2531 it in unix mktime format (eg. a number indicating the seconds after January
2532 1st, 1970). Expects the date to be in "Y-m-d, H:i:s" (1970-12-24, 00:00:00)
2533 or "Y-m-d H:i:s" (1970-12-24 00:00:00) or "YmdHis" (19701225000000) format,
2534 except for Sybase and Microsoft SQL Server, where "M d Y h:i:sA" (Dec 25
2535 1970 00:00:00AM) is also accepted (the 3 letter month strings are controlled
2536 by a global array, which might need localisation).</font></p>
2537 <font>
2538 </font><p><font>This function is available in both ADORecordSet
2539 and ADOConnection since 1.91. </font></p>
2540 <p><font><b>OffsetDate<a name="offsetdate"></a>($dayFraction,
2541 $basedate=false)</b></font></p>
2542 <p><font>Returns a string with the native SQL functions to calculate
2543 future and past dates based on $basedate in a portable fashion. If $basedate
2544 is not defined, then the current date (at 12 midnight) is used. Returns the
2545 SQL string that performs the calculation when passed to Execute(). </font></p>
2546 <p><font>For example, in Oracle, to find the date and time that
2547 is 2.5 days from today, you can use:</font></p>
2548 <pre><font># get date one week from now<br>$fld = $conn-&gt;OffsetDate(7); // returns "(trunc(sysdate)+7")</font></pre>
2549 <pre><font># get date and time that is 60 hours from current date and time<br>$fld = $conn-&gt;OffsetDate(2.5, $conn-&gt;sysTimeStamp); // returns "(sysdate+2.5)"<br><br>$conn-&gt;Execute("UPDATE TABLE SET dodate=$fld WHERE ID=$id");</font></pre>
2550 <p><font> This function is available for mysql, mssql, oracle, oci8 and postgresql drivers
2551 since 2.13. It might work with other drivers provided they allow performing
2552 numeric day arithmetic on dates.</font></p>
2553 <font> </font>
2554 <p><font><b>SQLDate<a name="sqldate"></a>($dateFormat, $basedate=false)</b></font></p>
2555 <font>Returns a string which contains the native SQL functions
2556 to format a date or date column $basedate. This is used in SELECT statements.
2557 For INSERT/UPDATE statements, use <a href="#dbdate">DBDate</a>. It uses a case-sensitive
2558 $dateFormat, which supports: </font>
2559 <pre><font>
2560 Y: 4-digit Year
2561 Q: Quarter (1-4)
2562 M: Month (Jan-Dec)
2563 m: Month (01-12)
2564 d: Day (01-31)
2565 H: Hour (00-23)
2566 h: Hour (1-12)
2567 i: Minute (00-59)
2568 s: Second (00-60)
2569 A: AM/PM indicator
2570 w: day of week (0-6 or 1-7 depending on DB)
2571 l: day of week (as string - lowercase L)
2572 W: week in year (0..53 for MySQL, 1..53 for PostgreSQL and Oracle)
2573 </font></pre>
2574 <p><font>All other characters are treated as strings. You can
2575 also use \ to escape characters. Available on selected databases, including
2576 mysql, postgresql, mssql, oci8 and DB2. </font></p>
2577 <p><font>This is useful in writing portable sql statements that
2578 GROUP BY on dates. For example to display total cost of goods sold broken
2579 by quarter (dates are stored in a field called postdate): </font></p>
2580 <pre><font> $sqlfn = $db-&gt;SQLDate('Y-\QQ','postdate'); # get sql that formats postdate to output 2002-Q1<br> $sql = "SELECT $sqlfn,SUM(cogs) FROM table GROUP BY $sqlfn ORDER BY 1 desc";<br> </font></pre>
2581 <p><font><b>MoveNext<a name="movenext"></a>( )</b></font></p>
2582 <p><font>Move the internal cursor to the next row. The <i>$this-&gt;fields</i> array
2583 is automatically updated. Returns false if unable to do so (normally because
2584 EOF has been reached), otherwise true. </font></p>
2585 <p><font> If EOF is reached, then the $this-&gt;fields array
2586 is set to false (this was only implemented consistently in ADOdb 3.30). For
2587 the pre-3.30 behaviour of $this-&gt;fields (at EOF), set the global variable
2588 $ADODB_COMPAT_FETCH = true.</font></p>
2589 <p><font>Example:</font></p>
2590 <pre><font>$rs = $db-&gt;Execute($sql);<br>if ($rs) <br> while (!$rs-&gt;EOF) {<br> ProcessArray($rs-&gt;fields); <br> $rs-&gt;MoveNext();<br> } </font></pre>
2591 <p><font><b>Move<a name="move"></a>($to)</b></font></p>
2592 <p><font>Moves the internal cursor to a specific row $<b>to</b>.
2593 Rows are zero-based eg. 0 is the first row. The <b>fields</b> array is automatically
2594 updated. For databases that do not support scrolling internally, ADOdb will
2595 simulate forward scrolling. Some databases do not support backward scrolling.
2596 If the $<b>to</b> position is after the EOF, $<b>to</b> will move to the
2597 end of the RecordSet for most databases. Some obscure databases using odbc
2598 might not behave this way.</font></p>
2599 <p><font>Note: This function uses <i>absolute positioning</i>,
2600 unlike Microsoft's ADO.</font></p>
2601 <p><font>Returns true or false. If false, the internal cursor
2602 is not moved in most implementations, so AbsolutePosition( ) will return
2603 the last cursor position before the Move( ). </font></p>
2604 <p><font><b>MoveFirst<a name="movefirst"></a>()</b></font></p>
2605 <p><font>Internally calls Move(0). Note that some databases do
2606 not support this function.</font></p>
2607 <p><font><b>MoveLast<a name="movelast"></a>()</b></font></p>
2608 <p><font>Internally calls Move(RecordCount()-1). Note that some
2609 databases do not support this function.</font></p>
2610 <p><font><b>GetRowAssoc</b><a name="getrowassoc"></a>($toUpper=true)</font></p>
2611 <p><font>Returns an associative array containing the current
2612 row. The keys to the array are the column names. The column names are upper-cased
2613 for easy access. To get the next row, you will still need to call MoveNext(). </font></p>
2614 <p><font>For example:<br>
2615 Array ( [ID] =&gt; 1 [FIRSTNAME] =&gt; Caroline [LASTNAME] =&gt; Miranda [CREATED]
2616 =&gt; 2001-07-05 ) </font></p>
2617 <p><font>Note: do not use GetRowAssoc() with $ADODB_FETCH_MODE
2618 = ADODB_FETCH_ASSOC. Because they have the same functionality, they will
2619 interfere with each other.</font></p>
2620 <font>
2621 </font><p><font><b>AbsolutePage<a name="absolutepage"></a>($page=-1) </b></font></p>
2622 <p><font>Returns the current page. Requires PageExecute()/CachePageExecute() to be called.
2623 See <a href="#ex8">Example 8</a>.</font></p>
2624 <font>
2625 <p><b>AtFirstPage<a name="atfirstpage">($status='')</a></b></p>
2626 <p>Returns true if at first page (1-based). Requires PageExecute()/CachePageExecute()
2627 to be called. See <a href="#ex8">Example 8</a>.</p>
2628 <p><b>AtLastPage<a name="atlastpage">($status='')</a></b></p>
2629 <p>Returns true if at last page (1-based). Requires PageExecute()/CachePageExecute()
2630 to be called. See <a href="#ex8">Example 8</a>.</p>
2631 <p><b>Fields</b><a name="fields"></a>(<b>$colname</b>)</p>
2632 <p>Returns the value of the associated column $<b>colname</b> for the current
2633 row. The column name is case-insensitive.</p>
2634 <p>This is a convenience function. For higher performance, use <a href="#adodb_fetch_mode">$ADODB_FETCH_MODE</a>. </p>
2635 <p><b>FetchRow</b><a name="fetchrow"></a>()</p>
2636 </font><p><font>Returns array containing current row, or false
2637 if EOF. FetchRow( ) internally moves to the next record after returning the
2638 current row. </font></p>
2639 <p><font>Warning: Do not mix using FetchRow() with MoveNext().</font></p>
2640 <p><font>Usage:</font></p>
2641 <pre><font>$rs = $db-&gt;Execute($sql);<br>if ($rs)<br> while ($arr = $rs-&gt;FetchRow()) {<br> &nbsp;&nbsp;# process $arr <br> }</font></pre>
2642 <p><font><b>FetchInto</b><a name="fetchinto"></a>(<b>&amp;$array</b>)</font></p>
2643 <p><font> Sets $array to the current row. Returns PEAR_Error
2644 object if EOF, 1 if ok (DB_OK constant). If PEAR is undefined, false is returned
2645 when EOF. FetchInto( ) internally moves to the next record after returning
2646 the current row. </font></p>
2647 <p><font> FetchRow() is easier to use. See above.</font></p>
2648 <font> </font>
2649 <p><font><b>FetchField<a name="fetchfield"></a>($column_number)</b></font></p>
2650 <p><font>Returns an object containing the <b>name</b>, <b>type</b> and <b>max_length</b> of
2651 the associated field. If the max_length cannot be determined reliably, it
2652 will be set to -1. The column numbers are zero-based. See <a href="#ex2">example
2653 2.</a></font></p>
2654 <p><font><b>FieldCount<a name="fieldcount"></a>( )</b></font></p>
2655 <p><font>Returns the number of fields (columns) in the record
2656 set.</font></p>
2657 <p><font><b>RecordCount<a name="recordcount"></a>( )</b></font></p>
2658 <p><font>Returns the number of rows in the record set. If the
2659 number of records returned cannot be determined from the database driver
2660 API, we will buffer all rows and return a count of the rows after all the
2661 records have been retrieved. This buffering can be disabled (for performance
2662 reasons) by setting the global variable $ADODB_COUNTRECS = false. When disabled,
2663 RecordCount( ) will return -1 for certain databases. See the supported databases
2664 list above for more details. </font></p>
2665 <p><font> RowCount is a synonym for RecordCount.</font></p>
2666 <p><font><b>PO_RecordCount<a name="po_recordcount"></a>($table,
2667 $where)</b></font></p>
2668 <p><font>Returns the number of rows in the record set. If the
2669 database does not support this, it will perform a SELECT COUNT(*) on the
2670 table $table, with the given $where condition to return an estimate of the
2671 recordset size.</font></p>
2672 <p><font>$numrows = $rs-&gt;PO_RecordCount("articles_table", "group=$group");</font></p>
2673 <font><b> NextRecordSet<a name="nextrecordset" id="nextrecordset"></a>()</b> </font>
2674 <p><font>For databases that allow multiple recordsets to be returned
2675 in one query, this function allows you to switch to the next recordset. Currently
2676 only supported by mssql driver.</font></p>
2677 <pre><font>$rs = $db-&gt;Execute('execute return_multiple_rs');<br>$arr1 = $rs-&gt;GetArray();<br>$rs-&gt;NextRecordSet();<br>$arr2 = $rs-&gt;GetArray();</font></pre>
2678 <p><font><b>FetchObject<a name="fetchobject"></a>($toupper=true)</b></font></p>
2679 <p><font>Returns the current row as an object. If you set $toupper
2680 to true, then the object fields are set to upper-case. Note: The newer FetchNextObject()
2681 is the recommended way of accessing rows as objects. See below.</font></p>
2682 <p><font><b>FetchNextObject<a name="fetchnextobject"></a>($toupper=true)</b></font></p>
2683 <p><font>Gets the current row as an object and moves to the next
2684 row automatically. Returns false if at end-of-file. If you set $toupper to
2685 true, then the object fields are set to upper-case. Note that for some drivers such as mssql, you need to SetFetchMode(ADODB_FETCH_ASSOC) or SetFetchMode(ADODB_FETCH_BOTH).</font></p>
2686 <pre><font>$rs = $db-&gt;Execute('select firstname,lastname from table');<br>if ($rs) {<br> while ($o = $rs-&gt;FetchNextObject()) {<br> print "$o-&gt;FIRSTNAME, $o-&gt;LASTNAME&lt;BR&gt;";<br> }<br>}<br></font></pre>
2687 <p><font>There is some trade-off in speed in using FetchNextObject().
2688 If performance is important, you should access rows with the <code>fields[]</code> array. <b>FetchObj<a name="fetchobj" id="fetchobj"></a>()</b> </font></p>
2689 <p><font>Returns the current record as an object. Fields are
2690 not upper-cased, unlike FetchObject.
2691 </font></p>
2692 <p><font><b>FetchNextObj<a name="fetchnextobj" id="fetchnextobj"></a>()</b> </font></p>
2693 <p><font>Returns the current record as an object and moves to
2694 the next record. If EOF, false is returned. Fields are not upper-cased, unlike
2695 FetctNextObject. </font></p>
2696 <font>
2697 <p><b>CurrentRow<a name="currentrow"></a>( )</b></p>
2698 <p>Returns the current row of the record set. 0 is the first row.</p>
2699 <p><b>AbsolutePosition<a name="abspos"></a>( )</b></p>
2700 <p>Synonym for <b>CurrentRow</b> for compatibility with ADO. Returns the current
2701 row of the record set. 0 is the first row.</p>
2702 <p><b>MetaType<a name="metatype"></a>($nativeDBType[,$field_max_length],[$fieldobj])</b></p>
2703 <p>Determine what <i>generic</i> meta type a database field type is given its
2704 native type $<b>nativeDBType</b> as a string and the length of the field $<b>field_max_length</b>.
2705 Note that field_max_length can be -1 if it is not known. The field object returned
2706 by FetchField() can be passed in $<b>fieldobj</b> or as the 1st parameter <b>$nativeDBType</b>.
2707 This is useful for databases such as <i>mysql</i> which has additional properties
2708 in the field object such as <i>primary_key</i>. </p>
2709 <p>Uses the field <b>blobSize</b> and compares it with $<b>field_max_length</b> to
2710 determine whether the character field is actually a blob.</p>
2711 For example, $db-&gt;MetaType('char') will return 'C'.
2712 <p>Returns:</p>
2713 <ul>
2714 <li><b>C</b>: Character fields that should be shown in a &lt;input type="text"&gt; tag. </li>
2715 <li><b>X</b>: Clob (character large objects), or large text fields that should
2716 be shown in a &lt;textarea&gt;</li>
2717 <li><b>D</b>: Date field</li>
2718 <li><b>T</b>: Timestamp field</li>
2719 <li><b>L</b>: Logical field (boolean or bit-field)</li>
2720 <li><b>N</b>: Numeric field. Includes decimal, numeric, floating point, and
2721 real. </li>
2722 <li><b>I</b>:&nbsp; Integer field. </li>
2723 <li><b>R</b>: Counter or Autoincrement field. Must be numeric.</li>
2724 <li><b>B</b>: Blob, or binary large objects. </li>
2725 </ul>
2726 </font><p><font> Since ADOdb 3.0, MetaType accepts $fieldobj
2727 as the first parameter, instead of $nativeDBType. </font></p>
2728 <font> </font>
2729 <p><font><b>Close( )<a name="rsclose"></a></b></font></p>
2730 <p><font>Closes the recordset, cleaning all memory and resources
2731 associated with the recordset. </font></p>
2732 <p>
2733 <font>If memory management is not an issue, you do not need to
2734 call this function as recordsets are closed for you by PHP at the end of the
2735 script. SQL statements such as INSERT/UPDATE/DELETE do not really return a recordset,
2736 so you do not have to call Close() for such SQL statements.</font></p>
2737 <hr />
2738 <h3><font>function rs2html<a name="rs2html"></a>($adorecordset,[$tableheader_attributes],
2739 [$col_titles])</font></h3>
2740 <p><font>This is a standalone function (rs2html = recordset to
2741 html) that is similar to PHP's <i>odbc_result_all</i> function, it prints
2742 a ADORecordSet, $<b>adorecordset</b> as a HTML table. $<b>tableheader_attributes</b> allow
2743 you to control the table <i>cellpadding</i>, <i>cellspacing</i> and <i>border</i> attributes.
2744 Lastly you can replace the database column names with your own column titles
2745 with the array $<b>col_titles</b>. This is designed more as a quick debugging
2746 mechanism, not a production table recordset viewer.</font></p>
2747 <p><font>You will need to include the file <i>tohtml.inc.php</i>.</font></p>
2748 <p><font>Example of rs2html:<b><font color="#336600"><a name="exrs2html"></a></font></b></font></p>
2749 <pre><font><b><font color="#336600">&lt;?<br>include('tohtml.inc.php')</font></b>; # load code common to ADOdb <br><b>include</b>('adodb.inc.php'); # load code common to ADOdb <br>$<font color="#663300">conn</font> = &amp;ADONewConnection('mysql'); # create a connection <br>$<font color="#663300">conn</font>-&gt;PConnect('localhost','userid','','agora');# connect to MySQL, agora db<br>$<font color="#663300">sql</font> = 'select CustomerName, CustomerID from customers'; <br>$<font color="#663300">rs</font> = $<font color="#663300">conn</font>-&gt;Execute($sql); <br><font color="#336600"><b>rs2html</b></font><b>($<font color="#663300">rs</font>,'<i>border=2 cellpadding=3</i>',array('<i>Customer Name','Customer ID</i>'));<br>?&gt;</b></font></pre>
2750 <hr />
2751 <h3><font>Differences between this ADOdb library and Microsoft
2752 ADO<a name="adodiff"></a></font></h3>
2753 <ol>
2754 <font>
2755 <li>ADOdb only supports recordsets created by a connection object. Recordsets
2756 cannot be created independently.</li>
2757 <li>ADO properties are implemented as functions in ADOdb. This makes it easier
2758 to implement any enhanced ADO functionality in the future.</li>
2759 <li>ADOdb's <font face="Courier New, Courier, mono">ADORecordSet-&gt;Move()</font> uses
2760 absolute positioning, not relative. Bookmarks are not supported.</li>
2761 <li><font face="Courier New, Courier, mono">ADORecordSet-&gt;AbsolutePosition() </font>cannot
2762 be used to move the record cursor.</li>
2763 <li>ADO Parameter objects are not supported. Instead we have the ADOConnection::<a href="#parameter">Parameter</a>(
2764 ) function, which provides a simpler interface for calling preparing parameters
2765 and calling stored procedures.</li>
2766 <li>Recordset properties for paging records are available, but implemented as
2767 in <a href="#ex8">Example 8</a>.</li>
2768 </font></ol>
2769 <hr />
2770 <h1><font>Database Driver Guide<a name="driverguide"></a></font></h1>
2771 <p><font>This describes how to create a class to connect to a
2772 new database. To ensure there is no duplication of work, kindly email me
2773 at jlim#natsoft.com.my if you decide to create such a class.</font></p>
2774 <p><font>First decide on a name in lower case to call the database
2775 type. Let's say we call it xbase. </font></p>
2776 <p><font>Then we need to create two classes ADODB_xbase and ADORecordSet_xbase
2777 in the file adodb-xbase.inc.php.</font></p>
2778 <p><font>The simplest form of database driver is an adaptation
2779 of an existing ODBC driver. Then we just need to create the class <i>ADODB_xbase
2780 extends ADODB_odbc</i> to support the new <b>date</b> and <b>timestamp</b> formats,
2781 the <b>concatenation</b> operator used, <b>true</b> and <b>false</b>. For
2782 the<i> ADORecordSet_xbase extends ADORecordSet_odbc </i>we need to change
2783 the <b>MetaType</b> function. See<b> adodb-vfp.inc.php</b> as an example.</font></p>
2784 <p><font>More complicated is a totally new database driver that
2785 connects to a new PHP extension. Then you will need to implement several
2786 functions. Fortunately, you do not have to modify most of the complex code.
2787 You only need to override a few stub functions. See <b>adodb-mysql.inc.php</b> for
2788 example.</font></p>
2789 <p><font>The default date format of ADOdb internally is YYYY-MM-DD
2790 (Ansi-92). All dates should be converted to that format when passing to an
2791 ADOdb date function. See Oracle for an example how we use ALTER SESSION to
2792 change the default date format in _pconnect _connect.</font></p>
2793 <p><font><b>ADOConnection Functions to Override</b></font></p>
2794 <p><font>Defining a constructor for your ADOConnection derived
2795 function is optional. There is no need to call the base class constructor.</font></p>
2796 <p><font>_<b>connect</b>: Low level implementation of Connect.
2797 Returns true or false. Should set the _<b>connectionID</b>.</font></p>
2798 <p><font>_<b>pconnect:</b> Low level implemention of PConnect.
2799 Returns true or false. Should set the _<b>connectionID</b>.</font></p>
2800 <p><font>_<b>query</b>: Execute a query. Returns the queryID,
2801 or false.</font></p>
2802 <p><font>_<b>close: </b>Close the connection -- PHP should clean
2803 up all recordsets. </font></p>
2804 <p><font><b>ErrorMsg</b>: Stores the error message in the private
2805 variable _errorMsg. </font></p>
2806 <p><font><b>ADOConnection Fields to Set</b></font></p>
2807 <p><font>_<b>bindInputArray</b>: Set to true if binding of parameters
2808 for SQL inserts and updates is allowed using ?, eg. as with ODBC.</font></p>
2809 <p><font><b>fmtDate</b></font></p>
2810 <p><font><b>fmtTimeStamp</b></font></p>
2811 <p><font><b>true</b></font></p>
2812 <p><font><b>false</b></font></p>
2813 <p><font><b>concat_operator</b></font></p>
2814 <p><font><b>replaceQuote</b></font></p>
2815 <p><font><b>hasLimit</b> support SELECT * FROM TABLE LIMIT 10
2816 of MySQL.</font></p>
2817 <p><font><b>hasTop</b> support Microsoft style SELECT TOP 10
2818 * FROM TABLE.</font></p>
2819 <p><font><b>ADORecordSet Functions to Override</b></font></p>
2820 <p><font>You will need to define a constructor for your ADORecordSet
2821 derived class that calls the parent class constructor.</font></p>
2822 <p><font><b>FetchField: </b> as documented above in ADORecordSet</font></p>
2823 <p><font>_<b>initrs</b>: low level initialization of the recordset:
2824 setup the _<b>numOfRows</b> and _<b>numOfFields</b> fields -- called by the
2825 constructor.</font></p>
2826 <p><font>_<b>seek</b>: seek to a particular row. Do not load
2827 the data into the fields array. This is done by _fetch. Returns true or false.
2828 Note that some implementations such as Interbase do not support seek. Set
2829 canSeek to false.</font></p>
2830 <p><font>_<b>fetch</b>: fetch a row using the database extension
2831 function and then move to the next row. Sets the <b>fields</b> array. If
2832 the parameter $ignore_fields is true then there is no need to populate the <b>fields</b> array,
2833 just move to the next row. then Returns true or false.</font></p>
2834 <p><font>_<b>close</b>: close the recordset</font></p>
2835 <p><font><b>Fields</b>: If the array row returned by the PHP
2836 extension is not an associative one, you will have to override this. See
2837 adodb-odbc.inc.php for an example. For databases such as MySQL and MSSQL
2838 where an associative array is returned, there is no need to override this
2839 function.</font></p>
2840 <p><font><b>ADOConnection Fields to Set</b></font></p>
2841 <p><font>canSeek: Set to true if the _seek function works.</font></p>
2842 <h2><font>Optimizing PHP</font></h2>
2843 For info on tuning PHP, read this article on <a href="http://phplens.com/lens/php-book/optimizing-debugging-php.php">Optimizing
2844 PHP</a>. </font></p>
2845
2846 <h2><font>Change Log<a name="Changes"></a><a name="changes"></a><a name="changelog"></a></font></h2>
2847 <P>
2848 <p><a name="4.81"></a><b>4.81 ? 2006</b>
2849 <p>Fixed variable ref errors in adodb-ado5.inc.php in _query().
2850 <p>Mysqli setcharset fix using method_exists().
2851 <p>The adodb-perf.inc.php CreateLogTable() code now works for user-defined table names.
2852 <p>Error in ibase_blob_open() fixed. See http://phplens.com/lens/lensforum/msgs.php?id=14997
2853 <p><a name="4.80"></a><b>4.80 8 Mar 2006</b>
2854 <p>Added activerecord support.
2855 <p>Added mysql $conn->compat323 = true if you want MySQL 3.23 compat enabled. Fixes GetOne() Select-Limit problems.
2856 <p>Added adodb-xmlschema03.inc.php to support XML Schema version 3 and updated adodb-datadict.htm docs.
2857 <p>Better memory management in Execute. Thx Mike Fedyk.
2858 <p><a name="4.72"></a><b>4.72 21 Feb 2006</b>
2859 <p>Added 'new' DSN parameter for NConnect().
2860 <p>Pager now sanitizes $PHP_SELF to protect against XSS. Thx to James Bercegay and others.
2861 <p>ADOConnection::MetaType changed to setup $rs->connection correctly.
2862 <p>New native DB2 driver contributed by Larry Menard, Dan Scott, Andy Staudacher, Bharat Mediratta.
2863 <p>The mssql CreateSequence() did not BEGIN TRANSACTION correctly. Fixed. Thx Sean Lee.
2864 <p>The _adodb_countrecs() function in adodb-lib.inc.php has been revised to handle more ORDER BY variations.
2865 <p><a name="4.71"></a><b>4.71 24 Jan 2006</b>
2866 <p>Fixes postgresql security issue related to binary strings. Thx to Andy Staudacher.
2867 <p>Several DSN bugs found: