]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiDB/adodb/docs/tute.htm
Upgrade adodb
[SourceForge/phpwiki.git] / lib / WikiDB / adodb / docs / tute.htm
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\r
2 \r
3 <html>\r
4 <head>\r
5         <title>Tutorial: Moving from MySQL to ADODB</title>\r
6 </head>\r
7 \r
8 <body bgcolor=white>\r
9 <h1>Tutorial: Moving from MySQL to ADODB</h1>\r
10 \r
11 <pre>           You say eether and I say eyether, \r
12                 You say neether and I say nyther; \r
13                 Eether, eyether, neether, nyther - \r
14                 Let's call the whole thing off ! \r
15 <br>\r
16                 You like potato and I like po-tah-to, \r
17                 You like tomato and I like to-mah-to; \r
18                 Potato, po-tah-to, tomato, to-mah-to - \r
19                 Let's call the whole thing off ! \r
20 </pre>\r
21 <p>I love this song, especially the version with Louis Armstrong and Ella singing \r
22   duet. It is all about how hard it is for two people in love to be compatible \r
23   with each other. It's about compromise and finding a common ground, and that's \r
24   what this article is all about. \r
25 <p>PHP is all about creating dynamic web-sites with the least fuss and the most \r
26   fun. To create these websites we need to use databases to retrieve login information, \r
27   to splash dynamic news onto the web page and store forum postings. So let's \r
28   say we were using the popular MySQL database for this. Your company has done \r
29   such a fantastic job that the Web site is more popular than your wildest dreams. \r
30   You find that MySQL cannot scale to handle the workload; time to switch databases. \r
31 <p> Unfortunately in PHP every database is accessed slightly differently. To connect \r
32   to MySQL, you would use <i>mysql_connect()</i>; when you decide to upgrade to \r
33   Oracle or Microsoft SQL Server, you would use <i>ocilogon() </i>or <i>mssql_connect()</i> \r
34   respectively. What is worse is that the parameters you use for the different \r
35   connect functions are different also.. One database says po-tato, the other \r
36   database says pota-to. Oh-oh. \r
37 <h3>Let's NOT call the whole thing off</h3>\r
38 <p>A database wrapper library such as ADODB comes in handy when you need to ensure portability. It provides \r
39   you with a common API to communicate with any supported database so you don't have to call things off. <p>\r
40 \r
41 <p>ADODB stands for Active Data Objects DataBase (sorry computer guys are sometimes \r
42   not very original). ADODB currently supports MySQL, PostgreSQL, Oracle, Interbase, \r
43   Microsoft SQL Server, Access, FoxPro, Sybase, ODBC and ADO. You can download \r
44   ADODB from <a href=http://php.weblogs.com/adodb></a><a href="http://php.weblogs.com/adodb">http://php.weblogs.com/adodb</a>.\r
45 <h3>MySQL Example</h3>\r
46 <p>The most common database used with PHP is MySQL, so I guess you should be familiar \r
47   with the following code. It connects to a MySQL server at <i>localhost</i>, \r
48   database <i>mydb</i>, and executes an SQL select statement. The results are \r
49   printed, one line per row. \r
50 <pre><font color="#666600">$db = <b>mysql_connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;);\r
51 <b>mysql_select_db</b>(&quot;mydb&quot;,$db);</font>\r
52 <font color="#660000">$result = <b>mysql_query</b>(&quot;SELECT * FROM employees&quot;,$db)</font><code><font color="#663300">;\r
53 if ($result === false) die(&quot;failed&quot;);</font></code> \r
54 <font color="#006666"><b>while</b> ($fields =<b> mysql_fetch_row</b>($result)) &#123;\r
55  <b>for</b> ($i=0, $max=sizeof($fields); $i &lt; $max; $i++) &#123;\r
56                 <b>print</b> $fields[$i].' ';\r
57  &#125;\r
58  <b>print</b> &quot;&lt;br&gt;\n&quot;;\r
59 &#125;</font> \r
60 </pre>\r
61 <p>The above code has been color-coded by section. The first section is the connection \r
62   phase. The second is the execution of the SQL, and the last section is displaying \r
63   the fields. The <i>while</i> loop scans the rows of the result, while the <i>for</i> \r
64   loop scans the fields in one row.</p>\r
65 <p>Here is the equivalent code in ADODB</p>\r
66 <pre><b><font color="#666600"> include(&quot;adodb.inc.php&quot;);</font></b><font color="#666600">\r
67  $db = <b>NewADOConnection</b>('mysql');\r
68  $db-&gt;<b>Connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;mydb&quot;);</font>\r
69  <font color="#663300">$result = $db-&gt;<b>Execute</b>(&quot;SELECT * FROM employees&quot;);\r
70  </font><font color="#663300"></font><code><font color="#663300">if ($result === false) die(&quot;failed&quot;)</font></code><code><font color="#663300">;</font></code>  \r
71  <font color="#006666"><b>while</b> (!$result-&gt;EOF) &#123;\r
72         <b>for</b> ($i=0, $max=$result-&gt;<b>FieldCount</b>(); $i &lt; $max; $i++)\r
73                    <b>print</b> $result-&gt;fields[$i].' ';\r
74         $result-&gt;<b>MoveNext</b>();\r
75         <b>print</b> &quot;&lt;br&gt;\n&quot;;\r
76  &#125;</font> </pre>\r
77 <p></p>\r
78 <p>Now porting to Oracle is as simple as changing the second line to <code>NewADOConnection('oracle')</code>. \r
79   Let's walk through the code...</p>\r
80 <h3>Connecting to the Database</h3>\r
81 <p></p>\r
82 <pre><b><font color="#666600">include(&quot;adodb.inc.php&quot;);</font></b><font color="#666600">\r
83 $db = <b>NewADOConnection</b>('mysql');\r
84 $db-&gt;<b>Connect</b>(&quot;localhost&quot;, &quot;root&quot;, &quot;password&quot;, &quot;mydb&quot;);</font></pre>\r
85 <p>The connection code is a bit more sophisticated than MySQL's because our needs \r
86   are more sophisticated. In ADODB, we use an object-oriented approach to managing \r
87   the complexity of handling multiple databases. We have different classes to \r
88   handle different databases. If you aren't familiar with object-oriented programing, \r
89   don't worry -- the complexity is all hidden away in the<code> NewADOConnection()</code> \r
90   function.</p>\r
91 <p>To conserve memory, we only load the PHP code specific to the database you \r
92   are connecting to. We do this by calling <code>NewADOConnection(databasedriver)</code>. \r
93   Legal database drivers include <i>mysql, mssql, oracle, oci8, postgres, sybase, \r
94   vfp, access, ibase </i>and many others.</p>\r
95 <p>Then we create a new instance of the connection class by calling <code>NewADOConnection()</code>. \r
96   Finally we connect to the database using <code>$db-&gt;Connect(). </code></p>\r
97 <h3>Executing the SQL</h3>\r
98 <p><code><font color="#663300">$result = $db-&gt;<b>Execute</b>(&quot;SELECT * \r
99   FROM employees&quot;);<br>\r
100   if ($result === false) die(&quot;failed&quot;)</font></code><code><font color="#663300">;</font></code> \r
101   <br>\r
102 </p>\r
103 <p>Sending the SQL statement to the server is straight forward. Execute() will \r
104   return a recordset object on successful execution. You should check $result \r
105   as we do above.\r
106 <p>An issue that confuses beginners is the fact that we have two types of objects \r
107   in ADODB, the connection object and the recordset object. When do we use each?\r
108 <p>The connection object ($db) is responsible for connecting to the database, \r
109   formatting your SQL and querying the database server. The recordset object ($result) \r
110   is responsible for retrieving the results and formatting the reply as text or \r
111   as an array.\r
112 <p>The only thing I need to add is that ADODB provides several helper functions \r
113   for making INSERT and UPDATE statements easier, which we will cover in the Advanced \r
114   section. \r
115 <h3>Retrieving the Data<br>\r
116 </h3>\r
117 <pre><font color="#006666"><b>while</b> (!$result-&gt;EOF) &#123;\r
118    <b>for</b> ($i=0, $max=$result-&gt;<b>FieldCount</b>(); $i &lt; $max; $i++)\r
119            <b>print</b> $result-&gt;fields[$i].' ';\r
120    $result-&gt;<b>MoveNext</b>();\r
121    <b>print</b> &quot;&lt;br&gt;\n&quot;;\r
122 &#125;</font></pre>\r
123 <p>The paradigm for getting the data is that it's like reading a file. For every \r
124   line, we check first whether we have reached the end-of-file (EOF). While not \r
125   end-of-file, loop through each field in the row. Then move to the next line \r
126   (MoveNext) and repeat. \r
127 <p>The <code>$result-&gt;fields[]</code> array is generated by the PHP database \r
128   extension. Some database extensions do not index the array by field name. \r
129   To force indexing by name - that is associative arrays - \r
130   use the $ADODB_FETCH_MODE global variable. \r
131 <pre>\r
132         $<b>ADODB_FETCH_MODE</b> = ADODB_FETCH_NUM;\r
133         $rs1 = $db->Execute('select * from table');\r
134         $<b>ADODB_FETCH_MODE</b> = ADODB_FETCH_ASSOC;\r
135         $rs2 = $db->Execute('select * from table');\r
136         print_r($rs1->fields); // shows <i>array([0]=>'v0',[1] =>'v1')</i>\r
137         print_r($rs2->fields); // shows <i>array(['col1']=>'v0',['col2'] =>'v1')</i>\r
138 </pre>\r
139 <p>\r
140 As you can see in the above example, both recordsets store and use different fetch modes\r
141 based on the $ADODB_FETCH_MODE setting when the recordset was created by Execute().</p>\r
142 <h2>ADOConnection<a name="ADOConnection"></a></h2>\r
143 <p>Object that performs the connection to the database, executes SQL statements \r
144   and has a set of utility functions for standardising the format of SQL statements \r
145   for issues such as concatenation and date formats.</p>\r
146   \r
147 <h3>Other Useful Functions</h3>\r
148 <p><code>$recordset-&gt;Move($pos)</code> scrolls to that particular row. ADODB supports forward \r
149   scrolling for all databases. Some databases will not support backwards scrolling. \r
150   This is normally not a problem as you can always cache records to simulate backwards \r
151   scrolling. \r
152 <p><code>$recordset-&gt;RecordCount()</code> returns the number of records accessed by the \r
153   SQL statement. Some databases will return -1 because it is not supported. \r
154 <p><code>$recordset-&gt;GetArray()</code> returns the result as an array. \r
155 <p><code>rs2html($recordset)</code> is a function that is generates a HTML table based on the \r
156   $recordset passed to it. An example with the relevant lines in bold:\r
157 <pre>   include('adodb.inc.php'); \r
158    <b>include('tohtml.inc.php');</b> /* includes the rs2html function */\r
159    $conn = ADONewConnection('mysql'); \r
160    $conn-&gt;PConnect('localhost','userid','password','database');\r
161    $rs = $conn-&gt;Execute('select * from table');\r
162   <b> rs2html($rs)</b>; /* recordset to html table */ </pre>\r
163 <p>There are many other helper functions that are listed in the documentation available at <a href="http://php.weblogs.com/adodb_manual"></a><a href="http://php.weblogs.com/adodb_manual">http://php.weblogs.com/adodb_manual</a>. \r
164 <h2>Advanced Material</h2>\r
165 <h3>Inserts and Updates </h3>\r
166 <p>Let's say you want to insert the following data into a database. \r
167 <p><b>ID</b> = 3<br>\r
168   <b>TheDate</b>=mktime(0,0,0,8,31,2001) /* 31st August 2001 */<br>\r
169   <b>Note</b>= sugar why don't we call it off \r
170 <p>When you move to another database, your insert might no longer work.</p>\r
171 <p>The first problem is that each database has a different default date format. \r
172   MySQL expects YYYY-MM-DD format, while other databases have different defaults. \r
173   ADODB has a function called DBDate() that addresses this issue by converting \r
174   converting the date to the correct format.</p>\r
175 <p>The next problem is that the <b>don't</b> in the Note needs to be quoted. In \r
176   MySQL, we use <b>don\'t</b> but in some other databases (Sybase, Access, Microsoft \r
177   SQL Server) we use <b>don''t. </b>The qstr() function addresses this issue.</p>\r
178 <p>So how do we use the functions? Like this:</p>\r
179 <pre>$sql = &quot;INSERT INTO table (id, thedate,note) values (&quot; \r
180    . $<b>ID</b> . ','\r
181    . $db-&gt;DBDate($<b>TheDate</b>) .','\r
182    . $db-&gt;qstr($<b>Note</b>).&quot;)&quot;;\r
183 $db-&gt;Execute($sql);</pre>\r
184 <p>ADODB also supports <code>$connection-&gt;Affected_Rows()</code> (returns the \r
185   number of rows affected by last update or delete) and <code>$recordset-&gt;Insert_ID()</code> \r
186   (returns last autoincrement number generated by an insert statement). Be forewarned \r
187   that not all databases support the two functions.<br>\r
188 </p>\r
189 <h3>MetaTypes</h3>\r
190 <p>You can find out more information about each of the fields (I use the words \r
191   fields and columns interchangebly) you are selecting by calling the recordset \r
192   method <code>FetchField($fieldoffset)</code>. This will return an object with \r
193   3 properties: name, type and max_length. \r
194 <pre>For example:</pre>\r
195 <pre>$recordset = $conn-&gt;Execute(&quot;select adate from table&quot;);<br>$f0 = $recordset-&gt;FetchField(0);\r
196 </pre>\r
197 <p>Then <code>$f0-&gt;name</code> will hold <i>'adata'</i>, <code>$f0-&gt;type</code> \r
198   will be set to '<i>date'</i>. If the max_length is unknown, it will be set to \r
199   -1. \r
200 <p>One problem with handling different databases is that each database often calls \r
201   the same type by a different name. For example a <i>timestamp</i> type is called \r
202   <i>datetime</i> in one database and <i>time</i> in another. So ADODB has a special \r
203   <code>MetaType($type, $max_length)</code> function that standardises the types \r
204   to the following: \r
205 <p>C: character and varchar types<br>\r
206   X: text or long character (eg. more than 255 bytes wide).<br>\r
207   B: blob or binary image<br>\r
208   D: date<br>\r
209   T: timestamp<br>\r
210   L: logical (boolean)<br>\r
211   I: integer<br>\r
212   N: numeric (float, double, money) \r
213 <p>In the above date example, \r
214 <p><code>$recordset = $conn-&gt;Execute(&quot;select adate from table&quot;);<br>\r
215   $f0 = $recordset-&gt;FetchField(0);<br>\r
216   $type = $recordset-&gt;MetaType($f0-&gt;type, $f0-&gt;max_length);<br>\r
217   print $type; /* should print 'D'</code> */\r
218 <p> \r
219 <p><b>Select Limit and Top Support</b> \r
220 <p>ADODB has a function called $connection->SelectLimit($sql,$nrows,$offset) that allows\r
221 you to retrieve a subset of the recordset. This will take advantage of native\r
222 SELECT TOP on Microsoft products and SELECT ... LIMIT with PostgreSQL and MySQL, and\r
223 emulated if the database does not support it.\r
224 <p><b>Caching Support</b> \r
225 <p>ADODB allows you to cache recordsets in your file system, and only requery the database\r
226 server after a certain timeout period with $connection->CacheExecute($secs2cache,$sql) and \r
227 $connection->CacheSelectLimit($secs2cache,$sql,$nrows,$offset).\r
228 <p><b>PHP4 Session Handler Support</b> \r
229 <p>ADODB also supports PHP4 session handlers. You can store your session variables \r
230   in a database for true scalability using ADODB. For further information, visit \r
231   <a href="http://php.weblogs.com/adodb-sessions"></a><a href="http://php.weblogs.com/adodb-sessions">http://php.weblogs.com/adodb-sessions</a>\r
232 <h3>Commercial Use Encouraged</h3>\r
233 <p>If you plan to write commercial PHP applications that you want to resell, you should consider ADODB. It has been released using the lesser GPL, which means you can legally include it in commercial applications, while keeping your code proprietary. Commercial use of ADODB is strongly encouraged! We are using it internally for this reason.<p>\r
234 \r
235 <h2>Conclusion</h2>\r
236 <p>As a thank you for finishing this article, here are the complete lyrics for \r
237   <i>let's call the whole thing off</i>.<br>\r
238   <br>\r
239 <pre>\r
240    Refrain \r
241 <br>\r
242                 You say eether and I say eyether, \r
243                 You say neether and I say nyther; \r
244                 Eether, eyether, neether, nyther - \r
245                 Let's call the whole thing off ! \r
246 <br>\r
247                 You like potato and I like po-tah-to, \r
248                 You like tomato and I like to-mah-to; \r
249                 Potato, po-tah-to, tomato, to-mah-to - \r
250                 Let's call the whole thing off ! \r
251 <br>\r
252 But oh, if we call the whole thing off, then we must part. \r
253 And oh, if we ever part, then that might break my heart. \r
254 <br>\r
255                 So, if you like pajamas and I like pa-jah-mas, \r
256                 I'll wear pajamas and give up pa-jah-mas. \r
257                 For we know we \r
258                 Need each other, so we \r
259                 Better call the calling off off. \r
260                 Let's call the whole thing off ! \r
261 <br>\r
262    Second Refrain \r
263 <br>\r
264                 You say laughter and I say lawfter, \r
265                 You say after and I say awfter; \r
266                 Laughter, lawfter, after, awfter - \r
267                 Let's call the whole thing off ! \r
268 <br>\r
269                 You like vanilla and I like vanella, \r
270                 You, sa's'parilla and I sa's'parella; \r
271                 Vanilla, vanella, choc'late, strawb'ry - \r
272                 Let's call the whole thing off ! \r
273 <br>\r
274 But oh, if we call the whole thing off, then we must part. \r
275 And oh, if we ever part, then that might break my heart. \r
276 <br>\r
277                 So, if you go for oysters and I go for ersters, \r
278                 I'll order oysters and cancel the ersters. \r
279                 For we know we \r
280                 Need each other, so we \r
281                 Better call the calling off off. \r
282                 Let's call the whole thing off ! \r
283   </pre>\r
284 <p><font size=2>Song and lyrics by George and Ira Gershwin, introduced by Fred Astaire and Ginger Rogers\r
285 in the film "Shall We Dance?"  </font><p>\r
286 <p>\r
287 (c)2001-2002 John Lim.\r
288 \r
289 </body>\r
290 </html>\r