1
0

tute.htm 15 KB

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