Subversion Repositories svnkaklik

Rev

Details | Last modification | View Log

Rev Author Line No. Line
36 kaklik 1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2
<html>
3
<head>
4
<style>
5
pre {
6
  background-color: #eee;
7
  padding: 0.75em 1.5em;
8
  font-size: 12px;
9
  border: 1px solid #ddd;
10
}
11
.greybg {
12
  background-color: #eee;
13
  padding: 0.75em 1.5em;
14
  font-size: 12px;
15
  border: 1px solid #ddd;
16
}
17
.style1 {color: #660000}
18
</style>
19
<title>ADOdb with PHP and Oracle</title>
20
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
21
</style>
22
</head>
23
 
24
<body>
25
<table width=100%><tr><td>
26
<h2>Using ADOdb with PHP and Oracle: an advanced tutorial</h2>
27
</td><td><div align="right"><img src=cute_icons_for_site/adodb.gif width="88" height="31"></div></tr></table>
28
<p><font size="1">(c)2004-2005 John Lim. All rights reserved.</font></p>
29
<h3>1. Introduction</h3>
30
<p>Oracle is the most popular commercial database used with PHP. There are many ways of accessing Oracle databases in PHP. These include:</p>
31
<ul>
32
  <li>The oracle extension</li>
33
  <li>The oci8 extension</li>
34
  <li>PEAR DB library</li>
35
  <li>ADOdb library</li>
36
</ul>
37
<p>The wide range of choices is confusing to someone just starting with Oracle and PHP. I will briefly summarize the differences, and  show you the advantages of using <a href="http://adodb.sourceforge.net/">ADOdb</a>. </p>
38
<p>First we have the C extensions which provide low-level access to Oracle functionality. These C extensions are precompiled into PHP, or linked in dynamically when the web server starts up. Just in case you need it, here's a <a href=http://www.oracle.com/technology/tech/opensource/php/apache/inst_php_apache_linux.html>guide to installing Oracle and PHP on Linux</a>.</p>
39
<table width="75%" border="1" align="center">
40
  <tr valign="top">
41
    <td nowrap><b>Oracle extension</b></td>
42
    <td>Designed for Oracle 7 or earlier. This is obsolete.</td>
43
  </tr>
44
  <tr valign="top">
45
    <td nowrap><b>Oci8 extension</b></td>
46
    <td> Despite it's name, which implies it is only for Oracle 8i, this is the standard method for accessing databases running Oracle 8i, 9i or 10g (and later).</td>
47
  </tr>
48
</table>
49
<p>Here is an example of using the oci8 extension to query the <i>emp</i> table of the <i>scott</i> schema with bind parameters:
50
<pre>
51
$conn = OCILogon("scott","tiger", $tnsName); 
52
 
53
$stmt = OCIParse($conn,"select * from emp where empno > :emp order by empno"); 
54
$emp = 7900;
55
OCIBindByName($stmt, ':emp', $emp);
56
$ok = OCIExecute($stmt);
57
while (OCIFetchInto($stmt,$arr)) {
58
	print_r($arr);
59
	echo "&lt;hr>";	
60
} 
61
</pre>
62
<p>This generates the following output:
63
<div class=greybg>
64
Array ( [0] => 7902 [1] => FORD [2] => ANALYST [3] => 7566 [4] => 03/DEC/81 [5] => 3000 [7] => 20 ) 
65
<hr />
66
  Array ( [0] => 7934 [1] => MILLER [2] => CLERK [3] => 7782 [4] => 23/JAN/82 [5] => 1300 [7] => 10 )
67
</div>
68
<p>We also have  many higher level PHP libraries that allow you to simplify the above code. The most popular are <a href="http://pear.php.net/">PEAR DB</a> and <a href="http://adodb.sourceforge.net/">ADOdb</a>.  Here are some of the differences between these libraries:</p>
69
<table width="75%" border="1" align="center">
70
  <tr>
71
    <td><b>Feature</b></td>
72
    <td><b>PEAR DB 1.6</b></td>
73
    <td><b>ADOdb 4.52</b></td>
74
  </tr>
75
  <tr valign="top">
76
    <td>General Style</td>
77
    <td>Simple, easy to use. Lacks Oracle specific functionality.</td>
78
    <td>Has multi-tier design. Simple high-level design for beginners, and also lower-level advanced Oracle functionality.</td>
79
  </tr>
80
  <tr valign="top">
81
    <td>Support for Prepare</td>
82
    <td>Yes, but only on one statement, as the last prepare overwrites previous prepares.</td>
83
    <td>Yes (multiple simultaneous prepare's allowed)</td>
84
  </tr>
85
  <tr valign="top">
86
    <td>Support for LOBs</td>
87
    <td>No</td>
88
    <td>Yes, using update semantics</td>
89
  </tr>
90
  <tr valign="top">
91
    <td>Support for REF Cursors</td>
92
    <td>No</td>
93
    <td>Yes</td>
94
  </tr>
95
  <tr valign="top">
96
    <td>Support for IN Parameters</td>
97
    <td>Yes</td>
98
    <td>Yes</td>
99
  </tr>
100
  <tr valign="top">
101
    <td>Support for OUT Parameters</td>
102
    <td>No</td>
103
    <td>Yes</td>
104
  </tr>
105
  <tr valign="top">
106
    <td>Schema creation using XML</td>
107
    <td>No</td>
108
    <td>Yes, including ability to define tablespaces and constraints</td>
109
  </tr>
110
  <tr valign="top">
111
    <td>Provides database portability features</td>
112
    <td>No</td>
113
    <td>Yes, has some ability to abstract features that differ between databases such as dates, bind parameters, and data types.</td>
114
  </tr>
115
  <tr valign="top">
116
    <td>Performance monitoring and tracing</td>
117
    <td>No</td>
118
    <td>Yes. SQL can be traced and linked to web page it was executed on. Explain plan support included.</td>
119
  </tr>
120
  <tr valign="top">
121
    <td>Recordset caching for frequently used queries</td>
122
    <td>No</td>
123
    <td>Yes. Provides great speedups for SQL involving complex <i>where, group-by </i>and <i>order-by</i> clauses.</td>
124
  </tr>
125
  <tr valign="top">
126
    <td>Popularity</td>
127
    <td>Yes, part of PEAR release</td>
128
    <td>Yes, many open source projects are using this software, including PostNuke, Xaraya, Mambo, Tiki Wiki.</td>
129
  </tr>
130
  <tr valign="top">
131
    <td>Speed</td>
132
    <td>Medium speed.</td>
133
    <td>Very high speed. Fastest database abstraction library available for PHP. <a href="http://phplens.com/lens/adodb/">Benchmarks are available</a>.</td>
134
  </tr>
135
  <tr valign="top">
136
    <td>High Speed Extension available</td>
137
    <td>No</td>
138
    <td>Yes. You can install the optional ADOdb extension, which reimplements the most frequently used parts of ADOdb as fast C code. Note that the source code version of ADOdb runs just fine without this extension, and only makes use of the extension if detected.</td>
139
  </tr>
140
</table>
141
<p> PEAR DB is good enough for simple web apps. But if you need more power, you can see ADOdb offers more sophisticated functionality. The rest of this article will concentrate on using ADOdb with Oracle. You can find out more about <a href="#connecting">connecting to Oracle</a> later in this guide.</p>
142
<h4>ADOdb Example</h4>
143
<p>In ADOdb, the above oci8 example querying the <i>emp</i> table could be written as:</p>
144
<pre>
145
include "/path/to/adodb.inc.php";
146
$db = NewADOConnection("oci8");
147
$db->Connect($tnsName, "scott", "tiger");
148
 
149
$rs = $db->Execute("select * from emp where empno>:emp order by empno", 
150
                    array('emp' => 7900));
151
while ($arr = $rs->FetchRow()) {
152
    print_r($arr);
153
	echo "&lt;hr>";
154
}
155
</pre>
156
<p>The Execute( ) function returns a recordset object, and you can retrieve the rows returned using $recordset-&gt;FetchRow( ). </p>
157
<p>If we ignore the initial connection preamble, we can see the ADOdb version is much easier and simpler:</p>
158
<table width="100%" border="1">
159
  <tr valign="top" bgcolor="#FFFFFF">
160
    <td width="50%" bgcolor="#e0e0e0"><b>Oci8</b></td>
161
    <td bgcolor="#e0e0e0"><b>ADOdb</b></td>
162
  </tr>
163
  <tr valign="top" bgcolor="#CCCCCC">
164
    <td><pre><font size="1">$stmt = <b>OCIParse</b>($conn,
165
       "select * from emp where empno > :emp"); 
166
$emp = 7900;
167
<b>OCIBindByName</b>($stmt, ':emp', $emp);
168
$ok = <b>OCIExecute</b>($stmt);
169
 
170
while (<b>OCIFetchInto</b>($stmt,$arr)) {
171
	print_r($arr);
172
	echo "&lt;hr>";	
173
} </font></pre></td>
174
    <td><pre><font size="1">$recordset = $db-><b>Execute</b>("select * from emp where empno>:emp", 
175
                           array('emp' => 7900));
176
 
177
while ($arr = $recordset-><b>FetchRow</b>()) {
178
	print_r($arr);
179
	echo "&lt;hr>";
180
}</font></pre></td>
181
  </tr>
182
</table>
183
<p>&nbsp;</p>
184
<h3>2. ADOdb Query Semantics</h3>
185
<p>You can also query the database using the standard Microsoft ADO MoveNext( ) metaphor. The data array for the current row is stored in the <i>fields</i> property of the recordset object, $rs.
186
MoveNext( ) offers the highest performance among all the techniques for iterating through a recordset:
187
<pre>
188
$rs = $db->Execute("select * from emp where empno>:emp", array('emp' => 7900));
189
while (!$rs->EOF) {
190
	print_r($rs->fields);
191
	$rs->MoveNext();
192
}
193
</pre>
194
<p>And if you are interested in having the data returned in a 2-dimensional array, you can use:
195
<pre>
196
$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));
197
</pre>
198
<p>Now to obtain only the first row as an array:
199
<pre>
200
$arr = $db->GetRow("select * from emp where empno=:emp", array('emp' => 7900));
201
</pre>
202
<p>Or to retrieve only the first field of the first row:
203
<pre>
204
$arr = $db->GetOne("select ename from emp where empno=:emp", array('emp' => 7900));
205
</pre>
206
<p>For easy pagination support, we provide the SelectLimit function. The following will perform a select query, limiting it to 100 rows, starting from row 200:
207
<pre>
208
$offset = 200; $limitrows = 100;
209
$rs = $db->SelectLimit('select * from table', $offset, $limitrows);
210
</pre>
211
<p>The $limitrows parameter is optional.
212
<h4>Array Fetch Mode</h4>
213
<p>When data is being returned in an array, you can choose the type of array the data is returned in. 
214
<ol>
215
  <li> Numeric indexes - use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_NUM).</font></li>
216
  <li>Associative indexes - the keys of the array are the names of the fields (in upper-case). Use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_ASSOC)</font><font face="Courier New, Courier, mono">.</font></li>
217
  <li>Both numeric and associative indexes - use <font size="2" face="Courier New, Courier, mono">$connection-&gt;SetFetchMode(ADODB_FETCH_BOTH).</font></li>
218
</ol>
219
<p>The default is ADODB_FETCH_BOTH for Oracle.</p>
220
<h4><b>Caching</b></h4>
221
<p>You can define a database cache directory using $ADODB_CACHE_DIR, and cache the results of frequently used queries that rarely change. This is particularly useful for SQL with complex where clauses and group-by's and order-by's. It is also good for relieving heavily-loaded database servers.</p>
222
<p>This example will cache the following select statement for 3600 seconds (1 hour):</p>
223
<pre>
224
$ADODB_CACHE_DIR = '/var/adodb/tmp';
225
$rs = $db->CacheExecute(3600, "select names from allcountries order by 1");
226
</pre>
227
There are analogous CacheGetArray(
228
), CacheGetRow( ),  CacheGetOne( ) and CacheSelectLimit( )  functions. The first parameter is the number of seconds to cache. You can also pass a bind array as a 3rd parameter (not shown above).
229
<p>There is an alternative syntax for the caching functions. The first parameter is omitted, and you set the cacheSecs
230
 property of the connection object:
231
<pre>
232
$ADODB_CACHE_DIR = '/var/adodb/tmp';
233
$connection->cacheSecs = 3600;
234
$rs = $connection->CacheExecute($sql, array('id' => 1));
235
</pre>
236
<h3>&nbsp;</h3>
237
<h3>3. Using Prepare( ) For Frequently Used Statements</h3>
238
<p>Prepare( ) is  for compiling frequently used  SQL statement for reuse. For example, suppose we have a large array which needs to be inserted into an Oracle database. The following will result in a massive speedup in query execution (at least 20-40%), as the SQL statement only needs to be compiled once:</p>
239
<pre>
240
$stmt = $db->Prepare('insert into table (field1, field2) values (:f1, :f2)');
241
foreach ($arrayToInsert as $key => $value) {
242
	$db->Execute($stmt, array('f1' => $key, 'f2' => $val);
243
}
244
</pre>
245
<p>&nbsp;</p>
246
<h3>4. Working With LOBs</h3>
247
<p>Oracle treats data which is more than 4000 bytes in length specially. These are called Large Objects, or LOBs for short. Binary LOBs are BLOBs, and character LOBs are CLOBs. In most Oracle libraries, you need to do a lot of work to process LOBs, probably because Oracle designed it to work in systems with little memory. ADOdb tries to make things easy by assuming the LOB can fit into main memory. </p>
248
<p>ADOdb will transparently handle LOBs  in <i>select</i> statements. The LOBs are automatically converted to PHP variables without any special coding.</p>
249
<p>For updating records with LOBs, the functions UpdateBlob( ) and UpdateClob( ) are provided. Here's a BLOB example. The parameters should be self-explanatory:
250
<pre>
251
$ok = $db->Execute("insert into aTable (id, name, ablob) 
252
                                values (aSequence.nextVal, 'Name', null)");
253
if (!$ok) return LogError($db-&gt;ErrorMsg());
254
<font color="#006600"># params: $tableName, $blobFieldName, $blobValue, $whereClause</font>
255
$db->UpdateBlob('aTable', 'ablob', $blobValue, 'id=aSequence.currVal');
256
</pre>
257
<p>and the analogous CLOB example:
258
<pre>
259
$ok = $db->Execute("insert into aTable (id, name, aclob) 
260
                                values (aSequence.nextVal, 'Name', null)");
261
if (!$ok) return LogError($db-&gt;ErrorMsg());
262
$db->UpdateClob('aTable', 'aclob', $clobValue, 'id=aSequence.currVal');
263
</pre>
264
<p>Note that LogError( ) is a user-defined function, and not part of ADOdb.
265
<p>Inserting LOBs is more complicated. Since ADOdb 4.55, we allow you to do this
266
  (assuming that the <em>photo</em> field is a BLOB, and we want to store $blob_data into
267
  this field, and the primary key is the <em>id</em> field):
268
<pre>
269
	$sql = <span class="style1">"INSERT INTO photos ( ID, photo) ".
270
			"VALUES ( :id, empty_blob() )".
271
			" RETURNING photo INTO :xx"</span>;
272
 
273
 		$stmt = $db->PrepareSP($sql);
274
		$db->InParameter($stmt, $<strong>id</strong>, <span class="style1">'id'</span>);
275
		$blob = $db->InParameter($stmt, $<strong>blob_data</strong>, <span class="style1">'xx'</span>,-1, OCI_B_BLOB);
276
		$db->StartTrans();
277
		$ok = $db->Execute($stmt);
278
		$db->CompleteTrans();
279
</pre> 
280
<p>
281
<h3>5. REF CURSORs</h3>
282
<p>Oracle recordsets can be passed around as variables called REF Cursors. For example, in PL/SQL, we could define a function <i>open_tab</i> that returns a REF CURSOR in the first parameter:</p>
283
<pre>
284
TYPE TabType IS REF CURSOR RETURN TAB%ROWTYPE;
285
 
286
PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames IN VARCHAR) IS
287
	BEGIN
288
		OPEN tabcursor FOR SELECT * FROM TAB WHERE tname LIKE tablenames;
289
	END open_tab;
290
</pre>
291
<p>In ADOdb, we could access this REF Cursor using the ExecuteCursor() function. The following will find
292
 all table names that begin with 'A' in the current schema:
293
<pre>
294
$rs = $db->ExecuteCursor("BEGIN open_tab(:refc,'A%'); END;",'refc');
295
while ($arr = $rs->FetchRow()) print_r($arr);
296
</pre>
297
<p>The first parameter is the PL/SQL statement, and the second parameter is the name of the REF Cursor.
298
</p>
299
<p>&nbsp;</p>
300
<h3>6. In and Out Parameters</h3>
301
<p>The following PL/SQL
302
stored procedure  requires an input  variable, and returns a result into an output variable:
303
<pre>
304
PROCEDURE data_out(input IN VARCHAR, output OUT VARCHAR) IS
305
	BEGIN
306
		output := 'I love '||input;
307
	END;
308
</pre>
309
<p>The following ADOdb code allows you to call the stored procedure:</p>
310
<pre>
311
$stmt = $db->PrepareSP("BEGIN adodb.data_out(:a1, :a2); END;");
312
$input = 'Sophia Loren';
313
$db->InParameter($stmt,$input,'a1');
314
$db->OutParameter($stmt,$output,'a2');
315
$ok = $db->Execute($stmt);
316
if ($ok) echo ($output == 'I love Sophia Loren') ? 'OK' : 'Failed';
317
</pre>
318
<p>PrepareSP( ) is a special function that knows about bind parameters.
319
The main limitation currently is that IN OUT parameters do not work.
320
<h4>Bind Parameters and REF CURSORs</h4>
321
<p>We could also rewrite the REF CURSOR example to use InParameter (requires ADOdb 4.53 or later):
322
<pre>
323
$stmt = $db->PrepareSP("BEGIN adodb.open_tab(:refc,:tabname); END;");
324
$input = 'A%';
325
$db->InParameter($stmt,$input,'tabname');
326
$rs = $db->ExecuteCursor($stmt,'refc');
327
while ($arr = $rs->FetchRow()) print_r($arr);
328
</pre>
329
<h4>Bind Parameters and LOBs</h4>
330
<p>You can also operate on LOBs. In this example, we have IN and OUT parameters using CLOBs. 
331
<pre>
332
	$text = 'test test test';
333
	$sql = "declare rs clob; begin :rs := lobinout(:sa0); end;";
334
	$stmt = $conn -> PrepareSP($sql);
335
	$conn -> InParameter($stmt,$text,'sa0', -1, OCI_B_CLOB); # -1 means variable length
336
	$rs = '';
337
	$conn -> OutParameter($stmt,$rs,'rs', -1, OCI_B_CLOB);
338
	$conn -> Execute($stmt);
339
	echo "return = ".$rs."&lt;br>";
340
</pre>
341
<p>Similarly, you can use the constant OCI_B_BLOB to indicate that you are using BLOBs.
342
<h4>Reusing Bind Parameters with CURSOR_SHARING=FORCE</h4>
343
<p>Many web programmers do not care to use bind parameters, and prefer to enter the SQL directly. So instead of:</p>
344
<pre>
345
$arr = $db->GetArray("select * from emp where empno>:emp", array('emp' => 7900));
346
</pre>
347
<p>They prefer  entering the values inside the SQL:
348
<pre>
349
$arr = $db->GetArray("select * from emp where empno>7900");
350
</pre>
351
<p>This reduces Oracle performance because Oracle will reuse compiled SQL which is identical to previously compiled SQL. The above example with the values inside the SQL
352
is unlikely to be reused. As an optimization, from Oracle 8.1 onwards, you can set the following session parameter after you login:
353
<pre>
354
ALTER SESSION SET CURSOR_SHARING=FORCE
355
</pre>
356
<p>This will force Oracle to convert all such variables (eg. the 7900 value) into constant bind parameters, improving SQL reuse.</p>
357
<p>More <a href="http://phplens.com/adodb/code.initialization.html#speed">speedup tips</a>.</p>
358
<p>&nbsp;</p>
359
<h3>7. Dates and Datetime in ADOdb</h3>
360
<p>There are two things you need to know about dates in ADOdb. </p>
361
<p>First, to ensure cross-database compability, ADOdb assumes that dates are returned in ISO format (YYYY-MM-DD H24:MI:SS).</p>
362
<p>Secondly, since Oracle treats dates and datetime as the same data type, we decided not to display the time in the default date format. So on login, ADOdb will set the NLS_DATE_FORMAT to 'YYYY-MM-DD'. If you prefer to show the date and time by default, do this:</p>
363
<pre>
364
$db = NewADOConnection('oci8');
365
$db->NLS_DATE_FORMAT =  'RRRR-MM-DD HH24:MI:SS';
366
$db->Connect($tns, $user, $pwd);
367
</pre>
368
<p>Or execute:</p>
369
<pre>$sql = &quot;ALTER SESSION SET NLS_DATE_FORMAT = 'RRRR-MM-DD HH24:MI:SS'&quot;;
370
$db-&gt;Execute($sql);
371
</pre>
372
<p>If you are not concerned about date portability and do not use ADOdb's portability layer, you can use your preferred date format instead.
373
<p>
374
<h3>8. Database Portability Layer</h3>
375
<p>ADOdb provides the following functions for portably generating SQL functions 
376
  as strings to be merged into your SQL statements:</p>
377
<table width="75%" border="1" align=center>
378
  <tr> 
379
    <td width=30%><b>Function</b></td>
380
    <td><b>Description</b></td>
381
  </tr>
382
  <tr> 
383
    <td>DBDate($date)</td>
384
    <td>Pass in a UNIX timestamp or ISO date and it will convert it to a date 
385
      string formatted for INSERT/UPDATE</td>
386
  </tr>
387
  <tr> 
388
    <td>DBTimeStamp($date)</td>
389
    <td>Pass in a UNIX timestamp or ISO date and it will convert it to a timestamp 
390
      string formatted for INSERT/UPDATE</td>
391
  </tr>
392
  <tr> 
393
    <td>SQLDate($date, $fmt)</td>
394
    <td>Portably generate a date formatted using $fmt mask, for use in SELECT 
395
      statements.</td>
396
  </tr>
397
  <tr> 
398
    <td>OffsetDate($date, $ndays)</td>
399
    <td>Portably generate a $date offset by $ndays.</td>
400
  </tr>
401
  <tr> 
402
    <td>Concat($s1, $s2, ...)</td>
403
    <td>Portably concatenate strings. Alternatively, for mssql use mssqlpo driver, 
404
      which allows || operator.</td>
405
  </tr>
406
  <tr> 
407
    <td>IfNull($fld, $replaceNull)</td>
408
    <td>Returns a string that is the equivalent of MySQL IFNULL or Oracle NVL.</td>
409
  </tr>
410
  <tr>
411
    <td>Param($name)</td>
412
    <td>Generates bind placeholders, using ? or named conventions as appropriate.</td>
413
  </tr>
414
  <tr><td>$db->sysDate</td><td>Property that holds the SQL function that returns today's date</td>
415
</tr>
416
<tr><td>$db->sysTimeStamp</td><td>Property that holds the SQL function that returns the current
417
timestamp (date+time).
418
</td>
419
</tr>
420
<tr>
421
<td>$db->concat_operator</td><td>Property that holds the concatenation operator
422
</td>
423
</tr>
424
<tr><td>$db->length</td><td>Property that holds the name of the SQL strlen function.
425
</td></tr>
426
 
427
<tr><td>$db->upperCase</td><td>Property that holds the name of the SQL strtoupper function.
428
</td></tr>
429
<tr><td>$db->random</td><td>Property that holds the SQL to generate a random number between 0.00 and 1.00.
430
</td>
431
</tr>
432
<tr><td>$db->substr</td><td>Property that holds the name of the SQL substring function.
433
</td></tr>
434
</table>
435
<p>ADOdb also provides multiple oracle oci8 drivers for different scenarios:</p>
436
<table width="75%" border="1" align="center">
437
  <tr>
438
    <td nowrap><b>Driver Name</b></td>
439
    <td><b>Description</b></td>
440
  </tr>
441
  <tr>
442
    <td>oci805 </td>
443
    <td>Specifically for Oracle 8.0.5. This driver has a slower SelectLimit( ).</td>
444
  </tr>
445
  <tr>
446
    <td>oci8</td>
447
    <td>The default high performance driver. The keys of associative arrays returned in a recordset are upper-case.</td>
448
  </tr>
449
  <tr>
450
    <td>oci8po</td>
451
    <td> The portable Oracle driver. Slightly slower than oci8. This driver uses ? instead of :<i>bindvar</i> for binding variables, which is the standard for  other databases. Also the keys of associative arrays are in lower-case like other databases.</td>
452
  </tr>
453
</table>
454
<p>Here's an example of calling the <i>oci8po</i> driver. Note that the bind variables use question-mark:</p>
455
<pre>$db = NewADOConnection('oci8po');
456
$db-&gt;Connect($tns, $user, $pwd);
457
$db-&gt;Execute(&quot;insert into atable (f1, f2) values (?,?)&quot;, array(12, 'abc'));</pre>
458
<p>&nbsp;<a name=connecting></a>
459
<h3>9. Connecting to Oracle</h3>
460
<p>Before you can use ADOdb, you need to have the Oracle client installed and setup the oci8 extension. This extension comes pre-compiled for Windows (but you still need to enable it in the php.ini file). For information on compiling the oci8 extension for PHP and Apache on Unix, there is an excellent guide at <a href="http://www.oracle.com/technology/tech/opensource/php/apache/inst_php_apache_linux.html">oracle.com</a>. </p>
461
<h4>Should You Use Persistent Connections</h4>
462
<p>One question that is frequently asked is should you use persistent connections to Oracle. Persistent connections allow PHP to recycle existing connections, reusing them after the previous web pages have completed. Non-persistent connections close automatically after the web page has completed. Persistent connections are faster because the cost of reconnecting is expensive, but there is additional resource overhead. As an alternative, Oracle allows you to pool and reuse server processes; this is called  <a href="http://www.cise.ufl.edu/help/database/oracle-docs/server.920/a96521/manproc.htm#13132">Shared Server</a> (also known as MTS).</p>
463
<p>The author's benchmarks suggest that using non-persistent connections and the  Shared Server configuration offer the best performance. If Shared Server is not an option, only then consider using persistent connections.</p>
464
<h4>Connection Examples</h4>
465
<p>Just in case you are having problems connecting to Oracle, here are some examples:</p>
466
<p>a. PHP and Oracle reside on the same machine, use default SID, with non-persistent connections:</p>
467
<pre>	$conn = NewADOConnection('oci8');
468
	$conn-&gt;Connect(false, 'scott', 'tiger');</pre>
469
<p>b. TNS Name defined in tnsnames.ora (or ONAMES or HOSTNAMES), eg. 'myTNS', using persistent connections:</p>
470
<pre>	$conn = NewADOConnection('oci8');
471
	$conn-&gt;PConnect(false, 'scott', 'tiger', 'myTNS');</pre>
472
<p>or</p>
473
<pre> 	$conn-&gt;PConnect('myTNS', 'scott', 'tiger');</pre>
474
<p>c. Host Address and SID</p>
475
<pre>
476
	$conn->connectSID = true;	
477
	$conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'SID');</pre>
478
<p>d. Host Address and Service Name</p>
479
<pre>	$conn-&gt;Connect('192.168.0.1', 'scott', 'tiger', 'servicename');</pre>
480
<p>e. Oracle connection string:
481
<pre>	$cstr = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$host)(PORT=$port))
482
			(CONNECT_DATA=(SID=$sid)))";
483
	$conn-&gt;Connect($cstr, 'scott', 'tiger');
484
</pre>
485
<p>f. ADOdb data source names (dsn):
486
<pre>
487
	$dsn = 'oci8://user:pwd@tnsname/?persist';  # persist is optional
488
	$conn = ADONewConnection($dsn);  # no need for Connect/PConnect
489
 
490
	$dsn = 'oci8://user:pwd@host/sid';
491
	$conn = ADONewConnection($dsn);
492
 
493
	$dsn = 'oci8://user:pwd@/';   # oracle on local machine
494
	$conn = ADONewConnection($dsn);</pre>
495
<p>With ADOdb data source names,
496
you don't have to call Connect( ) or PConnect( ).
497
</p>
498
<p>&nbsp;</p>
499
<h3>10. Error Checking</h3>
500
<p>The examples in this article are easy to read but a bit simplistic because we ignore error-handling. Execute( ) and Connect( ) will return false on error. So a more realistic way to call Connect( ) and Execute( ) is:
501
<pre>function InvokeErrorHandler()
502
{<br>global $db; ## assume global
503
    MyLogFunction($db-&gt;ErrorNo(), $db-&gt;ErrorMsg());
504
}
505
if (!$db-&gt;Connect($tns, $usr, $pwd)) InvokeErrorHandler();
506
 
507
$rs = $db->Execute("select * from emp where empno>:emp order by empno", 
508
                    array('emp' => 7900));
509
if (!$rs) return InvokeErrorHandler();
510
while ($arr = $rs->FetchRow()) {
511
    print_r($arr);
512
	echo "&lt;hr>";
513
}
514
</pre>
515
<p>You can retrieve the  error message and error number of the last SQL statement executed from ErrorMsg( ) and ErrorNo( ). You can also <a href=http://phplens.com/adodb/using.custom.error.handlers.and.pear_error.html>define a custom error handler function</a>.
516
ADOdb also supports throwing exceptions in PHP5.
517
<p>&nbsp;</p>
518
<h3>Handling Large Recordsets (added 27 May 2005)</h3>
519
The oci8 driver does not support counting the number of records returned in a SELECT statement, so the function RecordCount() 
520
is emulated when the global variable $ADODB_COUNTRECS is set to true, which is the default. 
521
We emulate this by buffering all the records. This can take up large amounts of memory for big recordsets.
522
 Set $ADODB_COUNTRECS to false for the best performance. 
523
 <p>
524
This variable is checked every time a query is executed, so you can selectively choose which recordsets to count.
525
<p>&nbsp;</p>
526
<h3>11. Other ADOdb Features</h3>
527
<p><a href="http://phplens.com/lens/adodb/docs-datadict.htm">Schema generation</a>. This allows you to define a schema using XML and import it into different RDBMS systems portably.</p>
528
<p><a href="http://phplens.com/lens/adodb/docs-perf.htm">Performance monitoring and tracing</a>. Highlights of performance monitoring include identification of poor and suspicious SQL, with explain plan support, and identifying which web pages the SQL ran on.</p>
529
<p>&nbsp;</p>
530
<h3>12. Download</h3>
531
<p>You can <a href="http://adodb.sourceforge.net/#download">download ADOdb from sourceforge</a>. ADOdb uses a BSD style license. That means that it is free for commercial use, and redistribution without source code is allowed.</p>
532
<p>&nbsp;</p>
533
<h3>13. Resources</h3>
534
<ul>
535
  <li>Oracle's <a href="http://www.oracle.com/technology/pub/articles/php_experts/index.html">Hitchhiker Guide to PHP</a></li>
536
  <li>OTN article on <a href=http://www.oracle.com/technology/pub/articles/deployphp/lim_deployphp.html>Optimizing PHP and Oracle</a> by this author.
537
  <li>Oracle has an excellent <a href="http://www.oracle.com/technology/tech/opensource/php/php_troubleshooting_faq.html">FAQ on PHP</a></li>
538
  <li>PHP <a href="http://php.net/oci8">oci8</a> manual pages</li>
539
  <li><a href=http://phplens.com/lens/lensforum/topics.php?id=4>ADOdb forums</a>.
540
</ul>
541
</body>
542
</html>